angular foreach更新对象属性

时间:2016-05-04 09:26:28

标签: arrays angularjs foreach

所以使用角度foreach如下

        $scope.section = [{
      "id": 1,
      "name": "name1",
      "value": "foo1"
    },
    {
      "id": 2,
      "name": "name 2",
      "value": "foo2"
    }]

    angular.forEach(section, function(item, key) {
        if(item.value)  {
            item.value = 'Some New value'
            }
    });

由于某些原因它不起作用加上如果我试图操纵我得到关于重复值的错误

3 个答案:

答案 0 :(得分:3)

转换此

angular.forEach(section, function(item, key) {

到此

angular.forEach($scope.section, function(item, key) {

DEMO

答案 1 :(得分:2)

这项工作对我来说,我只是在forEach上添加scope.section

 $scope.section = [{
      "id": 1,
      "name": "name1",
      "value": "foo1"
    },
    {
      "id": 2,
      "name": "name 2",
      "value": "foo2"
    }]
angular.forEach($scope.section, function(item, key) {
    if(item.value)  {
        item.value = 'Some New value';
        console.log('new value');
        }
});

答案 2 :(得分:1)

您忘记在对象中添加$scope



var jimApp = angular.module("mainApp",  []);

jimApp.controller('mainCtrl', function($scope){
  
  $scope.section = [{ "id": 1, "name": "name1", "value": "foo1" },
                    { "id": 2, "name": "name 2", "value": "foo2" }];

    angular.forEach($scope.section, function(item, key) {
        if(item.value)  {
            item.value = 'Some New value'
        }
    });

  
});

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="mainApp" ng-controller="mainCtrl">
  {{section}}
</div>
&#13;
&#13;
&#13;