为了让 UI 神奇地更新,必须对 $scope 的属性进行一些更改。例如,如果从休息资源中检索一些用户,我可能会这样做:
app.controller("UserCtrl", function($http) {
$http.get("users").success(function(data) {
$scope.users = data; // update $scope.users IN the callback
}
)
尽管在加载模板之前有更好的方法来检索数据(通过路由/ng-view):
app.config(function($routeProvider, userFactory) {
$routeProvider
.when("/users", {
templateUrl: "pages/user.html",
controller: "UserCtrl",
resolve: {
// users will be available on UserCtrl (inject it)
users: userFactory.getUsers() // returns a promise which must be resolved before $routeChangeSuccess
}
}
});
app.factory("userFactory", function($http, $q) {
var factory = {};
factory.getUsers = function() {
var delay = $q.defer(); // promise
$http.get("/users").success(function(data){
delay.resolve(data); // return an array of users as resolved object (parsed from JSON)
}).error(function() {
delay.reject("Unable to fetch users");
});
return delay.promise; // route will not succeed unless resolved
return factory;
});
app.controller("UserCtrl", function($http, users) { // resolved users injected
// nothing else needed, just use users it in your template - your good to go!
)
我已经实现了这两种方法,而后者是非常可取的,原因有两个:
在资源被解析之前它不会加载页面。这允许您通过在 $routeChangeStart 和 $routeChangeSuccess 上附加处理程序来放置加载图标等。
此外,它与“进入”动画效果更好,因为每次加载页面时,所有项目都不会烦人地播放进入动画(因为 $scope.users 是预先填充的,而不是在页面后在回调中更新已加载)。