在指令定义中返回对象与函数之间的差异?

时间:2013-08-20 20:17:34

标签: javascript angularjs angularjs-directive

以下代码(在Widget Uno中)使用指令定义对象之间的功能差异是什么(我认为它被称为..?)...

angular.module("app").
    directive("widgetUno", ["$http", function ($http) {
        return {
                // A whole bunch of crap going on here
            },
            templateUrl: "widgetUno.html"
        };
    }]);

...这个代码在Widget Dos中?

angular.module("app").directive('widgetDos', function($http) {
    return function(scope, element, attrs) {
        // A whole bunch of crap going on here
    };
});

我试图将像Widget Uno这样的指令转换为Widget Dos,但是我在哪里引用templateUrl?这可能是Widget Dos吗?

3 个答案:

答案 0 :(得分:44)

仅返回指令中的函数只是完整定义中link函数的简写。

如果您要指定而不是 link函数(例如templateUrl),那么您需要编写很长的路径:

angular.module("app").
    directive("widgetUno", ["$http", function ($http) {
        return {
          link: function(scope, element, attrs) {
             // A whole bunch of crap going on here
          },
          templateUrl: "widgetUno.html"
        };
    }]);

这种差异实际上记录在这里 - http://docs.angularjs.org/guide/directive

答案 1 :(得分:9)

返回该功能的人实际上是:

的快捷方式
angular.module("app").directive('widgetDos', function($http) {
    return {
        link: function(scope, element, attrs) {
            //...
        };
    }
});

如果您的指令不需要模板,控制器等,请使用它。除此之外,这两种调用方法之间绝对没有功能差异。

答案 2 :(得分:1)

它应该像这样工作:

angular.module("app").directive('widgetDos', function($http) {
    return {
        templateUrl: "....",
        link: function(scope, element, attrs) {
            // A whole bunch of crap going on here
        };
    }
});

另见http://docs.angularjs.org/guide/directive(长版)。有一个例子。