Call Global Variable in AngularJS Expression
angularjs, javascript
Solution
These expressions are evaluated against the current scope. If you have not set them in your scope via a controller, it will not evaluate. See http://docs.angularjs.org/guide/expression
Example:
function MyCtrl($scope)
{
$scope.apiRoot = apiRoot;
}
HTML:
<div ng-controller="MyCtrl">
{{apiRoot}}
</div>
As has been mentioned, while the above example works, it is not reccommended. The better way would be to set these variables in a service and then get them through the service.
function MyCtrl($scope, apiRootService)
{
$scope.apiRoot = apiRootService.getApiRoot();
}
The service:
angular.module('myServices', []).factory('apiRootService', function() {
var apiRoot = 'http://localhost:8000/api',
apiUrl = apiRoot,
apiBadgeUrl = apiRoot + '/badges',
apiLevelUrl = apiRoot + '/levels',
apiBehaviorUrl = apiRoot + '/behaviors',
apiTrophyUrl = apiRoot + '/trophies',
apiUserUrl = apiRoot + '/users',
apiWidgetPreferencesUrl = apiRoot + '/widgetPreferences';
return {
getApiRoot: function() {
return apiRoot
},
//all the other getters
});
Problem
I have some global variables in head's tag: ``` <script type="text/javascript"> var apiRoot = 'http://localhost:8000/api', apiUrl = apiRoot, apiBadgeUrl = apiRoot + '/badges', apiLevelUrl = apiRoot + '/levels', apiBehaviorUrl = apiRoot + '/behaviors', apiTrophyUrl = apiRoot + '/trophies', apiUserUrl = apiRoot + '/users', apiWidgetPreferencesUrl = apiRoot + '/widgetPreferences'; </script> ``` I want to use in angular expression in html file but my tries are fails: ``` {{ $window.apiRoot }} or {{ apiRoot }} ```