14

我正在尝试使用angular-bootstrap制作一个Angular指令来模拟confirm()函数。Modal确认为一个Angular UI指令

这里是在视觉效果和行为我想实现一个普拉克:http://embed.plnkr.co/27fBNbHmxx144ptrCuXV/preview

现在我想用一个指令来调用模态窗口:

<div ng-controller="ModalDemoCtrl"> 
    <ul> 
     <li ng-repeat="item in items"> 
       {{ item }} <a ng-really-message="Are you sure ?" ng-really-click="reallyDelete(item)">Delete</a> 
     </li> 
    </ul> 
</div> 

我做了一个工作指令它使用'confirm()'函数,但是当我尝试使用模式窗口而不是确认函数时,出现“$digest already in progress”错误。

的普拉克:http://plnkr.co/edit/JSOInyZIvMtBZFaNvQRO?p=preview

var ModalDemoCtrl = function($scope, $modal) { 

    $scope.items = ['item1', 'item2', 'item3']; 

    $scope.reallyDelete = function(item) { 
    $scope.items = window._.remove($scope.items, function(elem) { 
     return elem != item; 
    }); 
    }; 
}; 

angular.module('ngReallyClickModule', ['ui.bootstrap']) 
    .directive('ngReallyClick', ['$modal', 
    function($modal) { 

     var ModalInstanceCtrl = function($scope, $modalInstance) { 
     $scope.ok = function() { 
      $modalInstance.close(); 
     }; 

     $scope.cancel = function() { 
      $modalInstance.dismiss('cancel'); 
     }; 
     }; 

     return { 
     restrict: 'A', 
     link: function(scope, element, attrs) { 
      element.bind('click', function() { 
      var message = attrs.ngReallyMessage || "Are you sure ?"; 

      /* 
      //This works 
      if (message && confirm(message)) { 
       scope.$apply(attrs.ngReallyClick); 
      } 
      //*/ 

      //*This doesn't work 
      var modalHtml = '<div class="modal-body">' + message + '</div>'; 
      modalHtml += '<div class="modal-footer"><button class="btn btn-primary" ng-click="ok()">OK</button><button class="btn btn-warning" ng-click="cancel()">Cancel</button></div>'; 

      var modalInstance = $modal.open({ 
       template: modalHtml, 
       controller: ModalInstanceCtrl 
      }); 

      modalInstance.result.then(function() { 
       scope.$apply(attrs.ngReallyClick); //raise an error : $digest already in progress 
      }, function() { 
       //Modal dismissed 
      }); 
      //*/ 

      }); 

     } 
     } 
    } 
    ]); 

+0

http://stackoverflow.com/questions/29602222/create-a-simple-bootstrap-yes-no-confirmation-or-just -notification-alert-in-angu/37265529#37265529 –

回答

27

尝试功能结合(&):

scope:{ 
    ngReallyClick:"&", //declare a function binding for directive 
    item:"=" //the current item for the directive 
}, 

你的HTML:

<a ng-really-message="Are you sure ?" ng-really-click="reallyDelete(item)" item="item">Delete</a> 

打电话给你的功能,当用户点击OK:

modalInstance.result.then(function() { 
    scope.ngReallyClick({item:scope.item}); //call the function though function binding 
}, function() { 
       //Modal dismissed 
}); 

DEMO

+5

谢谢!我不知道指令中的绑定。实际上,这个实现甚至不需要'item =“item”'部分。我结束了这个解决方案:http://plnkr.co/edit/tvc1u7EJVkyRqfLZEtTq?p=preview – mmai

+0

这太棒了!只是想分享另一个有用的链接:http://weblogs.asp.net/dwahlin/building-an-angularjs-modal-service – Jordan