推送到数组不会通过ng repeat指令更新视图列表

Pushing to an array does not update view list via ng-repeat directive

本文关键字:repeat ng 指令 更新 列表 新视图 数组      更新时间:2023-09-26

我在index.html 中实现了一个简单的ng-repeat指令

<div ng-repeat="item in itemCollection">
    {{item.name}}
    {{item.date}}
    ...
</div>

我正在尝试使用push()方法在数组中添加一个新项。

$scope.itemCollection = [];
$scope.someFunction = function(){
    var o = {};
    //do stuff here.
    o.name = name-fromDoingStuff;
    o.date = date-fromDoingStuff;
    ...
    $scope.itemCollection.push(o);
}

itemCollection得到更新。我使用alert() 确认了这一点

alert($scope.itemCollection[0].name); 
alert($scope.itemCollection[0].date); 
... 
alert($scope.itemCollection[1].name); 
alert($scope.itemCollection[1].date); 
...

但视图中显示的列表不会更新。我已经尝试过使用$scope.$apply,但它仍然是一样的。我可能做错了什么?

已编辑添加了其他信息:

divng-controller

<body ng-app = "grabbingSystem" ng-controller = "mainCtrl">
    <div class = "center-wrap">
        <ui-view></ui-view> //I'm using angular-ui-router
    </div>
</body>

div不是嵌套ng-repeat 的一部分

已编辑添加附加信息:

配置中的所有页面都分配给同一个控制器。

.config([
        '$stateProvider',
        '$urlRouterProvider',
        function($stateProvider, $urlRouterProvider){
            $stateProvider
                .state('list', {
                    url: '/list',
                    templateUrl: 'tickets/_ticketsList.html',
                    controller: 'mainCtrl',
                    resolve: {
                      postPromise: ['tickets', function(tickets){  
                        return tickets.DBgetAll();
                      }]
                    }
                })
                .state('grab', {
                    url: '/grab',
                    templateUrl: 'tickets/_ticketsGrab.html',
                    controller: 'mainCtrl'
                })
            $urlRouterProvider.otherwise('list');
        }
    ])

我试过你的代码,它运行得很好,只是做了一些小改动。

http://jsbin.com/qirafa/1/edit?html,js,输出

HTML

<body ng-app="myApp" ng-controller="MainController">
<div ng-repeat="item in itemCollection">
  {{item.name}}
  {{item.date}}
</div>
</body>

Javscript

var myApp = angular.module('myApp', []);
myApp.controller("MainController", function($scope) {
$scope.itemCollection = [];
$scope.someFunction = function(){
    var o = {};
    o.name = "a";
    o.date = "b";
    $scope.itemCollection.push(o);
};
$scope.someFunction();
});

检查你的ng重复应该在正确的控制器内。

并且应该调用将项添加到数组的函数。