AngularJS类中的引用属性(ControllerAs语法)

Reference property in AngularJS class (ControllerAs syntax)

本文关键字:ControllerAs 语法 属性 引用 AngularJS      更新时间:2023-09-26

最近我一直在使用 ControllerAs 语法,但我不确定如何在$watch内从我的控制器更改模型。

我的手表是这样的:

$scope.$watch(angular.bind(this, function () {
    return this.allItemsSelected;
}), function (value) {
    //
})

在我看来,我得到了一个名为pages.selectedItems的模型。 pages是我PagesController的别名。

到目前为止,我已经尝试了$scope.selectedItemsselectedItemsthis.selectedItems,但它不起作用。我也把它包在angular.bind里,但效果不佳。

有人也有这个问题,可以提供解决方案吗?

EDIT

我正在使用 checklist-model 指令,因此 ngRepeat 中的模型checklist-model="pages.selectedItems" .allItemsSelected变量是复选框中的模型。如果它是真的,我必须遍历我的数据并将 id 添加到selectedItems数组中。

请看一下下面的内容,我认为它应该与您正在尝试做的事情相匹配。

请注意,您通常需要对传递给$scope.$watch()的两个函数使用 angular.bind()

angular.module("myModule", ['checklist-model'])
.controller("MyController", ["$scope", function MyController($scope) {
    this.options = ["hello", "goodbye", "bonsoir", "bonne nuit"];
    $scope.$watch(angular.bind(this, function () {
        return this.selectAll;
    }), 
    angular.bind(this, function (value) {
        if (value) {
            this.selectedOptions = angular.copy(this.options);
        }
    }));
}]);
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.10/angular.min.js"></script>
<script src="//vitalets.github.io/checklist-model/checklist-model.js"></script>
<div ng-app="myModule" ng-controller="MyController as me">
  <div ng-repeat="item in me.options">
    <input type="checkbox" checklist-model="me.selectedOptions" 
           checklist-value="item" /> {{item}}
  </div>
  <div>
    <input type="checkbox" ng-model="me.selectAll" /> Select all
  </div>
  <div ng-repeat="opt in me.selectedOptions">{{opt}}</div>
</div>

编辑:使用 angular.bind() 的另一种方法是将this分配给匿名函数之外的变量,然后使用它代替这些函数中的this

angular.module("myModule", ['checklist-model'])
.controller("MyController", ["$scope", function MyController($scope) {
    var self = this;
    this.options = ["hello", "goodbye", "bonsoir", "bonne nuit"];
    $scope.$watch(function () {
        return self.selectAll;
    }, function (value) {
        if (value) {
            self.selectedOptions = angular.copy(self.options);
        }
    });
}]);