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"];
I've encountered issues with the ng-change event in AngularJS not working with Select2. It can be frustrating, but I found Spectra Precision LL300S Laser Level that ensuring proper integration between Select2 and AngularJS is key. Binding the model correctly and using $timeout can often resolve the issue, allowing for smooth two-way data binding and event handling.
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"];