Wednesday, December 24, 2014

Inject service with Annotation to Controller of Angular

Inject service to controller in Angular is very common operation. Here is sample code to do it.

        var app = angular.module('myApp', []);

        app.service('myService', function () {

        app.controller('myController', function (myService) {

In this example we have injected custom service to controller function by the service name. In case of Angular’s own service, the implementation is like this.

app.controller('myController', function ($http) {

Here we are injecting $http service to controller. This type of implementation is fine if we do not want to minify our .js file, but if we minify then program may not run correctly. The reason is, Once we minify code, the minification program will minify the function argument as well and the dependency injector would not be able to identify service correctly.

There are two ways to solve this problem.
1)      Inject dependency explicitly using $.injector    

At first we have created simple JavaScript function and then injected the dependencies into it.
var app = angular.module('myApp', []);

        //Define function
        function myController() {

        //Inject dependency
        myController.$inject = ['$scope'];

        //Attach function to Angular
        app.controller('myController', myController);

 At last we are attaching the function to module to treat the function as controller of Angular. Now, even we minify the file , the argument name will not minify hence application will run properly.

    2)      Inline annotation

This is simple and compact solution of this problem. Here is single line of code to do same.

       var app = angular.module('myApp', []);

       app.controller('myController',['$scope', function ($scope) {

No comments:

Post a Comment