在ngRepeat

时间:2017-10-24 05:36:48

标签: angularjs ajax angularjs-ng-repeat q

努力在ngRepeat内展示动态内容。当需要显示我的承诺内容时,我得到一个空对象{}

<div ng-controller="DemoCtrl">
    <div class="sidebar" ng-repeat="row in rows">
        <div class="row">
            <input type="checkbox">
            <div class="name">{{row.name}}</div>
            <div class="title">{{map[$index]}}</div>
        </div>
    </div>
</div>

和控制器:

 function DemoCtrl($scope, $http, $q) {
    const rows = function() {
        const rows = [];

        for (let i = 0; i < 12; i++) {
            rows.push({
                id: `demo-${i}`,
                name: `Demo ${i}`
            });
        }

        return rows;
    };

    $scope.rows = rows();
    $scope.map = [];

    // $scope.$watch($scope.map, function (oldValue, newValue) {
    //   console.log(oldValue, newValue);
    // });

    function _data() {
        // const promises = [];

        for (let i = 0; i < $scope.rows.length; i++) {
            var defer = $q.defer();

            $http.get(`https://jsonplaceholder.typicode.com/posts/${i + 1}`).then(function(post) {
                defer.resolve(`${post.data.title.substring(0, 10)}...`);
            });

            $scope.map.push(defer.promise);
            // promises.push(defer.promise);
        }

        // return $q.all(promises);
        return $q.all($scope.map);
    }

    function _init() {
        _data().then(function(data) {
            $scope.map = data; // why aren't we getting here?
        });
    };

    _init();
}

此处的Plunker:https://plnkr.co/edit/2BMfIU97Moisir7BBPNc

我已经修改了一些其他想法,例如在值更改后尝试在$watch对象上添加$scope,但我不相信这会有任何帮助。我有一些挥之不去的问题:

  1. 根据我的理解,您可以使用promise inside a template,以便ngRepeat内如何/为何会发生变化?
  2. 为什么$q.all的回叫没有被调用?
  3. 如果这不是正确的方法,那是什么?

1 个答案:

答案 0 :(得分:2)

在Angular中,您几乎不需要使用$ q。

您可以在每个$ http.get

之后填写一系列帖子标题
function DemoCtrl($scope, $http) {
  const rows = function () {
    const rows = [];

    for (let i = 0; i < 12; i++) {
      rows.push({
        id: `demo-${i}`,
        name: `Demo ${i}`
      });
    }

    return rows;
  };

  $scope.rows = rows();
  $scope.map = [];

  function _init() {
    for (let i = 0; i < $scope.rows.length; i++) {

      $http.get(`https://jsonplaceholder.typicode.com/posts/${i + 1}`).then(function (post) {
        $scope.map.push(post.data.title);
      });
    }
  }

  _init();
}

https://plnkr.co/edit/zOF4KNtAIFqoCOfinaMO?p=preview