AngularJs:问题从$ routeParams对应的工厂获取Jsons

时间:2015-05-18 04:10:03

标签: javascript json angularjs

当用户导航到$scope.lessons时,我希望/writeups/example.json获得/tutorials/example

我的app.js文件启用了html5模式,如下所示:

.when('/', {templateUrl: 'views/home.html', controller: 'HomeCtrl'})
.when('/tutorials/:topic', {templateUrl: 'views/default.html', controller: 'AppCtrl'})
.otherwise({ redirectTo: '/'});

我目前在我的控制器中

$scope.lessons = LessonService.get({topic: $routeParams.topic});

我的工厂看起来像:

app.factory('LessonService', ['$resource', function($resource){
    return $resource('writeups/:topic.json', {}, {
        query: {method:'GET', params:{topic:'bc'}, isArray:true}
    });
}]);

更新:这是我的完整控制器

app.controller('NavCtrl', ['$scope', 'LessonService', '$routeParams', '$mdSidenav', '$timeout','$log', function($scope, $routeParams, LessonService, $mdSidenav, $timeout, $log) {
    function toggleSideNav(name){
        $mdSidenav(name).toggle();
    }

    function selectLesson(name){
        $scope.page = name.Path;
        $scope.toggleSideNav('left');
    }

    $scope.lessons = LessonService.LessonService.get({topic: $routeParams.topic});
    $scope.orderProp = 'Id';
    $scope.toggleSideNav = toggleSideNav;
    $scope.selectLesson = selectLesson;
    $scope.page = 'views/defaultLesson.html';
}]);

2 个答案:

答案 0 :(得分:1)

你需要在你的控制器中包含$ routeParams,如下所示:

angular.module('yourApp')
     .controller('yourCtrl',["$scope", "$routeParams", function ($scope, $routeParams) {
      console.log($routeParams)

}]);

答案 1 :(得分:1)

问题在于我使用'get'而不是'query'。谢谢你的帮助,gregL!这个错误浪费了很多时间:'(

$scope.lessons = LessonService.query({topic: $routeParams.topic});