angularjs:forEach in ng-click

时间:2018-01-03 21:06:20

标签: angularjs for-loop

我在实施"选择全部"时遇到问题简单列表的功能:

控制器:

$scope.numbers = [{v:1},{v:2},{v:3},{v:4}];

模板:

<a href="" ng-click="numbers.forEach(function(v) {v.selected=true;});">select All</a>
<p ng-repeat='n in numbers'>
  <label>
    <input type="checkbox" ng-model="n.selected">
    Label: {{ n.v }}
  </label>
</p>

似乎角度解析器无法处理ng-click语句:

  

错误:[$ parse:syntax]
  (...)
  在关系(angular.min.js:234)
     在r.equality(angular.min.js:233)
     在r.logicalAND(angular.min.js:233)&#34;&lt; a href =&#34;&#34; ng-click =&#34; numbers.forEach(function(v){v.selected = true;});&#34;&gt;&#34;

Plunker演示: https://plnkr.co/edit/6OZP02SZ5ZYa0iO4PBY3?p=preview

我可以在html模板中实现它还是必须使用控制器方法?

修改:控制器方法运行正常,我仍然感兴趣为什么就地代码无法解析?

2 个答案:

答案 0 :(得分:3)

如下所示,numbers.forEach(function(v) {v.selected=true;});错误会引发错误,因为数字没有forEach menthod而匿名函数无效ng-click

这是执行全选

的最佳方式
<div ng-app="myApp" ng-controller="myCtrl">
  <label>
        <input type="checkbox" ng-model="all">
        Select All
      </label>
    <p ng-repeat='n in numbers'>
      <label>
        <input type="checkbox" ng-checked="all">
        Label: {{ n.v }}
      </label>
    </p>
</div>

var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
  $scope.numbers = [{v:1},{v:2},{v:3},{v:4}];
});

https://fiddle.jshell.net/mspj0z65/1/

<强> HTML

<div ng-app="myApp" ng-controller="myCtrl">
  <a href="" ng-click="loop">select All</a>
    <p ng-repeat='n in numbers'>
      <label>
        <input type="checkbox" ng-model="n.selected">
        Label: {{ n.v }}
      </label>
    </p>
</div>

Angular script:

var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
  $scope.numbers = [{v:1},{v:2},{v:3},{v:4}];
  $scope.loop = function(){
    angular.forEach(numbers, function(v) {
      v.selected=true;
    });
  }
});

https://fiddle.jshell.net/mspj0z65/

答案 1 :(得分:0)

最好在控制器上实现方法:

$scope.selectAll=function() {
        $scope.numbers.forEach(function(v) {
          v.selected=true
        });
      }

并在视图中使用ng-click="selecAll()"

让您的视图尽可能简单,并使代码更易读,易于使用 了解第三方或将来拥有。

我建议您查看John Papa Angular style guide