Skip to content Skip to sidebar Skip to footer

How To Create A Object With Properties That Are Sharable Among Controllers In Angularjs?

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 co

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

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

Solution 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

Post a Comment for "How To Create A Object With Properties That Are Sharable Among Controllers In Angularjs?"