Why is the function in angular's DI inline annotation a array element?

前端 未结 2 863
生来不讨喜
生来不讨喜 2021-01-17 19:26

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 th

2条回答
  •  迷失自我
    2021-01-17 20:19

    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'
        };
    });
    

提交回复
热议问题