I am attempting to replicate the functionality of the ng-change attribute within a directive without making changes to the HTML (thus excluding the use of the ng-change property).
After examining the Angular source code for the ngChange
directive, I have created a directive that functions as follows:
(Essentially, this directive involves calling the blur()
method on a select
field when the model
is altered)
.directive('blurOnChangeFix', ['$timeout',
function($timeout) {
return {
restrict: 'AEC',
require: 'ngModel',
link: function($scope, element, attr, ngModel) {
// automatically blur element on ngModel change
ngModel.$viewChangeListeners.push(function() {
$timeout(function() { // IE bug fix
$(element).blur();
}, 100);
});
}
};
}
]);
Implementing it as follows:
<select
id="test"
ng-options="option for option in ['test1', 'test2'] track by option"
class="form-control"
ng-model="form.test"
ng-required="true"
blur-on-change-fix
></select>
However, is this the optimal solution? Are there alternative methods to achieve the same result? What about using scope.change()
?
Thank you