mcmwhfy
mcmwhfy

Reputation: 1686

Inject service into angular 1.5 component

I'm trying to initialize a test.service.js from an angular1.5 component and I don't really know how to that. I have used this structure for angular components:

var testComponent =  {
    templateUrl: "app/components/test.component.html",
    controllerAs: "mvm",
    bindings:{
        bindingInput: "=",
},
controller: function(){
      var mvm = this;

    }
};
angular.module('myApp').component('testComponent', testComponent);

Upvotes: 0

Views: 661

Answers (2)

Renaud is Not Bill Gates
Renaud is Not Bill Gates

Reputation: 2084

Just inject it using the controller as following :

...
},
controller: ['testService', function(testService){
  var mvm = this;
}],
...

Upvotes: 1

31piy
31piy

Reputation: 23859

You can inject the service right into the controller like this:

....
    controller: function(testService) {
      var mvm = this;
    }
};

To prevent testService getting obfuscated by a minification plugin, let the injector service know about the dependencies as well.

var Controller = function(testService) {
   // Your controller code here
};

Controller.$inject = ['testService'];

var testComponent = {
  ...
  controller: Controller, // Assign controller in component
  ...
};

Upvotes: 1

Related Questions