无法从其他控制器获取状态参数

时间:2017-08-07 10:10:43

标签: javascript angularjs

controller1:

app.controller('task1Controller',['$scope', 'taskFactory', '$state', function($scope, taskFactory, $state){

    $scope.taskData = {};

    taskFactory.get().then(function(response){
        $scope.jsonData = response.data.data.resultCareGivers[0];
        $scope.taskData.fname = $scope.jsonData.firstName;
        $scope.taskData.lname = $scope.jsonData.lastName;
        $scope.taskData.email = $scope.jsonData.email;
    });

    $scope.viewDetails = function(){
        console.log('taskData before route ', $scope.taskData);
        $state.go('view-details', {some: $scope.taskData});
    };
}]);

控制器2:

app.controller('viewDetailsController', ['$scope', '$stateParams', '$state', function($scope, $stateParams, $state){
    console.log('receiveing state params ', $stateParams); //returns null
}]);

HTML:

<div ng-controller="task1Controller">
    <div>
        <a ng-click="viewDetails()">View Details</a>
    </div>
</div>

<div class="container" id="main" ng-controller="viewDetailsController"></div>

无法从控制器1到控制器2获取状态参数。我试图在state.go('params here')中发送params,但我怎么也无法在控制器2中检索它(返回null)。

config:

在州提供商

中配置的路由
app.config(['$stateProvider', '$urlRouterProvider', 
    function($stateProvider, $urlRouterProvider){

    $urlRouterProvider.otherwise('task1');
    var header = {
        templateUrl: 'views/header.html',
        controller: function ($scope) {
        }
    };

    $stateProvider
    .state('task1', {
        url: "/task1",
        views: {
            header: header,
            content: {
                templateUrl: 'views/task1.html',
                controller: function($scope){
                    console.log('$scope1 ', $scope.image);
                }
            }
        }
    })
    .state('view-details', {
        url: "/view-details",
        views: {
            header: header,
            content: {
                templateUrl: 'views/view-details.html',
            }
        }
    });
}]);

1 个答案:

答案 0 :(得分:1)

您可以使用$stateParams访问该值。您必须使用$stateParams

引用参数

<强>控制器

app.controller('viewDetailsController', ['$scope', '$stateParams', '$state', function($scope, $stateParams, $state){
    console.log('receiveing state params ', $stateParams.some); //returns some
}]);

<强>配置

 .state('view-details', {
        url: "/view-details",
        params: { some: null },
        views: {
            header: header,
            content: {
                templateUrl: 'views/view-details.html',
            }
        }

有关如何通过$stateParams将对象从控制器传递到另一个对象的详情,请查看Pass object as parameter in $state.go