我一直在尝试AngularJS进行一个实验项目,我遇到这个问题.
在我的html中,我想显示一个项目列表
在我的html中,我想显示一个项目列表
的index.html
<h1>Some list</h1>
<div ng-controller="datlist">
<div ng-repeat="item in items">
<div>Item description: {{item.description}}</div>
<div>Item name: {{item.name}}</div>
</div>
</div>
起初我正在使用一个简单的控制器获取信息,并使用以下更新视图:
controllers.js(原文)
function datlist($scope,$http){
$http({method: 'GET',url: 'http://localhost:61686/getdatlist?format=json',headers: {'Access-Control-Allow-Origin': 'localhost:*'}}).
success(function(data,status,headers,config) {
$scope.items=data.itemsToReturn;
console.log(data);
}).
error(function(data,config) {
console.log("fail");
});
}
这很好,我可以得到项目清单.同时,通过将我的结构改变为使用工厂来生成相同的请求并将其绑定到$scope.items,它不起作用.我尝试了许多变化的$watch,但我无法得到它来更新$scope.items.我发现一些关于$apply的东西,但我真的不明白如何使用它.
controllers.js(新的)
var datModule = angular.module('datModule',[]);
datModule.controller('datlist',function ($scope,datfactory){
$scope.items = datfactory.getlist();
$scope.$watch($scope.items,$scope.items = datfactory.getlist());
});
datModule.factory('datfactory',function ($http){
var factory = {};
factory.getlist = function(){
$http({method: 'GET',headers: {'Access-Control-Allow-Origin': 'localhost:*'}}).
success(function(data,config) {
console.log(data.itemsToReturn); //I get the correct items,all seems ok here
return data.itemsToReturn;
}).
error(function(data,config) {
console.log("fail");
});
}
return factory;
});
任何有关这方面的想法都会很棒.
PS:我发现很多帖子都在谈论这个问题,但是没有一个帮助我得到一个完整的解决方案.
谢谢
解决方法
使用手表是有点丑陋.
尝试这个:
datModule.factory('datfactory',function ($http,$q){
this.getlist = function(){
return $http.get('http://localhost:61686/getdatlist?format=json',{'Access-Control-Allow-Origin': 'localhost:*'})
.then(function(response) {
console.log(response); //I get the correct items,all seems ok here
return response.data.itemsToReturn;
});
}
return this;
});
datModule.controller('datlist',datfactory){
datfactory.getlist()
.then(function(arrItems){
$scope.items = arrItems;
});
});
这是你如何使用承诺异步的事情.
更新(15.01.2015):现在更时尚!