javascript - Angular 中声明要在模板中使用的全局函数的最佳方法是什么?

标签 javascript angularjs global-variables

有两种方法(或者还有其他方法?)在模板中使用函数:

<强>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/

相关文章:

c++ - 全局变量的行为在不同的函数中有所不同

javascript - 如何打开持久的 SSH 客户端来制作基于 Web 的文件管理器?

javascript - 显示图像 onclick 工作正常,但如何在再次单击时隐藏它

javascript - JSON 数组 - 删除第一个元素

javascript - 使用 controllerAs 语法时将当前范围传递给 modalInstance

javascript - 更改变量值以在另一个变量中使用它

javascript - WebStorm TypeScript 减少自动完成建议

javascript - agGrid - 在列标题名称中显示过滤短语

javascript - 在 angularjs 中使用 jQuery UI 按钮集

c++ - 在全局变量的 header 和源中使用 "extern int x"中的 extern 关键字是否正确?