Injecting services into AngularJS directive controller directly

后端 未结 2 1528
傲寒
傲寒 2021-02-19 07:44

I understand how Angular dependency injection works with directives but wanted clarification on something. I have a dummy test directive as follows:

app.directiv         


        
相关标签:
2条回答
  • 2021-02-19 08:20

    You can do this also. Much better way by splitting directive and its controller in a single file. Or you can write in separate files. But, better understand

    app.directive('throbberDirective', 
    [   
        function(){
            return {
                restrict: "EA",
                templateUrl: "common/utils/throbbers/throbber.html",
                controller: throbberController
            }
        }
    ]);
    app.controller('throbberController', throbberController);
    throbberController.$inject = ['$scope', '_$ajax'];
    function throbberController($scope){
         $scope.throbber = _$ajax.getThrobberConfigs();
         $scope.throbber.templateName = $scope.throbber.templateName;
    
    }
    
    0 讨论(0)
  • 2021-02-19 08:21

    In this case, you're receiving the same service, so it likely doesn't matter too much. I personally prefer to keep them as localized as possible; if you don't need $filter in the link function or something like that, I'd just inject it into the controller.

    In certain cases, this may also make it easier to mock dependencies during testing.

    0 讨论(0)
提交回复
热议问题