可变缓存在AngularJS(厂) [英] Variable caching in AngularJS (factory)
问题描述
我在我的应用程序下面的控制器,但我无法解释一些奇怪的行为。我已经编号的两行帮助的描述,他们并不在现场code同时都存在。
I have the following controller in my application, but there is some strange behaviour that I cannot explain. I've numbered two of the lines to help with the description, they don't both exist at the same time in the live code.
var app = angular.module('movieListings', ['ngResource', 'ngRoute', 'ui.bootstrap', 'ng']);
var cachedMovieList = [];
//Controller for movie list
app.controller('MovieListController', ['$http', function($http){
var mlc = this; //needed for the $http request
this.movies = cachedMovieList;
this.loaded = false;
this.error = false;
if(this.movies.length == 0) {
console.log("Grabbing new movie list from DB");
$http.get('data/movies.json').success(function(data){
mlc.movies = data;
mlc.loaded = true;
cachedMovieList = data; //(1)
}).error(function(data){
mlc.error = true;
});
cachedMovieList = this.movies; //(2)
} else {
this.loaded = true;
}
}]);
随着code如上线(1)present和线(2)未present,我能够缓存结果,这样,当我在页面之间轻弹我不需要不断地重新获取数据。
With the code as above with line (1) present and line (2) not present, I am able to cache the result so that when I flick between pages I don't need to constantly re-get the data.
但是,如果我删除线(1),并插入线(2),是从来没有填充变量cachedMovieList。我希望它是基于一个事实,即mlc.movies被分配到...但我不明白为什么是这样的话?
However if I remove line (1) and insert line (2), the variable "cachedMovieList" is never populated. I would expect it to be based on the fact that "mlc.movies" was assigned to... but I cannot understand why this is the case?
任何意见欢迎。
推荐答案
实施一个工厂,检索数据。使用angular.copy至preserve数组引用时,从$ HTTP调用返回的数据。
Implement a factory that retrieves the data. Use angular.copy to preserve the array reference when the data returns from the $http call.
var app = angular.module('movieListings', ['ngResource', 'ngRoute', 'ui.bootstrap', 'ng']);
app.factory('movies', function($http) {
var movies = {
data: [],
loaded: false,
error: false
};
$http.get('data/movies.json').success(function(data){
angular.copy(data, movies.data);
movies.loaded = true;
}).error(function(data){
movies.error = true;
});
return movies;
});
注入出厂到控制器:
Inject the factory into your controller:
//Controller for movie list
app.controller('MovieListController', ['$scope','movies', function($scope, movies){
this.movies = movies;
}]);
工厂(如服务业)是单身。它们被初始化一次,缓存为SPA的整个生命周期。
Factories (like services) are singletons. They are initialized once, and cached for the entire lifetime of the SPA.
使用控制器的看法:
<div ng-controller="MovieListController as ctrl">
<div ng-show="!ctrl.movies.loaded"> Loading... </div>
<ul>
<li ng-repeat="movie in ctrl.movies.data">
{{ movie.name }}
</li>
</ul>
</div>
这篇关于可变缓存在AngularJS(厂)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!