我在我的 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/