将函数传递给角度js组件

时间:2016-12-30 05:48:58

标签: angularjs angular-ui-bootstrap

我有一个组件(父组件),我在其中使用:

显示模态
showModal() {
    this.modalInstance = this.modal.open({
        template: "<upload-modal on-close='$ctrl.closeModal()'></upload-modal>"
    });
}

这是上传组件(子组件)的代码:

import uploadController from "./upload.controller";
export const UPLOAD_COMPONENT_NAME = "uploadModal";

export const uploadComponent = {
   templateUrl: "templates/profile/upload-image.html",
   controller: uploadController,
   bindings: {
    'onClose': "&"
   }
};

这是我调用onClose函数的方法(upload-image.html):

 <div class="modal-content">
<form id="addReview" name="addReview" role="form" class="form-horizontal">
    <div class="modal-header">
        <button type="button" ng-click="$ctrl.onClose()" class="close"><span
                aria-hidden="true">×</span><span class="sr-only">Close</span></button>
        <h4 id="myModalLabel" class="modal-title">Upload your profile image</h4>
    </div>
    <div class="modal-body">
        <input id="input-id" type="file" class="file" data-preview-file-type="image">
    </div>
    <div class="modal-footer">
        <button ng-click="$ctrl.onClose()" type="button" class="btn btn-default">
            Cancel
        </button>
        <button type="submit" class="btn btn-primary">Update</button>
    </div>
</form>

但是,永远不会调用父组件中的函数closeModal。我在这里做错了什么?

1 个答案:

答案 0 :(得分:0)

您需要将该函数传递给组件,而不是它的调用

变化:

template: "<upload-modal on-close='$ctrl.closeModal()'></upload-modal>"

进入这个:

template: "<upload-modal on-close='$ctrl.closeModal'></upload-modal>"

如果您发布控制器代码以查看您是否正确调用此功能,也会有所帮助。 应该是这样的

if ($ctrl.closeModal && angular.isFunction($ctrl.closeModal()) {
    $ctrl.closeModal()(anyValueYouWantToPass);
}

<强> P.S

ui-bootstrap模式已经返回lifecycle callbacks as promisesopen方法返回模态对象,其中一个属性是

  

关闭(类型:保证) - 在关闭模态并完成动画时解析。