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.
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);
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