shah
shah

Reputation: 1169

angularjs - dynamically add a variable to the scope of each controller

i want to add a global viable to the scope of all controllers

i can do it manually in each controller like...

if variable is

<script>
    var base_url ="http://localhost/myapp/";
</stript>

then

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

i can also use $rootScope or service

but i want to add this variable to the scope of each controller dynamically. So as there any possible way to do this?

Upvotes: 1

Views: 545

Answers (3)

Artem K.
Artem K.

Reputation: 804

Another alternative for controller input is ng-init directive. https://docs.angularjs.org/api/ng/directive/ngInit

<div ng-controller="MyCtrl as $ctrl" 
     ng-init="$ctrl.init({baseUrl: 'http://localhost/myapp/'})"></div>

 angular.module('myApp').controller('MyCtrl', function () {
      this.init = function (inputData) {
           console.log(inputData); // {baseUrl: 'http://localhost/myapp/'}
            this.baseUrl = inputData.baseUrl;
      }
});

Upvotes: 0

fbid
fbid

Reputation: 1570

Possible solution:

If it's more a constant than a variable that you need to pass to all the controllers, so for example it's an URL that never change you can use angular method constant

Example:

app.constant('BASE_URL','http://localhost/myapp/');

Then in each controller you inject it:

app.controller('Ctrl', ['$scope','BASE_URL' , function ($scope, BASE_URL){
  $scope.base_url = BASE_URL;
}])

Alternatives:

  • Services
  • $rootScope

Upvotes: 5

Walfrat
Walfrat

Reputation: 5353

There is a base tag that support angular to make sure that every URL in your javascript (templates, $http,...) will be relative to that one. So you can just use it : https://docs.angularjs.org/#!/guide/$location

Others way are :

  1. $rootScope as you mentioned
  2. Events, all controller require that value can listen for a specific event to get the new value.
  3. Service. Either $watch is value or use events again
  4. If it has not to changed and you can know the value at bootstrap you can use angular.constant to define and then inject a constant balue. This one seems to be out of subject for you though.

Upvotes: 0

Related Questions