爲了使UI奇蹟般地更新,一些改變必須發生在$範圍的性能。例如,如果從靜止的資源獲取一些用戶,我可能會做這樣的事情:
app.controller("UserCtrl", function($http) {
$http.get("users").success(function(data) {
$scope.users = data; // update $scope.users IN the callback
}
)
雖然有更好的方法來檢索數據裝載模板之前(通過路由/ NG-視圖):
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是預先填充的,而不是在一旦頁面加載就回調)。