呼叫全局变量角度防爆pression [英] Call Global Variable in Angular Expression
问题描述
我在头上的标签一些全局变量:
<脚本类型=文/ JavaScript的>
VAR apiRoot =的http://本地主机:8000 / API,
apiUrl = apiRoot,
apiBadgeUrl = apiRoot +'/徽章,
apiLevelUrl = apiRoot +'/水平',
apiBehaviorUrl = apiRoot +'/行为',
apiTrophyUrl = apiRoot +'/奖杯,
apiUserUrl = apiRoot +'/用户,
apiWidget preferencesUrl = apiRoot +'/部件preferences';
< / SCRIPT>
我想在角前pression在HTML文件中使用,但我的尝试是失败:
{{$ window.apiRoot}}或{{apiRoot}}
这些前pressions是针对当前范围进行评估。如果你还没有通过控制器在你的范围内进行设置,也不会评价。请参见 http://docs.angularjs.org/guide/ex$p$pssion
例如:
函数MyCtrl($范围)
{
$ scope.apiRoot = apiRoot;
}
HTML
< DIV NG控制器=MyCtrl>
{{apiRoot}}
< / DIV>
正如已经提到的,尽管上述实施例的工作原理,它不reccommended。更好的办法是在服务设置这些变量,然后通过服务获得它们。
函数MyCtrl($范围,apiRootService)
{
$ scope.apiRoot = apiRootService.getApiRoot();
}
该服务:
angular.module('myServices',[])。工厂('apiRootService',函数(){
VAR apiRoot =的http://本地主机:8000 / API,
apiUrl = apiRoot,
apiBadgeUrl = apiRoot +'/徽章,
apiLevelUrl = apiRoot +'/水平',
apiBehaviorUrl = apiRoot +'/行为',
apiTrophyUrl = apiRoot +'/奖杯,
apiUserUrl = apiRoot +'/用户,
apiWidget preferencesUrl = apiRoot +'/部件preferences';
返回{
getApiRoot:功能(){
回报apiRoot
},
//所有其他干将
});
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 }}
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
});
这篇关于呼叫全局变量角度防爆pression的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!