angularjs 1.5组件依赖注入

Hok*_*sei 32 angularjs angularjs-directive angularjs-components

这可能听起来很新,但我一直在关注angularjs组件的本教程.

我是组件的新手,我如何注入常量UtilsauthService像我这样的组件?

app.component('tlOverallHeader', {
    bindings: {
        data: '='
    },
    templateUrl: 'js/indexTimeline/components/tl_overallHeader/templates/tl_overallHeader.html',
    controller: function() {
        this.ms = 'tlOverallheader!'
    }
})
Run Code Online (Sandbox Code Playgroud)

谢谢!

Gon*_*ndy 47

您可以将服务注入组件控制器,如下所示:

angular.module('app.module')
        .component('test', {
            templateUrl: 'views/someview.html',
            bindings: {
                subject: '='
            },
            controller: ['$scope', 'AppConfig', TestController]
        });

    function TestController(scope, config) {
        scope.something = 'abc';
    }
Run Code Online (Sandbox Code Playgroud)

或者像这样:

angular.module('app.module')
        .component('test', {
            templateUrl: 'views/someview.html',
            bindings: {
                subject: '='
            },
            controller: TestController
        });

    TestController.$inject = ['$scope', 'AppConfig']
    function TestController(scope, config) {
        scope.something = 'abc';
    }
Run Code Online (Sandbox Code Playgroud)


mzu*_*lch 22

您应该能够像单独的控制器一样将服务注入到组件的控制器中:

controller: function(Utils, authService) {
    this.ms = 'tlOverallheader!'

    authService.doAuthRelatedActivities().then(...);
}
Run Code Online (Sandbox Code Playgroud)


小智 11

接受的答案不是缩小安全性.您也可以在此处使用minification-safe依赖注入表示法:

controller: ['Utils', 'authService',
  function(Utils, authService) {
    this.ms = 'tlOverallheader!'

    authService.doAuthRelatedActivities().then(...);
  },
]
Run Code Online (Sandbox Code Playgroud)