[英]Angular pass data between controller
I have requirement where i need to share data between controllers,so i created factory 我有需要在控制器之间共享数据的要求,所以我创建了工厂
suppose i have url like: abc/123 (Note:123 is dynamic i need to pass it from controller) 假设我的网址是:abc / 123(注意:123是动态的,我需要从控制器传递它)
MyCode 我的密码
appServices.factory('classesService', function($http){
return {
getClasses: function(value) {
return $http.get(urlprefix + 'orgs/' + value + '/classes?with-users=true');
}
};
});
In Controller 在控制器中
classesService.getClasses($scope.organization.id).then(function(data){});
now suppose i am using it in 3 contollers 3 calls will go to server. 现在,假设我在3个contollers中使用它,则3个呼叫将转到服务器。 i dont want three calls i want only one call.
我不想打三个电话,我只想打一个电话。
Note:value is same for all three controller 注意:三个控制器的值都相同
is there any way i can acheive this. 有什么办法可以做到这一点。
Thanks 谢谢
您可以使用UI-ROUTER-EXTRAS“ https://christopherthielen.github.io/ui-router-extras/#/home ”
The easiest solution is to just enable caching in your service. 最简单的解决方案是仅在服务中启用缓存。 This way all your controllers can access the method and the request is made only once.
这样,您的所有控制器都可以访问该方法,并且该请求仅发出一次。
return $http.get(urlprefix + 'orgs/' + value + '/classes?with-users=true', {cache: true});
This is very basic caching. 这是非常基本的缓存。 You may need a more advanced strategy -- but this is your first step.
您可能需要更高级的策略-但这是您的第一步。
UPDATE 更新
You may run into a race condition with simple $http caching if your second or third request are made before the first request completes. 如果在第一个请求完成之前发出了第二个或第三个请求,则可能会通过简单的$ http缓存进入竞争状态。 We can overcome this easily.
我们可以轻松克服这一点。
appServices.factory('classesService', function($http) {
var orgsPromise;
return {
getClasses: function(value) {
if (orgsPromise) return orgsPromise;
orgsPromise = $http.get(urlprefix + 'orgs/' + value + '/classes?with-users=true');
return orgsPromise;
}
};
});
I believe you can do something like this; 我相信你可以做这样的事情;
var yourApp = angular.module('yourApp',[]);
yourApp.factory('classesService', function($http){
var classes;
return {
getClasses: function(value) {
if (!classes) {
classes= $http.get(urlprefix + 'orgs/' + value + '/classes?with-users=true');
}
return classes;
}
};
});
yourApp.factory('Classes', ['classesService',function(classesService){
return classesService.getClasses();
}]);
function yourControllerA($scope, Classes) {
$scope.value="Hello from Controller A";
$scope.sharedValue=Classes;
....
}
function yourControllerB($scope, Classes) {
$scope.value="Hello from Controller B";
$scope.sharedValue=Classes;
....
}
function yourControllerC($scope, Classes) {
$scope.value="Hello from Controller C";
$scope.sharedValue=Classes;
....
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.