在angularjs ng-repeat中动态地向对象添加属性

时间:2017-01-02 05:08:32

标签: html angularjs angularjs-ng-repeat

我有一个对象列表,并使用ng-repeat迭代该列表以生成表格行。每个td都包含源名称和复选框。我想将复选框与列表中不可用的属性绑定。怎么可能?列表是这样的: -

scope.reasons = [
        {sourceName:'Lack of rainfall'},
        { sourceName: 'Change in land use' },
        {sourceName:'Change in Land Cover'}
        ];

,HTML代码就是这样: -

<table>
  <tr ng-repeat="source in reasons">
    <td>{{source.sourceName}}</td>
    <td><input type="checkbox" ng-checked="source.postAdequate"></td>
  </tr>
</table>

4 个答案:

答案 0 :(得分:1)

您可以使用ng-model属性执行此操作,ng-change仅用于检查更改检测。

<table>
    <tr ng-repeat="source in reasons">
      <td>{{source.sourceName}}</td>
      <td>
        <input type="checkbox" ng-model="source.postAdequate" ng-change="changeDet()">
      </td>
    </tr>
  </table>

Demo Fiddle

希望这有帮助

答案 1 :(得分:1)

试试这个:

<input type="checkbox" ng-model="source.postAdequate">

点击此处jsfiddle链接:

https://jsfiddle.net/avnesh2/5cpm48tc/2/
  

但是只有点击才会添加source.postAdequate: true/false,保持对象保持不变。

因此,如果您想在source.postAdequate: true/false之前添加$scope.reasons,只能添加.k-input{ height: 2.214em; line-height: 2.214em; padding: .177em 0; text-indent: .8em; border: 0; margin: 0; } .custom_parent .k-input{ height:auto !Important; }

希望这会对你有所帮助。

答案 2 :(得分:0)

使用ng-model代替ng-checked会在复选框更改时在内部添加属性

<input type="checkbox" ng-model="source.postAdequate"></td>

如果必须在所有对象上具有该属性,则迭代该数组并添加它

scope.reasons.forEach(function(item){
   item.postAdequate = false
})

答案 3 :(得分:0)

是否可以将范围对象循环一次以初始设置postAdequate:false表示所有项目。然后在checkbox ng-model中绑定该对象。

        angular.forEach($scope.reasons, function(e,i){
          e.postAdequate = false;
        });

html代码

<table>
<tr ng-repeat="source in reasons">
<td>{{source.sourceName}}</td>
<td>
<input type="checkbox" ng-model="source.postAdequate" ng-click="clickfunction(source.postAdequate)">
</td></tr>
</table>