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