使用forEach修改角度范围变量

时间:2015-02-12 11:14:44

标签: javascript angularjs

鉴于服务器上的以下数据:

people.json

{
  "Bill": "Bill the Man",
  "Jane": "Jane Doe",
  "Jack": "Jack the Ripper"
}

groups.json

[
   ["Bill", "Jack"],
   ["Jane", "Jack"]
]

我在controllers.js中导入它:

var websiteApp = angular.module('websiteApp', []);

websiteApp.controller('websiteCtrl', function ($scope, $http) {
  // import data
  $http.get('people.json').success(function (data) {
    $scope.people = data;
  });
  $http.get('groups.json').success(function (data) {
    $scope.groups = data;
  });

  // fill groups with people data
  $scope.groups.forEach(function (group, i) {
    group.forEach(function (person, j) {
      $scope.groups[i][j] = $scope.people[person];
    });
  });
});

然后我使用以下模板:

<ul>
  <li ng-repeat="group in groups">
    <ul><li ng-repeat="person in group">{{person}}</li></ul>
  </li>
</ul>

我希望从people.json获取名单列表,但我得到groups.json中的名字。对console.log进行的一些进一步调查表明,forEach循环未执行。在分配范围之前,使用局部变量进行的进一步试验也不会成功。

我该如何处理这个问题?我不了解Angular是如何工作的? (N.B。:我是Angular和Javascript框架的新手。)

2 个答案:

答案 0 :(得分:2)

尝试这样的事情......

var websiteApp = angular.module('websiteApp', []);

websiteApp.controller('websiteCtrl', function($scope, $http, $q) {
    // import data

    getPeopleAndGroups = function() {

        var people = $http.get('people.json');
        var groups = $http.get('groups.json');

        return $q.all([people, groups]);
    }


    getPeopleAndGroups().then(function(data) {
        var people = data[0].data;
        var groups = data[1].data;

        // fill groups with people data
        groups.forEach(function(group, i) {
            group.forEach(function(person, j) {
                $scope.groups[i][j] = $scope.people[person];
            });
        });
    })
});

使用$q库,您可以返回一个承诺,这样可以帮助您 - 我无法在工作中验证它,但它应该让您走上正轨。看看Angular q Library

答案 1 :(得分:1)

$http本质上是异步的,当两个ajax请求都完成时,您需要调用foreach。例如:

var websiteApp = angular.module('websiteApp', []);

websiteApp.controller('websiteCtrl', function ($scope, $http) {
    // import data
    $http.get('people.json').success(function (data) {
        $scope.people = data;
        $http.get('groups.json').success(function (data) {
            $scope.groups = data;
            // fill groups with people data
            $scope.groups.forEach(function (group, i) {
                group.forEach(function (person, j) {
                    $scope.groups[i][j] = $scope.people[person];
                });
            });

        });
    });



});