[英]AngularJs $watch doesn't bind
我尝试使用输入列表管理数组。
我希望用户仅在最后一个不为空的情况下才能添加一项。 我不明白为什么我不能绑定数组的更改。
我在html中完全尝试了相同类型的代码,但效果不佳。
我哪里错了?
这是一个小矮人: 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;
在这里,您的朋克更新了: http ://plnkr.co/edit/tf2SSoWNaXSXaZqvRkQT?p=preview
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.