如何使用工厂/服务在angularjs多个控制器之间的信息共享? [英] how to use factory/service for sharing information between multiple controllers in angularjs?
问题描述
我试着在应用程序启动和加载一个JSON US $ p $垫我所有的控制器之间的数据。
我知道这是不是很辛苦的事,但是我从迷茫的所有文章/答案,我读过,因为它们使用不同的语法比我好,可有人请直接与我如何来的?
Im trying to load a JSON when app starts, and spread the data between all my controllers. I know this is not very hard to do, but Im confused from all articles/answers I've read because they use different syntax than I do, can someone Please direct me on how to to that?
林目前正在控制器使$ http.get:
Im currently making the controller make the $http.get :
myApp = angular.module("myApp", [])
myApp.controller "HomeCtrl", ($scope, $http, $routeParams) ->
$http.get('gethome.php').success (data) ->
$scope.home = data
但我不得不重复自己在每一个控制器,我想访问该数据
But I have to repeat myself in each and every controller I want to have access to that Data
推荐答案
我会建议你使用记忆化模式与服务一起,并在控制器重用服务
I will recommend you using Memoization pattern along with service and reuse the service in the controller
请检查下面的示例code
Pls check the below sample code
var app = angular.module('plunker', []);
app.service('cache', function ($http,$q) {
var mycache={};
return {
getdata: function (key) {
var deferred = $q.defer();
if (mycache[key]) {
deferred.resolve(mycache[key]);
}
else {
$http.get('TextFile.txt').then(function (data) {
mycache[key] = data.data;
deferred.resolve(mycache[key]);
});
}
return deferred.promise;
}
}
});
app.controller('test', function ($scope, cache) {
cache.getdata('cache').then(function (data) {
$scope.data = data;
});
});
app.controller('test1', function ($scope, cache) {
//since data is already cached now it will server the cached data
cache.getdata('cache').then(function (data) {
$scope.data = data;
});
});
这篇关于如何使用工厂/服务在angularjs多个控制器之间的信息共享?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!