How to create a object with properties that are sharable among controllers in AngularJS?

天大地大妈咪最大 提交于 2019-12-24 07:09:23

问题


This is a follow-up question to How to create this global constant to be shared among controllers in Angularjs?

The answer provided allows a constant $webroot to be shared among controllers.

app = angular.module('myApp', []);
app.constant('$webroot', 'localhost/webroot/app');

app.controller('myController', ['$scope', '$webroot', function($scope, $webroot) {
  $scope.webroot = $webroot;
}]);

However, the problem is if I have 10 constants, then all 10 constants have to be injected into the controller. This makes the controller declaration look long and ugly. How can I create an object with properties that are sharable among controllers in AngularJS? In this way, I need only inject a single object instead of many constants. Can this be done in Angularjs? Thanks.


回答1:


var app = angular.module('app', []);

app.constant('config', {
  prop1: 'val1',
  prop2: 'val2',
  ...
});

app.controller('Ctrl', ['config', function(config) {
  console.log(config.prop1);
  console.log(config.prop2);
  ...
}]);



回答2:


You can use a factory for that:

app = angular.module('myApp', []);
app.factory('MyGlobals', function() {
  return {
    globalOne: 12345,
    globalTwo: 'Hey there',
    globalThree: {foo: 'bar'},
    globalFour: [1, 2, 3, 4],
    isFoo: function () {
      return (this.globalTwo == 'Foo' ? true : false);
    }
  }
});

app.controller('myController', ['$scope', 'MyGlobals', function($scope, MyGlobals) {
  $scope.globalOne = MyGlobals.globalOne
  [...]
  if (MyGlobals.isFoo()) {
    // Be creative
  }
}]);



回答3:


You can share object or variable among different controllers in multiple ways -

  1. using factories

  2. using services

  3. broadcast or emit

If your requirement is just sharing variables among multiple controllers, you can achieve this using services.

create a service as below - here name is sharedService. you can use your own service name. And then define/declare variables using 'this' keyword (as many you want).

    var app = angular.module('app', []);

    app.service('sharedService', function ($rootScope) {
    this.globalvar1 = "my global variable1";
    this.globalvar2="";
    });

Inject service in your controller and then access the service variable as below

 app.controller('myController', ['$scope', 'sharedService',
    function ($scope,sharedService) {
    var myGlobalVariable=sharedService.globalvar1;
    sharedService.globalvar1="my global variable value changed from controller";
    }]);

You can use service variables in all of your controllers but you have to inject service name in controllers



来源:https://stackoverflow.com/questions/22710593/how-to-create-a-object-with-properties-that-are-sharable-among-controllers-in-an

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