AngularJS:在控制器注射时厂始终是不确定的 [英] AngularJS: Factory is always undefined when injected in controller

查看:91
本文介绍了AngularJS:在控制器注射时厂始终是不确定的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想通讯簿角应用简单的例子。我有一个工厂的记录回报阵列,在列表视图中显示得到列表控制器

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
            }
        );
    };
}]);

下面地址簿永远是不确定的里面list_controller。任何输入往哪里去错..?

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

推荐答案

您没有注释地址簿为您的DI

You are not annotating AddressBook for your DI

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

应该是:

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

同为其他控制器。

Same for the other controller.

这篇关于AngularJS:在控制器注射时厂始终是不确定的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆