从$ routeProvider将模块配置中的服务数据传递给Controller?

时间:2014-08-27 13:48:47

标签: angularjs

我对角度很新,并且已经阅读了许多教程等,并且遇到以下问题:

搜索-module.js

var Search = angular.module('SearchApp',["ngCookies","ngRoute"]);

Search.run(function ($http, $cookies) {
    $http.defaults.headers.common['X-CSRFToken'] = $cookies['csrftoken'];
});

Search.config(function($routeProvider){
    $routeProvider
        .when('/', {
            controller:'searchCtrl',
            resolve: {
                inv_items: function (InventoryService){
                    return InventoryService.get('red');
                }
            }
        })
        .otherwise({
            redirectTo: '/'
        })
});

数据-service.js

Search.factory('InventoryService', function ($http, $q) {

    var api_url = "api/inventory/";

    return {

        get: function (inventory) {
            var url = api_url + inventory;
            var defer = $q.defer();
            $http({method: 'GET', url: url}).
                success(function (data, status, headers, config){
                    defer.resolver(data);
                })
                .error(function (data,status, headers, config){
                    defer.reject(status);
                });
            return defer.promise;
        }
    }
});

搜索-controller.js

Search.controller('searchCtrl', function($scope){

    $scope.selected = 'have';

    $scope.setSection = function(section){
        $scope.selected = section;
    };

    $scope.isSelected = function(section){
        return $scope.selected == section;
    };

});

就像我之前提到过的那样,我昨天刚刚接受了角色。基本上从我写的内容中我明白,当URL是' /'那么服务将被启动并且控制器将被调用?我想知道的是为什么我不能在我的控制器中使用inv_items?我得到以下error

我是否需要将某种全局传递给包含inv_items的控制器,或者我是否缺少一些重要的知识?

谢谢!

1 个答案:

答案 0 :(得分:0)

解决变量' inv_items'不会自动添加到' searchCtrl'。

的范围内
Search.controller('searchCtrl', function($scope, inv_items){ //Add this
    $scope.inv_items = inv_items; //And this
    $scope.selected = 'have';

    $scope.setSection = function(section){
        $scope.selected = section;
    };

    $scope.isSelected = function(section){
        return $scope.selected == section;
    };
});

假设其余代码有效,您的' inv_items'现在应该可以在那个范围内使用。