Angular factory routeParam变量不变

时间:2014-09-19 19:07:27

标签: angularjs

angular.module('app')
  .factory('Answers', function ($resource, $routeParams, $location) {
    return $resource('api/answers?questionid=' + $routeParams.questionId, {
      answerId: '@_id'
    }, {
      update: {
        method: 'PUT'
      }
    });
  });

$scope.findAnswers = function() {
  Answers.query(function(answers) {
    $scope.answers = answers;
  });
};

似乎$routeParams变量没有更新,因为我通过不同的路线浏览我的应用。这是服务的情况吗?我猜我应该在控制器中定义变量,然后将其传递给我的服务?

编辑:

angular.module('intquestApp')
  .factory('Answers', function ($resource, $routeParams, $location) {
    return {
        get: function(questionId) {

          return $resource('api/answers?questionid=' + questionId, {
            update: {
              method: 'PUT'
            }
          });
        }
    };
  });

  Answers.get($routeParams.questionId, function(answers) {
    console.log(answers);
    $scope.answers = answers;
  });

1 个答案:

答案 0 :(得分:0)

我认为方法是将$routeParams注入您的Controller,然后将值传递给服务。

见这里:Use $routeParams in service

所以在你的控制器里面:

Answers.get(passRouteParamValueHere, function(answers) {
  $scope.answers = answers;
});

修改

为什么update内有get?这是你可以尝试的东西,但还没有测试过它:

.factory('Answers',['$resource', function ($resource) {
  return $resource('/api/answers/?questionid=' + questionId, {}, {
    get: { method: 'GET'}
  });
}])

但我更喜欢这种方法:

.factory('Answers',['$resource', function ($resource) {
  return $resource('/api/answers/:qid', {}, {
    get: { method: 'GET'}
  });
}])

然后:

Answers.get({qid: questionIDFromRouteParam}, function(answers) {
  $scope.answers = answers;
});

只是一点清洁