简体   繁体   中英

AngularJS : changing a model in a $watch function

I have a directive like so:

.directive('checkMeIfApplyAll', function($timeout) {
    return {
        link: function(scope, element, attrs) {
            scope.$watch(attrs.checkMeIfApplyAll, function(value) {
                debugger;
                if(value === true) {
                    element.prop('checked', true);
                }
                else {
                    element.prop('checked', false);
                }
            });
        }
    };

And here is the corresponding html snippet:

<tr 'ng-repeat'='permission in category.permissions'>
  <input type='checkbox' 'ng-model'='permission.show' 'check-me-if-apply-all'= 'category.allChecked'>
</tr>

Notice that if the value of category.allChecked changes, the watcher function is triggered. As you can see, if that value is true, then using jquery, I can check the checkbox. However, as you can see in the html snippet, each checkbox has been assigned a model eg 'permission.show'. And what I really want to do is change the model value in the directive and not simply the property of element. How can I access the ng-model attribute of the element inside of the watch function?

Let's go simple. I think you don't need directive for this and $watch should not be overused.

<tr ng-repeat='permission in category.permissions'>
  <input type='checkbox' ng-model='permission.show' 
    ng-checked='category.allChecked'>
</tr>

To access model in the directive, just access scope.category.permissions[INDEX].show

I haven't tested the above since there is no plnkr provided.

You can use ngModelController :

.directive('checkMeIfApplyAll', function($timeout) {
    return {
        require: 'ngModel',
        link: function(scope, element, attrs, ngModel) {
            scope.$watch(attrs.checkMeIfApplyAll, function(value) {
                debugger;
                if(value === true) {
                    element.prop('checked', true);
                }
                else {
                    element.prop('checked', false);
                }

                // Set value like this
                ngModel.$setViewValue(value);
            });
        }
    };

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM