我有一个显示项目列表的页面。项目列表可以不断变化,所以无论何时使用此页面或刷新页面,他都会看到新的项目列表。承诺退回后无法更新控制器的视图
我目前使用Parse存储我的项目,我将使用承诺与Parse API进行交互并获取我的项目。下面是一个非常简单的例子。
基本流程是当显示index.html时,HomeCtrl.js将加载并调用ItemService.getItems()以获取项目,将它们附加到$ scope.items,然后显示对视图的任何更改。 ItemService.getItems()是从Parse API提供的一个承诺。
app.js
var myApp = angular.module('myApp',[]);
// Parse API keys
Parse.initialize('MCNXFhdenmpSRN1DU8EJrG3YROXaX4bg0Q5IYwKp', 'XZfWd7J9xGSZQOizu0BoAtIUYtECdci4o6yR76YN');
的index.html
<html ng-app = 'myApp'>
<script src="//www.parsecdn.com/js/parse-1.6.2.min.js"></script>
<head>
<title> My Simple Example that doesn't work! </title>
</head>
<body layout="row">
<div ng-controller = "HomeCtrl as ctrl">
<div ng-repeat="item in ctrl.items">
{{item.id}}
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.6/angular.min.js"></script>
<script src = "app.js"> </script>
<script src = "HomeCtrl.js"> </script>
<script src = "ItemService.js"> </script>
</body>
</html>
ItemService.js
var myApp = angular.module('myApp');
myApp.service('ItemService', function(){
// gets all Items
this.getItems = function() {
var Item = Parse.Object.extend("Item");
var query = new Parse.Query(Item);
return query.find().then(function(items){
return items;
});
return this;
}
});
HomeCtrl.js
var myApp = angular.module('myApp');
myApp.controller('HomeCtrl',[ 'ItemService', '$scope',function(ItemService, $scope){
$scope.items = [];
ItemService.getItems()
.then(function(results){
$scope.$apply(function() {
$scope.items = results;
console.log($scope.items);
});
});
console.log($scope.items);
}]);
$ scope.items在$ scope中做了更改。$ apply函数(我打印出来并可以看到一些项目),但是视图没有改变。当我在ItemService.getItems()后打印$ scope.items时,打印出一个空数组。
我是否在调用承诺后错误地更新$ scope.items,或者是否存在一些我不理解的概念?
任何帮助表示赞赏。
编辑
从456的回答,我看到,我在NG-重复他的回答作品犯了一个错误。不过,我想继续使用controllerAs语法。我试图在$ scope中更新this.items。$ apply函数但它不起作用 - this.items被修改,但是这个改变没有在视图中表示。我的修改是低于
的index.html
<div ng-controller = "HomeCtrl as ctrl">
<div ng-repeat="item in ctrl.items">
{{item.id}}
</div>
</div>
HomeCtrl.js
var myApp = angular.module('myApp');
myApp.controller('HomeCtrl',[ 'ItemService', '$scope',function(ItemService, $scope){
this.items = [];
ItemService.getItems()
.then(function(results){
$scope.$apply(function() {
this.items = results;
console.log(this.items);
});
});
}]);
如果您在HTML中使用controllerAs语法,则不需要在控制器中使用$ scope。您可以在控制器中的此属性上将这些元素添加到此变量中。 –
@MahendraSingh我必须在控制器中使用$ scope来使用$ apply来更新视图。有没有办法可以继续使用'this'并获得$ apply的相同影响? – Rohan
当然你可以使用$ scope.apply,但是你的物品清单不需要在作用域上。 –