从 REST 扩充 JSON 关于 AngularJS 中的额外数据

Augmenting JSON from REST about additional data within AngularJS

编辑(解决方案):http://plnkr.co/edit/SjzpmQqMPuOCvcdZn5bV?p=preview

我从 REST-API:

获取以下数据
[
  {
    "a": "foo"
  },
  {
    "a": "bar"
  }
]

但需要:

 [
  {
    "a": "foo",
    "activated": false
  },
  {
    "a": "bar",
    "activated": true
  }
]

我怎么能在 angular 内做到这一点,我主要是如何添加一些新属性,以便我可以对它们的变化做出反应,可能是一种新的样式。

第二个问题:或者我可能需要以下转换:

{
  "a": {
    "foo": true,
    "bar": false
  }
}

是否有 "Angular-way" 可以做到这一点?我必须使用 lodash、underscore 等库吗?

array[1].c = "Michael Jackson";
array[1].d = ["Thriller..."]

array[0].c乔治·迈克尔...

您可以使用underscorejs's extend方法。

http://jsfiddle.net/2676saju/

<!doctype html>
<html ng-app="app">
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
</head>
<body>
    <div ng-controller="MyController as vm">
        {{vm.list | json}}
    </div>
    <script>
        angular.module('app', [])
          .controller('MyController', function () {
              var vm = this;
              var list = [{
                  "a": "foo"
              }, {
                  "a": "bar"
              }];

              vm.list = _.each(list, function (item) {
                  var result = _.random(0, 100) % 2 ? true : false;
                  _.extend(item, { activated: result });
              });
          });
    </script>
</body>
</html>

结果

[ { "a": "foo", "activated": false }, { "a": "bar", "activated": true } ]

对于 "Angular way" 解决方案,您可以使用 angular.forEach 函数

angular.module("myApp")
    .controller("myVm", function($scope) {

var vm = $scope;

vm.items = [
  {
    "a": "foo"
  },
  {
    "a": "bar"
  }
];

vm.activeList = [];

var pushItem = function(value,key) {
    var o = {};
    o[value.a] = false;
    this.push(o);
};

angular.forEach(vm.items, pushItem, vm.activeList);

});

输出

activeList = [{"foo":false},{"bar":false}]

有关 angular.forEach 函数的详细信息,请参阅 AngularJS angular.forEach API Reference