javascript - 推送到数组不会通过 ng-repeat 指令更新 View 列表

标签 javascript arrays angularjs angular-ui-router angularjs-ng-repeat

我在我的 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); 
...

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

已编辑添加了附加信息:

div 位于 ng-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的一部分

已编辑添加了附加信息:

配置中的所有页面都分配给同一个 Controller 。

.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,output

HTML

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

JavaScript

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-repeat 是否应位于正确的 Controller 内。

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

关于javascript - 推送到数组不会通过 ng-repeat 指令更新 View 列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34714850/

相关文章:

javascript - ng-model 没有在单选按钮中更新

javascript - 了解这段 javascript 代码的输出

arrays - 按子级值对多维数组进行排序

javascript - 如何维护时区

javascript - MongoDB $where 可选字段

java - 使用两个值 x 和 y 对 java 中的数组进行自定义排序

ios - 检查对象是否超出数组范围的最佳方法

javascript - Angular POST 请求不起作用

angularjs - 使用 ng-model 使用 angularjs/ui-bootstrap 制作 Accordion

javascript - 有没有办法使用 ng-options 更新两个值而不使用 ng-change ?