0

我是 angularjs 的新手,下面的部分总是让我很困惑

angular.module('bookYourSeatApp', [])
    .factory('seats', SeatsFactory)
    .controller('mainCtrl', MainCtrl);

我想获得路由参数,我试过了

function SeatsFactory($rootScope, $timeout, $routeParams) {

function MainCtrl(seats, $routeParams) {

并在其他几个地方插入 $routeparams ,我到处都是错误。代码在小提琴中。如何在下面的代码中注入 $routeparams?

angular.module('bookYourSeatApp', [])
    .factory('seats', SeatsFactory)
    .controller('mainCtrl', MainCtrl);

function SeatsFactory($rootScope, $timeout) {


    //more code
    var factory = {
        map: seats,
        setSeats: setSeats,
        select: selectSeats,
        checkedSeats: checkedSeats,
        availCount: {},
        setAvailCount: function(count) {
            console.log('avail', count);
            checkSelected(count);
        }
    };

    return factory
}

function MainCtrl(seats) {
    // console.log($routeParams);
    var vm = this;
    angular.extend(vm, {
        seats: seats,
        selectionCount: [//[0,1,2,3,4],[
        {id: 0, val: 0}, // object for two-way binding
        ],
        selectedCount: 0
    });

    vm.selectedCount = vm.selectionCount[0];
    seats.setAvailCount(vm.selectedCount);
}
4

2 回答 2

0

您可能在创建工厂和控制器之前错过了这些注入

SeatsFactory.$inject = ['$rootScope', '$timeout'] //make sure if you need 2 params in your SeatsFactory function, inject 2 params as well here
MainCtrl.$inject = ['seats', '$routeParams'] //as well the controller

记住:服务/工厂是一个共享资源,它是单例的,你可能不希望这个单例接收一些依赖的参数,只传递服务/工厂需要继续的数据。

希望能帮助到你。

于 2016-11-01T05:45:19.163 回答
0
angular.module('bookYourSeatApp', [])
    .factory('seats', SeatsFactory)
    .controller('mainCtrl', MainCtrl);

   MainCtrl.$inject = ['$routeParams'];

function SeatsFactory($rootScope, $timeout) {


    //more code
    var factory = {
        map: seats,
        setSeats: setSeats,
        select: selectSeats,
        checkedSeats: checkedSeats,
        availCount: {},
        setAvailCount: function(count) {
            console.log('avail', count);
            checkSelected(count);
        }
    };

    return factory
}

function MainCtrl(seats, $routeParams) {
    console.log($routeParams);
    var vm = this;
    angular.extend(vm, {
        seats: seats,
        selectionCount: [//[0,1,2,3,4],[
        {id: 0, val: 0}, // object for two-way binding
        ],
        selectedCount: 0
    });

    vm.selectedCount = vm.selectionCount[0];
    seats.setAvailCount(vm.selectedCount);
}

我建议不要将 $routeParams 作为服务的初始化参数注入。相反,将其注入 controllers.factory 是单例的

于 2016-11-01T05:04:58.423 回答