سؤال

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.

هل كانت مفيدة؟

المحلول

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

نصائح أخرى

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

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

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top