Question

I'm trying to simulate the ng-change attribute in a directive without modifying the HTML (so without the ng-change property).

Looking at angular source code of the ngChange directive, my directive works and looks like this : (Basically in this directive, I need to blur() a select field when model change)

.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);
                });
            }
        };
    }
]);

applying it with :

<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>

But Is it the right solution ? isn't there another way to do this ? What about scope.change() ?

Thanks

Was it helpful?

Solution

If I understand you correctly, you are looking for doing a $watch on your model; eg:

link: function($scope, element, attr, ngModel) {
    $scope.$watch(attr.ngModel,function(newVal,oldVal) {
        element.blur();
    })

You stated that you wanted to do something when the model changed, so this is the usage of the $watch.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top