I have a controller for a generic list view:
(angular
.module('app.controllers')
.controller('ItemListContr', [
/*****/ '$scope', 'ItemData',
function($scope, ItemData,) {
...
}
])
);
where ItemData
is not the name of an existing component, but a placeholder name for a service that I inject into the controller from a route:
(angular
.module('app', ['app.controllers', 'app.services'])
.config([
/******/ '$routeProvider',
function ($routeProvider) {
$routeProvider
.when('/books', {
controller: 'ItemListContr',
resolve: {ItemData: 'BookData'},
templateUrl: 'book-list.html'
})
.when('/magazines', {
controller: 'ItemListContr',
resolve: {ItemData: 'MagazineData'},
templateUrl: 'magazine-list.html'
})
}])
);
where BookData
and MagazineData
are services defined in app.services
module.
I also need to use this controller inside a template:
<span ng-controller="ItemListContr">...</span>
but I need to supply the data source ItemData
for it. And I do not know how to do it from a template.
You can use $injector
to get your service by name in the controller.
Like this:
var myApp = angular.module('myApp', []);
myApp.value('ItemData', 'BookData')
myApp.service('BookData', function () {
return {
test: function () {
alert("Test called in BookData!");
}
}
});
myApp.controller('ItemListContr', function ($scope, $injector, ItemData) {
var myService = $injector.get(ItemData);
myService.test();
});
And here is a Fiddle