![](/img/trans.png)
[英]In total.js what is the best way to define global constants that i can use in scripts and templates?
[英]What is the best way in Angular to declare global functions to use in templates?
在模板中使用函數有兩種方法(或者還有其他方法?):
1.在$ rootScope中聲明它:
app.run(function ($rootScope) {
$rootScope.makeURL = function (url) {
return 'http://mysite.ru/' + url;
}
});
並在模板中:
<a href="makeURL('blog')">go Blog</a>
2.像指令一樣聲明:
app.directive('makeURL', function () {
return {
link: function ($scope, $element, $attrs) {
var url = 'http://mysite.ru/' + $attrs.makeurl; // just example
$element.attr('href', url);
}
}
}
並在模板中:
<div ng-controller="SomeCtrl">
<a makeURL="blog">go Blog</a>
</div>
還是我需要使用過濾器? 什么是最好的方法? 我可以將$ rootScope用於此類情況嗎? 還是最壞的方法? 為什么? 我需要了解這些東西。
編輯:我認為這就是答案: Angular JS-使服務可以從控制器和視圖全局訪問
使用服務
mymodule.service('URL',function(){
this.make=function(){...}
});
mymodule.controller($scope,URL){
$scope.URL=URL;
}
<a href="{{Url.make(somedata)}}"/>
服務將使您的控制器更具可測試性,並且您將能夠獨立測試服務。 如果您在angular.run方法中向rootscope添加任何內容,則會更加困難。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.