如何在AngularJS的模态实例控制器上访问控制器方法?

时间:2019-01-24 10:11:53

标签: angularjs

您能帮我吗?我正在尝试从模态实例上创建的模板访问父/主控制器上的函数,但无法直接访问它。你能帮我吗? 这是我的代码:

以下是用于访问和显示模式的功能:

openQuestionModalForm() {
    let ctrl = this;
    var modalInstance = ctrl.$modal.open({
        templateUrl: 'questionModal.tmpl.html',
        scope: this.$scope,
        controller: ['$modalInstance', function($modalInstance) {

            this.parentController = ctrl;

            this.modalOptions = {
                mode: 'add',
                actionType: 'add'
            }

            console.log(this.Questionnaire_formController);

            //this.modalOptions.data = angular.copy(data);
            // this.modalOptions = {
            //     mode: mode,
            //     id: id,
            //     data: angular.copy(data),
            //     actionType: mode //set to mode temporarily should be ActionType
            // }
            this.close = $modalInstance.close;
        }],
        size: 'small',
        controllerAs: '$ctrl',
        windowClass: 'addeditcourseware-modal'
    });
    modalInstance.result.then(function(result) {
        try {
            console.log('*-----*', result);
        } catch(e) { 
            console.log('Error!'); 
        }
    })
}

这是由该功能触发的,我将此事件附加到了按钮上

openAddEditCoursewareModal(mode, id, data, actionType) {

    let ctrl = this;
    if(ctrl.QuestionsStore.questionnaireType == 'Questionnaire') {

        this.openQuestionModalForm(); //shows my modal based on the condition

....

<div class="row">
    <div class="columns title-box move-right">
        <p class="title">Questions</p>
        <div class="button_link">
            <button class="button-primary button-default" ng-click="$ctrl.openAddEditCoursewareModal('add')">Add Question</button>
        </div>
    </div>
</div>

现在这是我在父/主控制器上调用函数的部分。

<label class="stacked">
    Question Type:
    <select name="question_type" class="form-field" id="questionType" ng-model="$ctrl.questionModal.data.attributes.question_type" ng-change="$ctrl.getSelectedQuestionType()" ng-required="true">
        <option value="single">Single</option>
        <option value="multiple">Multiple</option>
        <option value="true_or_false">True or False</option>
        <option value="free_text">Free Text</option>
    </select> 
</label>

我正在onchange事件上调用函数getSelectedQuestionType。但是控制台上的结果是undefined

您能帮我吗?

1 个答案:

答案 0 :(得分:1)

您可以通过resolve块传递函数引用,然后在模态控制器中对其进行访问,如下所示:

modalInstance = ctrl.$modal.open({
    ...

    resolve: {
        'getSelectedQuestionType': function () {
            return ctrl.getSelectedQuestionType;
        }
    },
    controller: ['$modalInstance', 'getSelectedQuestionType', function($modalInstance, getSelectedQuestionType) {
        // Bind to controller so that you can call it via $ctrl.getSelectedQuestionType in your view
        this.getSelectedQuestionType = getSelectedQuestionType;
    }

    ...
});

希望这会有所帮助:)