简体   繁体   中英

AngularJs $watch doesn't bind

I try to manage an array with an input List.

I'd like the user to be able to add an item only if the last one is not empty. I don't understand why I can't bind the change of the array.

I tried the same kind of code completely in the html, but doesn't work better.

Where am I wrong ?

Here is a 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);

});

The correct watch for an array is:

 $scope.$watchCollection

Then you should check the newVal coming into the function in order to apply some logic (coming as an array). Example:

  if ( newValue.length > 1 && newValue[newValue.length-2].code === undefined )  $scope.disableAddRadio = true;

Here your plunker updated: http://plnkr.co/edit/tf2SSoWNaXSXaZqvRkQT?p=preview

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM