Yogesh Devatraj Yogesh Devatraj - 4 months ago 27
AngularJS Question

AngularJS: Factory is always undefined when injected in controller

I am trying simple example of AddressBook Angular application. I have a factory with return array of records and getting displayed on list view using List controller

angular.module('abModule', ['ngRoute'])
.factory('AddressBook', function() {
var address_book = [
{
"id": 1,
"first_name": "John",
"last_name": "Doe",
"age": 29
},
{
"id": 2,
"first_name": "Anna",
"last_name": " Smith",
"age": 24
},
{
"id": 3,
"first_name": "Peter",
"last_name": " Jones",
"age": 39
}
];
alert('inside factory function');
return {
get: function() {
return address_book
}
};
})
.config(function($routeProvider) {
$routeProvider
.when('/', {
controller:'list_controller',
templateUrl:'list.html'
})
.when('/add', {
controller:'add_controller',
templateUrl:'add.html'
})
.otherwise({
redirectTo:'/'
});
})
.controller('list_controller',['$scope', function ($scope, AddressBook) {
$scope.address_book = AddressBook;
}])
.controller('add_controller',['$scope', function ($scope,AddressBook) {
//$scope.entry = {};
$scope.save = function() {
AddressBook.set(
{
"id": $scope.address_book.length +1,
"first_name":$scope.entry.firt_name,
"last_name":$scope.entry.last_name,
"age":$scope.entry.age
}
);
};
}]);


Here 'AddressBook' is always undefined inside 'list_controller'. Any input where it is going wrong.. ?

Answer

You are not annotating AddressBook for your DI

.controller('list_controller',['$scope', function ($scope, AddressBook) {
    $scope.address_book = AddressBook;
}])

should be:

.controller('list_controller',['$scope', 'AddressBook', function ($scope, AddressBook) {
    $scope.address_book = AddressBook;
}])

Same for the other controller.

Comments