为什么我不能使用$ location.path()来获取$ resource的数据?

时间:2014-03-30 21:17:05

标签: angularjs

我已经编写了一个服务来使用数据库中的$ resource来获取数据:

    .factory('Students', ['$resource', function($resource) {
    return $resource('/students', {}, {
        query: {method: 'GET', isArray: true}
    });
    }])

但我希望在我的网页的网址更改时获取不同的数据。所以我改成了这个:

    factory('Students', ['$resource', function($resource) {
    var urlBase = '/group-';
    return function(urlExt) {
        var url = urlBase + urlExt;
        return $resource(url, {}, {
            query: {method: 'GET', isArray: true}
        });
    }
}]);

我在控制器中称它为:

    $scope.students = Students($location.path());

我没有收到错误,但它没有返回任何内容。是否与页面不刷新但加载模板视图有关?

1 个答案:

答案 0 :(得分:0)

我认为你可以这样做:

.factory('Students', ['$resource', '$location', function($resource, $location) {
  return $resource($location.path(), {}, {
    query: {method: 'GET', isArray: true}
  });
}])

您也可以尝试:

.factory('Students', ['$resource', '$location', function ($resource, $location) {
  return $resource(':dest', {dest:$location.path()});
}]);

我不确定:dest是否可以在没有前导斜线的情况下工作,并且我非常确定$location.path()有一个前导斜杠,因此您可能需要将其更改为:

.factory('Students', ['$resource', '$location', function ($resource, $location) {
  return $resource('/:dest', {dest:$location.path().substr(1)});
}]);

好的,根据您的评论,为了防止网址编码错误,请再次尝试第一个,但注入$ sce并使用它将网址列入白名单,这可能是该网址的原始问题:

.factory('Students', ['$resource', '$location', '$sce', function($resource, $location, $sce) {
  return $resource($sce.trustAsResourceUrl($location.path()), {}, {
    query: {method: 'GET', isArray: true}
  });
}])