如何将子组件中的对象传递给angularJS中的父项

时间:2017-04-16 03:46:24

标签: javascript angularjs angular-ui-router angularjs-scope

我想在angularJS 1.5x中做一个多步骤,这是我的文件格式

-events
--events.component.js
--events.controller.js
-form.component.js
-form.controller.js

在我的form.component.js我使用UI路由器路由到表单的不同部分..

var createForm = {
        templateUrl: 'app/components/event/form.html'
    };

    angular
        .module('components.event')
        .component('createEvent', createEvent)
        .config(function($stateProvider) {
            $stateProvider
                .state('form', {
                    url: '/form',
                    component: 'createForm'
                })
                // nested states 
                .state('form.events', {
                    url: '/events',
                    component: 'createEvents'
                })
        });
在父控制器(form.controller.js)中有一个对象$ scope.formData:

function EventController($scope) {

        $scope.formData = {};

    }

    angular
        .module('components.event')
        .controller('EventController', EventController);

我想从我的事件控制器访问$ scope.formData。我已经尝试在events.controller.js中使用$ scope。$ parent.formData但这对我来说还不起作用

function EventController($scope) {

        $scope.parentformData = $scope.$parent.formData;

    }

    angular
        .module('components.event')
        .controller('EventController', EventController);

关于我如何做到这一点的任何想法?

1 个答案:

答案 0 :(得分:0)

希望下面的代码很有帮助!

//No need to pass the .js file name.
//Just pass the name / element of your controller.

//eg:
    // assuming this is your controller definition/declaration inside form.controller.js
    function formController($scope) {
        // code insde controller
    }

    // assuming this code is written inside events.controller.js 
    function EventController($scope) {

       var formControllerScope = angular.element(formController).scope();
       console.log(formControllerScope.formData);
    }