简体   繁体   English

如何在ng-repeat使用的数组的每一行上将字段设置为false?

[英]How can I set a field on every row in an array used by ng-repeat to false?

I have this code for a table: 我有一个表的代码:

<table>
   <tr data-ng-class="{clicked: row.current == true}"
       data-ng-click="grid.view.forEach(function(object) { object.current = false; }); row.current = true"
       data-ng-repeat="row in grid.view = (grid.data | filter:isInRange">
   <td>{{ row.id }}</td>
   <td>{{ row.current }}

I am getting a syntax error on the ng-click row. 我在ng-click行上收到语法错误。 I'm not sure if I am using the correct syntax. 我不确定我使用的语法是否正确。 What I have is that each row of the array contains fields and some objects. 我所拥有的是数组的每一行都包含字段和一些对象。 I want to set the field current to false for all rows and then set to true for the one I click on. 我想将所有行的字段当前设置为false,然后将我单击的字段设置为true。 If I omit the first javascript statement of the click it does not give a syntax error. 如果我省略了单击的第一个javascript语句,则不会出现语法错误。

Define the function in your controller (or where ever else you like), then pass its name to your markup: 在您的控制器(或您喜欢的任何地方)中定义函数,然后将其名称传递给您的标记:

$scope.x = function(){
  // do some stuff
}

// in markup
<tr ng-click="x()">

I strongly recommend to abstract such things in your markup as far as possible. 我强烈建议尽可能在标记中抽象这些内容。 Will be a lot more maintainable in the future. 将来会更加可维护。

The code inside ng-click and ng-repeat are angular expressions and repectively angular repeat expressions , not arbitrary java script code. ng-clickng-repeat中的代码是角度表达式 ,分别是角度重复表达式 ,而不是任意的Java脚本代码。 Angular expressions are a subset of JavaScript and processed by angular's $parse service. Angular表达式是JavaScript的子集,并由angular的$ parse服务处理。 The expression syntax isn't really well documented unfortunately, but afaik and after checking parse.js in the angular source, definition of functions (the function(){ ...} part in your ng-click )) is not supported. 不幸的是,表达式语法并没有得到很好的记录,但是afaik以及在角度源中检查parse.js之后,不支持function(){ ...}定义( ng-clickfunction(){ ...}部分)。 I also think that the assignment ( = in your ng-repeat ) is not really supported. 我也认为该赋值( =在您的ng-repeat )实际上不受支持。

In those cases, it is better to just call a function that is defined in the scope as pointed out in the answer by @Sprottenwels. 在这些情况下,最好只调用@Sprottenwels答案中指出的范围内定义的函数。

On a side note, rather than having a boolean flag row.current in each row, it might be simpler to have a single variable $scope.selectedRow in your scope pointing to the selected row. row.currentrow.current在每行中都具有一个布尔标志row.current$scope.selectedRow在您的作用域中使用单个变量$scope.selectedRow指向所选行。 Your code then becomes something like: 然后,您的代码将变为:

<tr data-ng-class="{clicked: row == selectedRow}"
    data-ng-click="selectRow(row)"
    data-ng-repeat="row in grid.data | filter:isInRange">

// in the controller
$scope.selectRow = function(row) {
    $scope.selectedRow = row;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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