gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 11:08:07 24 4
gpt4 key购买 nike

最近我一直在使用 ControllerAs 语法,但我不确定如何能够在 $watch 中从 Controller 更改模型。

我的 watch 是这样的:

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

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

到目前为止,我已经尝试过 $scope.selectedItemsselectedItemsthis.selectedItems,但它不起作用。我也将其包装在 angular.bind 中,但效果不佳。

有人也遇到这个问题并能提供解决方案吗?

编辑

我正在使用 checklist-model 指令,因此 ngRepeat 中的模型为 checklist-model="pages.selectedItems"allItemsSelected 变量是复选框的模型。如果它是 true,我必须循环遍历我的数据并将 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 代替 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);
}
});
}]);

关于javascript - AngularJS 类中的引用属性(ControllerAs 语法),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27744779/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com