AngularJs $watch doesn't bind
AngularJs $watch doesn't bind
我试图用输入List管理一个数组。
我希望用户只有在最后一个不为空的情况下才能添加项目。我不明白为什么我不能绑定数组的更改。
我在html中尝试了完全相同的代码,但效果并不好。
我哪里错了?
下面是一个plunker:http://plnkr.co/edit/IpivgS5TWNQFFxQlRloa?p=preview
HTML
<div class="row" ng-repeat="radio in radioList track by $index">
<p class="input-group">
<input type="text" class="form-control" ng-model="radio.code" placeholder="enter sthg" ng-required="true" />
<span class="input-group-btn">
<button type="button" class="btn btn-default" ng-click="removeRadioList($index);"><i class="glyphicon glyphicon-remove">X</i>
</button>
</span>
</p>
</div>
</div>
<div class="col-xs-3">
<button class="btn btn-primary" ng-click="addRadioList();" ng-disabled="disableAddRadio">Ajouter un cliché</button>
{{radioList[radioList.length-1] }}
</div>
**JS**
$scope.radioList = [{
code: ''
}];
$scope.addRadioList = function() {
$scope.radioList.push({
'code': ''
});
}
$scope.removeRadioList = function(i) {
$scope.radioList.splice(i, 1);
}
$scope.$watch('radioList', function(newValue, oldValue) {
console.log('change');
$scope.disableAddRadio = (angular.isDefined($scope.radioList[$scope.radioList.length - 1].code) || $scope.radioList.length < 1);
});
数组的正确监视是:
$scope.$watchCollection
然后,您应该检查进入函数的newVal,以便应用一些逻辑(作为数组)。示例:
if ( newValue.length > 1 && newValue[newValue.length-2].code === undefined ) $scope.disableAddRadio = true;
在这里你的plunker更新:http://plnkr.co/edit/tf2SSoWNaXSXaZqvRkQT?p=preview
相关文章:
- 直接在函数声明上使用function.prototype.bind
- 显示&作为&在jsp中使用angularjs而不使用ng-bind-html
- angularjs$watch获取已更改数组项的索引
- 在控制器上使用“$watch”时,为什么不更新此隐藏字段
- 指令$watch不会在更改时触发
- 如何使jQuery的“bind”或“on”事件处理程序幂等
- 角度范围$watch()等效于Rivets.js
- 强制 $scope.$watch 只开火一次
- AngularJS ng src不会在$rootScope上使用$watch进行更新
- Replacing jQuery.bind with jQuery.on
- 让ng更改等待$watch完成
- 无法使用.bind更改分配给此对象的值
- 你什么时候用_.bind和_.bindAll
- jQuery change()和bind(“change”)不起作用
- $scope变量发生更改时未触发Angular$watch
- 更改值时未触发$watch
- Angular 1.4解析ng-bind-html的内容
- 在使用AngularJS时,我应该在$apply和$watch之间使用哪个
- Javascript:函数bind.click&对于每个复选框
- AngularJs $watch doesn't bind