AngularJS:在$watch函数中修改模型

AngularJS : changing a model in a $watch function

本文关键字:修改 模型 函数 watch AngularJS      更新时间:2023-09-26

我有一个这样的指令:

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

下面是相应的html片段:

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

注意,如果category的值。allChecked变化,则触发监视功能。如您所见,如果该值为真,那么使用jquery,我就可以选中复选框。然而,正如你在html片段中看到的,每个复选框都被分配了一个模型,例如:"permission.show"。我真正想做的是改变指令中的model值,而不仅仅是元素的属性。如何访问watch函数内部元素的ng-model属性?

你可以使用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);
            });
        }
    };

让我们简单点。我认为你不需要指令,$watch不应该被过度使用。

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

要访问指令中的模型,只需访问scope.category.permissions[INDEX].show

由于没有提供plnkr,所以我没有测试上面的