[英]angularjs update view after $http.get
我的html视图中有一个<ul>
,并且该<ul>
的内容是基于$ http.get填充的。
HTML:
<div id="recentlyReleased" ng-controller="sampleRecordController as recCtrl">
<h1>Sample Records</h1>
<ul>
<li class="last-child" ng-repeat="record in recCtrl.records">
<a target="_new" ng-href="" >
<span>sample 1</span>
</a>
</li>
</ul>
<a ng-click="recCtrl.displayRecords('a')" href="">
<img />
</a>
<a ng-click="recCtrl.displayRecords('b')" href="">
<img />
</a>
</div>
厂
angular.module('homeApp.services', [])
.factory('homePage', function ($http) {
return {
showRecords: function (fac) {
return $http.get('/home/getRandom?num=10&fac=' + fac)
.then(function (response) {
return response.data
});
}
}
}
);
控制者
angular.module('homeApp.controllers')
.controller('sampleRecordController', function (homePage) {
var r = this;
r.base_url = base_url;
r.records = [];
var currentFac='c';
r.displayRecords = function (fac) {
homePage.setFac(fac);
homePage.showRecords(homePage.getFac()).then(function (data) {
r.records = data;
});
},
r.displayRecords(currentFac); //initial load
})
该代码最初成功加载了列表<ul>
,但是当我单击<a>
,html视图没有刷新。 我是angularjs的新手,有人可以帮忙吗? 谢谢
您应该尝试做的就是返回$ http.get()的承诺,如下所示。
angular.module('homeApp.services', [])
.factory('homePage', function ($http) {
return {
showRecords: function (fac) {
// return the promise here
return $http.get('/home/getRandom?num=10&fac=' + fac);
}
}
});
angular.module('homeApp.controllers')
.controller('sampleRecordController', function (homePage) {
var r = this;
r.base_url = base_url;
r.records = [];
var currentFac='c';
r.displayRecords = function (fac) {
homePage.setFac(fac);
homePage.showRecords() // resolve here
.then(function (data) {
r.records = data;
});
},
r.displayRecords(currentFac); //initial load
});
注意:您无法返回ajax调用的响应,因为它在不同的线程上运行,并且您不知道该调用何时完成。 您应该尝试了解承诺。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.