I am trying a simple example of an AddressBook Angular application. I have a factory that returns an array of records and it it gets displayed in a list view using a 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 idea where I am going wrong? Any help is greatly appreciated.
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.
Another approach is using $inject declaration of your dependencies , which are being used in the same order as arguments to your functionas show below . It helps in injecting the right services after the minification of the code.
var App = angular.module('myApp',[]);
App.controller('myCtrl',myCtrl);
//inject your dependencies;
myCtrl.$inject = ["$scope", "AddressBook","anotherService"] //
function myCtrl($scope,AddressBook,anotherService){
.....
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With