angularjs 1.5 component dependency injection
Asked Answered
Y

4

36

this may sound newb, but I have been following this tutorial for angularjs component.

I am new to components and how do I inject a constant Utils or authService to my component like this?

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

thanks!

Yajairayajurveda answered 20/1, 2016 at 4:5 Comment(0)
I
24

You should be able to inject services into your component's controller just like a standalone controller:

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

    authService.doAuthRelatedActivities().then(...);
}
Intermeddle answered 20/1, 2016 at 4:17 Comment(1)
It's admittedly not very intuitive, since with Directives you have to specify the injections both in the array AND in the function header, and the move to the Component controller did away with that pattern. (Yet is not very well discussed in Angular's docs). Took me a lot of searching to come to the same conclusion. Thanks!Clerestory
A
56

You can inject services to component controller like this:

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

    function TestController(scope, config) {
        scope.something = 'abc';
    }

or like this:

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';
    }
Aldas answered 13/10, 2016 at 15:17 Comment(3)
Adding in case ES6 need to assign params to local variable class FranchisesController { constructor($state) { this.$state = $state; } addFranchise(){ this.$state.go('franquicias.agregar'); } }Pettifogger
Where did you find this out? I could not find this in the docs at docs.angularjs.org/guide/component. CheersImmovable
@NickWhiu you can find it under Dependency Injection section - docs.angularjs.org/guide/diAldas
I
24

You should be able to inject services into your component's controller just like a standalone controller:

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

    authService.doAuthRelatedActivities().then(...);
}
Intermeddle answered 20/1, 2016 at 4:17 Comment(1)
It's admittedly not very intuitive, since with Directives you have to specify the injections both in the array AND in the function header, and the move to the Component controller did away with that pattern. (Yet is not very well discussed in Angular's docs). Took me a lot of searching to come to the same conclusion. Thanks!Clerestory
F
12

The accepted answer isn't minification safe. You can use the minification-safe dependency injection notation here too:

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

    authService.doAuthRelatedActivities().then(...);
  },
]
Fated answered 21/7, 2017 at 18:34 Comment(0)
F
1

For Functional style programming which utilizes Factory style services the following syntax gets the job done:

angular.module('myApp')

.component('myComponent', {
    templateUrl: 'myTemplate.html',
    controller: ['myFactory', function(myFactory){
        var thisComponent = this;
        thisComponent.myTemplatemsg = myFactory.myFunc();
    }]
})


.factory('myFactory', [ function(){

    return {
        myFunc: function(){
                    return "This message is from the factory";
                }
    };
}]);     

A word of caution: The same component service/factory you setup for your component is also injectable (and thus accessible) anywhere else in your app including the parent scope and other component scopes. This is powerful but can be easily abused. Hence, it is recommended components only modify data within their own scope so there's no confusion on who is modifying what. For more on this see https://docs.angularjs.org/guide/component#component-based-application-architecture .
However, even the discussion in the aforementioned link only addresses the cautionary use of the two-way-binding property value of '='when using the bindings object. Therefore the same reasoning should apply for component services and factories. If you plan on using the same service or factory in other component scopes and/or the parent scope I recommend setting up your service/factory where your parent scope resides or where your intended congregation of services/factories reside. Especially if you have numerous components using the same service/factory. You don't want it located in some arbitrary component module of which would be hard to find.

Fiduciary answered 20/11, 2017 at 3:52 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.