David Rivers
David Rivers

Reputation: 2945

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

What is the functional difference between the following code (in Widget Uno) using a directive definition object (I think it's called..?)...

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

...And this code in Widget Dos?

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

I'm trying to convert a directive that's like Widget Uno into Widget Dos, but where do I reference the templateUrl? Is this possible in Widget Dos?

Upvotes: 33

Views: 7241

Answers (3)

Terry
Terry

Reputation: 14219

Returning only a function in a directive is just a shorthand for the link function in the full definition.

If you are specifying something other than a link function (like templateUrl) then you need to write it the long way:

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"
        };
    }]);

This difference is actually documented here - http://docs.angularjs.org/guide/directive

Upvotes: 44

Buu
Buu

Reputation: 50345

The one returning the function is actually the shortcut for:

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

Use it in case your directive doesn't need template, controller etc. Other than that, there's absolutely no functional difference between those two calling approaches.

Upvotes: 9

Martin Hauner
Martin Hauner

Reputation: 1733

It should work like this:

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

See also http://docs.angularjs.org/guide/directive (long version). There is an example.

Upvotes: 1

Related Questions