1

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?

3 Answers 3

5

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
Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.