Skip to content Skip to sidebar Skip to footer

Why Is The Function In Angular's Di Inline Annotation A Array Element?

I have a question for the angularjs folks here. So, I am using angular for quite a while now. However, every time when I am writing a new Controller or something that is using dep

Solution 1:

I don't know the actual reason behind this syntax, but I assume it has to do with consistency --you should be able to use the same syntax regardless of where you need to inject services.

Most places use the syntax in your example: module.controller, module.factory etc. In those places the syntax could bee like requirejs.

However, when defining a directive you can also inject services into its controller. This is usually done if the directive's controller will be used by other directives, e.g. the ngModel directive.

module.directive('myDirective', function () {
    return {
        controller: ['$scope', '$element', function ($scope, $element) {
            // ...
        }]
    };
});

In this case you can't use the requirejs style, but the array style works. I guess this could be one of the reasons the syntax is as it is. There might be others.

As a side note you could define the directive's controller as a normal controller, but this makes the code more verbose, plus you could potentially use the controller in other places than the directive.

module.controller('myDirectiveCtrl', ['$scope', '$element', function ($scope, $element) {
    // ...
}]);

And then define the directive.

module.directive('myDirective', function () {
    return {
        controller: 'myDirectiveCtrl'
    };
});

Solution 2:

You don't have to use the syntax with an array anymore. You can write your code like this:

module.directive('myDirective', function () {
    return {
        controller: function ($scope, $element) {
            // ...
        }
    }
});

Read more here

Post a Comment for "Why Is The Function In Angular's Di Inline Annotation A Array Element?"