![](/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.