AngularJS - Trouble with $watch
AngularJS - Trouble with $watch
如果用户是我的商店网站上"高"组的成员,我正在尝试删除产品 SKU 上的"红色"和"蓝色"下拉列表选项。我想出的代码如下,但只能部分工作;唯一有效的是窗口警报。现在,如果我删除有关查找用户组的逻辑,那么它确实有效,但是用户必须首先设置颜色下拉列表的值。
function SpecController($scope) {
angular.forEach($scope.user.Groups, function (g) {
if (g.Name == "High") {
alert('You are in the correct group!');
$scope.$watch('user.Groups.Name', function (val) {
if (!val) return;
if (val == "High") {
$scope.Variant.Specs.Color.Options = $scope.Variant.Specs.Color.Options.filter(function (item) {
return item.Value !== 'Red' && item.Value !== 'Blue';
});
}
});
}
});
}
你的目标是在Groups
物体的每个Group
内的groupName
上放一块手表。因此,您当前的观察者指向实际上不存在user.Groups.Name
。如果你想让你当前的代码工作,那么你可以在放置$watch
时使用索引
法典
function SpecController($scope) {
angular.forEach($scope.user.Groups, function (g,index) { //added index param here
if (g.Name == "High") {
alert('You are in the correct group!');
//used that index param here to put watch on each group.
$scope.$watch('user.Groups['+ index + '].Name', function (val) {
if (!val) return;
if (val == "High") {
$scope.Variant.Specs.Color.Options = $scope.Variant.Specs.Color.Options.filter(function (item) {
return item.Value !== 'Red' && item.Value !== 'Blue';
});
}
});
}
});
}
注意
当您拥有超过 1000
groups
时,此解决方案会搞砸user.Groups
,观察者数量将增加,结果将是 应用程序将运行缓慢。
相关文章:
- Fighting with FRP
- issue with FB.Event.subscribe
- geolocation-marker.js conflict with markerclusterer.js
- Angular 2.0 with JavaScript or TypeScript?
- 为什么不推荐使用“with”?是否有更好或其他方法可以“下降”到对象的命名空间
- WebComponentsJS with IE10
- 指令的模板必须只有一个根元素:With restrict E&替换true
- timeago.js with datatable and PHP
- Ajax and Json with Rails
- errors with Javascript try catch
- how to split a string with ','
- Understanding Javascript scope with "var that = this&qu
- angularjs$watch获取已更改数组项的索引
- Architecture for CPU intensive tasks with NodeJS & Socke
- Issue With Angular $scope.Watch
- 使用`this$watch`而不是'scope$手表`with'控制器组件'
- 如何在数组中独立的多个对象上使用Angular的$watch with equal
- Gulp watch with browserSync
- AngularJS - Trouble with $watch
- ng-model with $watch只响应完整字符串(AngularJS)