首页 > 解决方案 > 如何从 ui-modal AngularJS 调用父函数?

问题描述

这是我的模态函数:

$uibModal.open({
   templateUrl: config.baseUrl + '/ClientApp/Views/Modals/userEditModal.html' + config.scriptVersion,
   size: size,
   scope: $scope,
   controller: function ($scope, $uibModalInstance) {                
     $scope.cancel = function () {
       $uibModalInstance.close();
     };
   }
}).result.catch(function (resp) {           
   if (['cancel', 'backdrop click', 'escape key press'].indexOf(resp) === -1) {
     throw resp;
   }
})

$uibModal是在我有其他$scope变量和函数的控制器内部。如果我ng-repeat在模态内部使用父范围对象进行操作ng-repeat!但是如果我调用一个函数 ex。doSomething()或尝试在ng-classex 中使用范围对象。ng-class="{'css': doSomething()}"- 它没有。如您所见,我$scope在模态中分配了范围属性。我究竟做错了什么?我也尝试过调用该函数,$parent但仍然无法正常工作。ng-if="$parent.doSomething()"

标签: angularjsangular-ui-bootstrapangular-ui-modal

解决方案


在定义 modal 时仅使用对已经存在的函数的引用怎么样?将属性绑定到控制器的范围并将其传递给您的模态。

bindToController: true,
controllerAs: 'parent'

然后就通过doSomething

function myController($uibModal) {

    var parent = this;
    parent.doSomething = function() {
        /** does something ... **/
    };

    $uibModal.open({
       templateUrl: config.baseUrl + '/ClientApp/Views/Modals/userEditModal.html' + config.scriptVersion,
       size: size,
       scope: $scope,
       controller: function ($scope, $uibModalInstance) {  

         $scope.doSomethingDelegate = parent.doSomething;

         // ... more stuff
       }
    })
}

然后在你的模态模板中

<element ng-if="doSomethingDelegate()"></element>

推荐阅读