how to use factory/service for sharing information between multiple controllers in angularjs?

吃可爱长大的小学妹 提交于 2019-12-10 00:03:30

问题


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?

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


回答1:


I will recommend you using Memoization pattern along with service and reuse the service in the controller

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;
              });
         });



回答2:


You can access to $scope with :

angular.element(document.getElementById('YourCtrl')).scope();

After, you can init data in all your controllers.



来源:https://stackoverflow.com/questions/17472097/how-to-use-factory-service-for-sharing-information-between-multiple-controllers

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!