javascript - 如何在 angularJS 中重构指令代码

标签 javascript angularjs

我来自.Net世界,所以我可能会错过javascript世界中angularjs中明显的东西。我正在编写一些指令,它们都有相同类型的代码,我需要在其中设置相同的属性。

是否可以创建一个函数并在 Angular 的链接函数中使用该函数?

谢谢

最佳答案

当然,这对于 JavaScript 来说并不难。

这里是一些执行此操作的示例代码。

(function(){
    function commonCode(){
        //common code goes here.
    }

    var app = angular.module("app");

    app.directive("first",function(){
        return function(scope,element,attrs){
            commonCode();
        }
    });


    app.directive("second",function(){
        return function(scope,element,attrs){
            commonCode();
        }
    });

    app.directive("third",function(){
        return function(scope,element,attrs){
            commonCode();
        }
    });

})();

使用 Angularjs 更容易做到这一点。

如果这个通用代码非常通用,那么您可以将此commonCode重构为服务并将其注入(inject)到您的所有中>指令

关于javascript - 如何在 angularJS 中重构指令代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16515898/

相关文章:

javascript - 延迟对象如何通知它已解决的 promise ?

javascript - Ionic Angular 在 View 之间传递数据

javascript - 使用 $http 刷新来自服务的数据时, Angular View 不更新

java - Spring MVC 不使用 angularjs 指令渲染 html

javascript - Angularjs 一页应用程序

javascript - 使用 JavaScript 设置 HTML5 输入列表值

javascript - 带箭头顶部和边框的框

javascript - jQuery show()/hide() 在 iPhone/Android 上工作吗?

javascript - 如何使用 angularjs $http.delete() 请求发送数据?

php - 如何从包含angularjs中json数组的json对象中获取特定值