33

使用指令定义对象(我认为它被称为..?)的以下代码(在 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 中可行吗?

4

3 回答 3

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

于 2013-08-20T20:42:00.690 回答
9

返回函数的那个​​实际上是以下的快捷方式:

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

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

于 2013-08-20T20:42:01.557 回答
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(长版)。有一个例子。

于 2013-08-20T20:32:13.273 回答