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

Dav*_*ers 33 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"
        };
    }]);
Run Code Online (Sandbox Code Playgroud)

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

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

我正在尝试将类似Widget Uno的指令转换为Widget Dos,但是我在哪里引用templateUrl?这可能在Widget Dos中吗?

Ter*_*rry 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"
        };
    }]);
Run Code Online (Sandbox Code Playgroud)

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


Buu*_*yen 9

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

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

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