有两种方法(或者还有其他方法?)在模板中使用函数:
<强>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 - Make service globally accessible from controllers and view
最佳答案
使用服务
mymodule.service('URL',function(){
this.make=function(){...}
});
mymodule.controller($scope,URL){
$scope.URL=URL;
}
<a href="{{Url.make(somedata)}}"/>
服务将使您的 Controller 更具可测试性,并且您将能够单独测试该服务。如果您在 angular.run 方法中向 rootscope 添加任何内容,则会更加困难。
关于javascript - Angular 中声明要在模板中使用的全局函数的最佳方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23590994/