Calling a global variable in an AngularJS expression
I have global variables in the head 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 the angular expression in the html file, but my attempts fail:
{{ $window.apiRoot }} or {{ apiRoot }} These expressions are evaluated in the current area. If you have not installed them in your volume using the 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 already mentioned, although the above example works, it is not recommended. It would be best to set these variables in the service and then get them through the service.
function MyCtrl($scope, apiRootService) { $scope.apiRoot = apiRootService.getApiRoot(); } 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 }); Another way to do this is to add your global to $ rootScope. You can do this by adding the following to your application module definition
angular.module('myApp', ['ngRoute']) .run(function ($rootScope){ $rootScope.myAPI = { 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' } }); Although the service does work, angular documentation recommends against this. http://docs.angularjs.org/misc/faq
Conversely, do not create a service whose sole purpose is to store and return data bits.