I have created an angularjs service which I am trying to access in a controller by injecting the service in the controller. Here's the code that I have used:
angular.module('ControllerModule').controller('AwarenessCntrl',['TestService',
function(TestService, $scope, $state)
{
console.log(TestService.list()[0].label);
$scope.goToHome = function()
{
$state.go('home');
};
}]);
I get the following error message in the console: Error: undefined is not an object (evaluating
'$scope.goToHome = function()
{
$state.go('home');
}')
Here's the code that I have used for the service:
angular.module('AppServices').service('TestService', [TestService]);
function TestService() {
var items = [{
id: 1,
label: 'Balle Balle, Service Chal Payi'
}, {
id: 2,
label: 'Item 1'
}];
this.list = function() {
return items;
};
this.add = function(item) {
items.push(item);
};
}
The console is able to print the data from the service; but it also gives an error message that I have mentioned above. What is it that I am doing wrong?
You need to include the $scope, $state
in the string array list too.
See the Angular Docs on Dependency Injection.
Best practice here would be to include build in angular features first and then custom services afterwards.
angular.module('ControllerModule').controller('AwarenessCntrl',['$scope', '$state', 'TestService',
function($scope, $state, TestService)
{
console.log(TestService.list()[0].label);
$scope.goToHome = function()
{
$state.go('home');
};
}]);