AngularJS:$ scope.array.push()不会更新视图,即使使用$ apply也是如此

问题描述 投票:12回答:2

我正在尝试学习AngularJS并且有一些我不明白的东西,这似乎是所有的互联网都通过使用$scope.$apply解决,但我已经使用它,它什么也没做。

基本上,我使用Twitter API来检索时间轴,当我们从底部滚动时,它会加载更多的推文。这部分工作,我正在使用工厂来做,但我可以在控制台中显示对象接收,我这里没有问题。

我有这样的观点,以显示数据:

<div class='timeline' ng-controller='TimelineCtrl' is-scrolled='loadData()'>
    <div class='tweet' ng-repeat='p in posts'>
        <img class='portrait' src='{{p.user.profile_image_url}}' />
        <p>{{p.text}}</p>
        <p class='date'>{{p.created_at}}</p>
    </div>
</div>

我的控制器看起来像这样:

    $scope.posts = [];

    // Load the original tweets list
    TwitterAPI.timeline($scope.count, function(data) {
        $scope.$apply(function() {
            $scope.maxId = data[data.length-1].id;
            $scope.sinceId = data[0].id;
            $scope.posts.push(data);
        });
    });

数据是合法的。

我根本不懂的东西,让我觉得它很容易解决,我只是看不到它,如果我使用'= data'而不是'push(data)',那么视图就是更新。即使我加载了更多的推文,如果我使用'=',视图也会更新(内容被替换当然不是我想要的)。

注意:maxId,sinceId和count之前已初始化,我没有把它放在那里,因为我觉得不重要。

angularjs angularjs-scope angularjs-ng-repeat angularjs-controller
2个回答
10
投票

麻烦似乎是Angular的NgRepeat停止,如果它不止一次迭代同一个对象。我有created a jsFiddle来演示。

在第一部分中,您可以向数组添加字符串。第一个按钮总是添加相同的字符串对象,而第二个按钮每次都创建一个新的字符串对象。请注意,只要您单击第一个按钮两次,添加到列表中的内容就没有关系。

在第二部分中,我们总是添加一个新对象,即使这些对象都包含对同一字符串对象的引用。这可以像你期望的那样工作。

因此,要使其成为明确的答案,请确保添加到列表中的内容是不同的对象,并在需要时使用对象文字来强制执行此操作。我更喜欢Array#push而不是Array#concat,因为后者每次创建一个新的数组对象,如果你有很多项目,那将是大量的流失和大量的垃圾收集。

HTML:

<div ng-controller="Controller1">
    <button ng-click="addLine()">Add Line</button>
    <button ng-click="addNumber()">Add Number</button>
    <button ng-click="reset()">Reset</button>
    <div>{{lines}}</div>
    <div ng-repeat="line in lines">
        {{line}}
    </div>
</div>

<hr />

<div ng-controller="Controller2">
    <button ng-click="addObject()">Add Object</button>
    <button ng-click="reset()">Reset</button>
    <div>{{objects}}</div>
    <div ng-repeat="obj in objects">
        {{obj.data}}
    </div>
</div>

JavaScript:

(function () {
    var myApp = angular.module('myApp', []);

    myApp.controller('Controller1', function ($scope) {
        $scope.lines = [];

        $scope.addLine = function () {
            $scope.lines.push('Hello world!');
        };

        $scope.addNumber = function () {
            $scope.lines.push('Line ' + $scope.lines.length);
        };

        $scope.reset = function () {
            $scope.lines = [];
        };
    });

    myApp.controller('Controller2', function ($scope) {
        $scope.objects = [];

        $scope.addObject = function () {
            var obj = { data: 'Hello world!' };
            $scope.objects.push(obj);
        };

        $scope.reset = function () {
            $scope.objects = [];
        };
    });
})();

6
投票

我相信如果你构造你的ng-repeat(使用$ index跟踪),它就不会停止在dupe上:

<div class='tweet' ng-repeat='p in posts track by $index'>
...
</div>
© www.soinside.com 2019 - 2024. All rights reserved.