AngularJs $watch doesn't bind

AngularJs $watch doesn't bind

本文关键字:bind watch doesn AngularJs      更新时间:2023-09-26

我试图用输入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