Angular 同名元素绑定方式

Angular way of binding elements of the same name together

在 angular 中,我有一个复选框列表,这些复选框都绑定到我从 json:

中获得的布尔值
<div ng-repeat="err in rec.errorList"><input type="checkbox" ng-model="err.ignore" name="{{err.errorCode}}" ng-value="err.errorCode"  check-all="{{err.errorCode}}" /></div>

但是与此同时,我在选中其中一个复选框时尝试选中所有具有相同名称的复选框!

以 angular 方式做到这一点的最佳方法是什么?我的意思是有没有一种方法可以将所有这些具有相同 Name 属性的复选框绑定在一起? 我试着写了一个指令,像这样,但不知道我应该如何继续:

.directive("checkAll", function(){
    return {
        link: function(scope, element, attr){
            element.bind('change', function(){
                var errorCode = attr["checkAll"];
                var elms = scope.errorCode;             
            })
        }
    }
})

这是我真正想做的事 http://plnkr.co/edit/sLXGlXRh9vu7FETDmJd1?p=preview 我可以有很多列表,而我想要的是每当我单击这些复选框之一时,用相同的错误代码更新所有复选框,也许不需要再次循环所有这些错误列表。

您可以简单地为每个名称使用相同的 ng-model 来做到这一点。

这看起来像这样:

控制器

$scope.errorList = [{errorCode:1},{errorCode:2},
{errorCode:1},{errorCode:3},{errorCode:1},{errorCode:1},
{errorCode:2},{errorCode:1},{errorCode:3},{errorCode:3}];
$scope.checkboxByName = {};

查看

  <div ng-repeat="err in errorList">
    <input type="checkbox" ng-model="checkboxByName[err.errorCode]">
  </div>

如果你真的需要每个错误的 error.ignore var,你可以添加这个函数:

 $scope.updateIgnore = function(){
  angular.forEach($scope.errorList, function(error){
   error.ignore = $scope.checkboxByName[error.errorCode];
  })
 }

并对所有输入进行 ng-change :

ng-change="updateIgnore()"

这里是 plunker 显示完整的实现

希望对您有所帮助。