在指令定义中返回对象和函数有什么区别?

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中是否可能实现这一点?

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


9
返回的函数实际上是以下缩写:
angular.module("app").directive('widgetDos', function($http) {
    return {
        link: function(scope, element, attrs) {
            //...
        };
    }
});

如果您的指令不需要模板、控制器等内容,请使用它。除此之外,这两种调用方式之间没有任何功能上的区别。


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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接