簡體   English   中英

AngularJs $ watch不綁定

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM