返回指令定义中的对象和函数之间的区别

Differences between returning an object vs a function in a directive definition?

本文关键字:函数 之间 区别 对象 定义 返回 指令      更新时间:2023-09-26

以下代码(在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中可能吗?

只返回指令中的函数只是完整定义中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

返回函数的函数实际上是的快捷方式

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

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

它应该这样工作:

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(长版)。有一个例子。