event ng-change of angularjs not working select2
HTML
<select class="form-select form-select-solid" select2 ng-model="objAssign_SystemUser_Project.ProjectID" ng-change="getList(objAssign_SystemUser_Project.ProjectID)">
<option value="-1">Chá»n dá»± án</option>
<option ng-repeat="item in listProject" value="{{item.ProjectID}}">{{item.ProjectName}}</option>
</select>
Controller of Angularjs
$scope.getList = $async(async (projectID) => {
console.log(projectID)
});
Directive
const select2 = ($timeout, $compile) => {
return {
restrict: 'A',
link: function (scope, element, attrs) {
let initialLoad = true;
$timeout(() => {
const { hideSearch } = attrs;
if (!isNullOrEmpty(hideSearch) && hideSearch == "true") {
$(element).select2({
minimumResultsForSearch: Infinity
});
}
else {
$(element).select2();
}
element.select2Initialized = true;
}, 500);
scope.$watch(attrs.ngModel, function (newVal, oldVal) {
if (newVal !== oldVal) {
$(element).trigger('change');
}
});
$(element).on('change.select2', function () {
$timeout(() => {
const selectedValue = $(element).val();
scope.$eval(attrs.ngModel + "='" + selectedValue + "'");
if (!initialLoad && attrs.ngChange) {
//scope.$eval(attrs.ngChange);
}
// Äặt initialLoad thành false sau khi gá»i ngChange
initialLoad = false;
})
});
}
}
}
select2.$inject = ["$timeout", "$compile"];
Replies (1)
Hi Tan Nguyen
The issue might be due to how the select2 plugin handles changes and how AngularJS tracks model changes.
To fix this, ensure that ng-change is explicitly triggered in your directive when the select2 selection changes. You can modify your directive as follows:
Modify the change.select2 event listener: Ensure that ng-change is evaluated when a change occurs.
Trigger $apply to notify Angular of changes.
const select2 = ($timeout, $compile) => {
return {
restrict: "A",
link: function (scope, element, attrs) {
let initialLoad = true;
$timeout(() => {
const { hideSearch } = attrs;
if (hideSearch === "true") {
$(element).select2({
minimumResultsForSearch: Infinity
});
} else {
$(element).select2();
}
element.select2Initialized = true;
}, 500);
scope.$watch(attrs.ngModel, function (newVal, oldVal) {
if (newVal !== oldVal) {
$(element).trigger("change");
}
});
$(element).on("change.select2", function () {
$timeout(() => {
const selectedValue = $(element).val();
scope.$eval(attrs.ngModel + "="" + selectedValue + """);
if (!initialLoad && attrs.ngChange) {
scope.$apply(() => {
scope.$eval(attrs.ngChange);
});
}
initialLoad = false;
});
});
}
}
}
select2.$inject = ["$timeout", "$compile"];