javascript - AngularJs $watch 没有绑定(bind)

标签 javascript angularjs scope

我尝试使用输入列表管理数组。

我希望用户仅当最后一项不为空时才能够添加一项。我不明白为什么我无法绑定(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

关于javascript - AngularJs $watch 没有绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26781526/

相关文章:

angularjs - Angular JS Controller 查看绑定(bind)在窗口大小调整时未更新

javascript - instanceof,范围和对象

javascript - 将复选框存储在本地存储中

javascript - Angular-Chart-JS - 根据点范围具有不同填充颜色的折线图

css - 与 AngularJS 绑定(bind)时,内联宽度在 IE 中不起作用

javascript - 在指令中,ng-click 多次触发 angularjs

c - 编译器或处理器在运行时如何区分静态局部变量?

ruby - ruby 中各种变量范围之间的区别

javascript - 如何从具有 chrome 扩展名的事件选项卡中获取段落?

javascript - JS opacity - 为什么这在 jsfiddle 上有效但在实时环境中无效?