使用通过$ state.go传递的参数的示例

时间:2016-01-27 12:51:32

标签: angularjs

有人可以解释如何使用$ state.go发送的参数吗?在CreatePollController中,我创建了一个轮询,我发送到状态add_data_pollAddDataPollController),但我真的不知道如何访问此参数以在视图中显示它或在控制器中使用它(我试图看到console.log($scope.response)的回复,但它不起作用,有人可以解释一下吗?

angular.module('estudios')

.controller('CreatePollController', ['$scope', 'Restangular', '$state',
function($scope, Restangular, $state) {

  $scope.addPoll = function() {
    if ($scope.allow_anonymous_answer == null)
      $scope.allow_anonymous_answer = false

    var poll = {title: $scope.title, description: $scope.description, allow_anonymous_answer: $scope.allow_anonymous_answer, initial_message: $scope.initial_message, final_message: $scope.final_message};
    Restangular.all('polls').post(poll).then(function(response) {
      $state.go('add_data_poll', response);
    });
  };
}])

.controller('AddDataPollController', ['$scope', 'Restangular',
function($scope, Restangular) {
}]);

这些是相应的状态。

        .state('create_poll', {
      url: '/create_poll',
            parent: 'home',
      templateUrl: 'poll/create_poll.html',
      controller: 'CreatePollController'
    })
        .state('add_data_poll', {
      url: '/create_poll/add_data_poll',
            parent: 'home',
      templateUrl: 'poll/add_data_poll.html',
      controller: 'AddDataPollController'

1 个答案:

答案 0 :(得分:2)

您需要在您的州中定义params或在您的州网址中定义查询参数。

状态params的示例:

.state('add_data_poll', {
      url: '/create_poll/add_data_poll',
      params: {
          // define object with parameters that you want to pass
          // Example:
          id: 1 // 1 is the default parameter if no id is passed
      }    
      parent: 'home',
      templateUrl: 'poll/add_data_poll.html',
      controller: 'AddDataPollController'

这样您就可以发送参数,但它们在查询字符串中不可用,刷新后会丢失。

定义查询参数的示例:

.state('add_data_poll', {
          url: '/create_poll/add_data_poll?someParameter&anotherOne',  
          parent: 'home',
          templateUrl: 'poll/add_data_poll.html',
          controller: 'AddDataPollController'
如果您从传入状态传递它们,

someParameteranotherOne将可用。

传递参数时,您应该定义要传递的参数。

$state.go('some.route', {id: 2, someParam: 'coolParam');

然后您可以在控制器中使用$stateParams访问它们。但首先你需要注射它。

myApp.controller('myCtrl', function($stateParams) {
   console.log($stateParams);
});

从API传递整个响应并不是一个好主意。如果您从响应中选择所需的内容并围绕它们构建您的状态,那就更好了。

详细了解ui-router state params HERE

相关问题