模态确认作为Angular UI指令

时间:2014-03-01 10:59:57

标签: javascript angularjs angularjs-directive angular-ui-bootstrap

我正在尝试使用angular-bootstrap创建一个Angular指令来模仿confirm()函数。

这是一个显示我想要实现的视觉效果和行为的插图: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()'函数的工作指令,但是当我尝试使用模态窗口而不是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
            });
            //*/

          });

        }
      }
    }
  ]);

1 个答案:

答案 0 :(得分: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>

当用户点击“确定”时调用您的函数:

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

DEMO