Reputation: 1169
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
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
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:
Upvotes: 5
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 :
angular.constant
to define and then inject a constant balue. This one seems to be out of subject for you though.Upvotes: 0