从angularui中的嵌套状态访问父状态控制器

时间:2015-08-17 14:11:35

标签: angularjs angular-ui

我在项目中定义了嵌套状态:

        $stateProvider
    .state("MultiStepForm", {
        url: "/Sensor/MultiStepForm",
        templateUrl: "/app/MultiStepForm/MultiStepForm.html",
        controller: "MultiStepFormController",
        controllerAs: "MultiStepLogic"
    })
        .state('MultiStepForm.step1', {
            url: '/step1',
            templateUrl: '/app/MultiStepForm/NestedViews/FormStep1.html',
            controller: "MultiStepLogicStep1Controller",
            controllerAs: "Step1"
        })
        .state('MultiStepForm.step2', {
            url: '/step2',
            templateUrl: '/app/MultiStepForm/NestedViews/FormStep2.html',
            controller: "MultiStepLogicStep2Controller",
            controllerAs: "Step2"
    })
        .state('MultiStepForm.step3', {
            url: '/step3',
            templateUrl: '/app/MultiStepForm/NestedViews/FormStep3.html',
            controller: "MultiStepLogicStep3Controller",
            controllerAs: "Step3"
        });

MultiStepForm 状态下,我已定义此属性:

var self = this;
this.data = "someObject";

MultiStepForm.step3 状态控制器(步骤3)中,我想访问在父状态控制器中定义的属性:

this.data =“来自MultiStepForm.step3状态的一些数据”

我的问题是如何从嵌套状态控制器访问父属性?

1 个答案:

答案 0 :(得分:1)

在将数据注入控制器之前,您需要“解析”该数据。如果它在父母那里得到解决,那么孩子们就可以使用它。

像这样:

$stateProvider
    .state("MultiStepForm", {
        url: "/Sensor/MultiStepForm",
        templateUrl: "/app/MultiStepForm/MultiStepForm.html",
        controller: "MultiStepFormController",
        controllerAs: "MultiStepLogic",
        resolve: {
          your_custom_data: ['$stateParams', 'another_service',
                function($stateParams, another_service) {
                    //you can use $stateParams or other services here as needed to get the data you want
                    return the_value_of_your_custom_data;
                }],
    })

然后在你的控制器中:

angular
    .module('your_app')
    .controller('MultiStepLogicStep3Controller', MultiStepLogicStep3Controller);

function MultiStepLogicStep3Controller($state, your_custom_data) {
    //access your $state or custom data here
    this.custom_data = your_custom_data;
}