微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

AngularJS:在控制器中注入时,工厂始终未定义

我正在尝试一个AddressBook Angular应用程序的简单示例.我有一个工厂,它返回一个记录数组,它使用List控制器显示在列表视图中

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

这里’AddressBook’总是在’list_controller’中未定义.知道我哪里错了吗?任何帮助是极大的赞赏.

解决方法

您没有为您的DI注释AddressBook

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

应该:

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

对于其他控制器也是如此.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐