将angularUI popover指令扩展为创建确认popover

3

我正在尝试在AngularJS中创建一个简单的确认弹出框。我已经使用AngularUI添加了很多其他组件,这就是为什么它似乎是自然的选择来扩展。

我已经在plnkr中创建了一个示例,但实质上我想能够像这样简单地向按钮添加确认...

<button confirm="Are you sure you want to delete what ever" confirm-func="deleteThing()" confirm-placement="right" confirm-title="Are you sure?" class="btn btn-default">Delete?    </button>

这段代码可以使用我的自定义模板,生成一个包含取消或确认按钮的弹出框。但我需要能够通过“confirm-func”属性传递任何要在确认按钮点击时运行的函数。无论我如何尝试,都无法使其正常工作。下面是扩展AngularUI的指令:

angular.module('plunker', ['ui.bootstrap']).directive( 'confirmPopup', function () {
  return {
    restrict: 'A',
    replace: true,
    scope: { title: '@', content: '@', placement: '@', animation: '&', isOpen: '&', func: '&' },
    templateUrl: 'confirmPopup.html',
    link: function ($scope, element, attrs) {
      $scope.confirm = function(){

        $scope.func();//here is where we want to run the function, but it does not work!
        $scope.$parent.tt_isOpen = false;
      }
      $scope.cancel = function(){
        $scope.$parent.tt_isOpen = false;
      }
    }
  };
})
.directive( 'confirm', [ '$tooltip', function ($tooltip) {
    return $tooltip( 'confirm', 'confirm', 'click' );
}]);

附带Plunkr示例:http://plnkr.co/edit/W9BWMc3x5khuaMEL7lp1?p=preview


根据我的理解,$tooltip服务并没有旨在打开其实现并允许扩展。相反,它是在popuptooltip(以及可能的其他指令)之间进行内部代码共享的好方法。不幸的是,我没有看到任何简单直接的方法来做到这一点,除非将一个编译后的元素传递给content,如 $compile(toolTipContent)(scope)。然而,这需要对angular.ui进行重大更改。 - musically_ut
如何开始做这件事?你有例子吗? - NimmoNet
3个回答

3

这不是对您特定问题的直接答案,但我在我的项目中寻求类似的解决方案(确认弹出框的简单指令),最终采用了此博客文章中的解决方案:

http://wegnerdesign.com/blog/angular-js-directive-tutorial-on-attribute-bootstrap-confirm-button/

它对我来说一直表现良好。我稍微修改了一下,以使其能够通过属性应用自定义CSS类。我的修改在此处:

https://github.com/sergkr/swot/blob/master/client/directives/confirmButton.js

用法示例:

<button type="button" confirm-button="deleteQuestion($index)" message="Are you sure you want to remove this question?"></button>

以下是该指令的截图示例:

确认气泡截图


不幸的是,尽管这是一个解决方案,但它并不理想,因为它依赖于jQuery而不是AngularUI。 - NimmoNet
@NimmoNet 不是依赖于 jQuery 吗?它应该已经在您的项目中了... - cecilphillip
@Sergey K,我该如何调整您指令的偏移量?当我使用“left”位置时,它会与按钮重叠,因此我想将其向左移动更多。 - WABBIT0111

1
我已经完成了你需要的内容,尽管它有点像黑客行为。我制作了一个plunk。 基本上,诀窍是将你自己的控制器注入到$tooltip返回的新指令实例中。
var tt = $tooltip( 'confirm', 'confirm', 'click' );
tt.controller = 'ConfirmCtrl';
return tt;

你需要调整Popover模板以便它们可以调用你的控制器方法。

<button class="btn-block btn btn-danger" ng-click="$parent.confirm()">Confirm </button>
最新的步骤是从您的控制器调用确认处理程序。
var fn = $parse($attrs.confirmHandler);

$scope.confirm = function(){
  fn($scope);
  $scope.tt_isOpen  = false;
};

希望能对您有所帮助!我不是一个Angular专家,所以欢迎任何关于该方法的评论/反馈。


1

没有直接传递confirm-func参数的方法。您需要自己实现工具提示指令,而不是使用$tooltip服务。有一种不太好的解决方案,但我不能推荐这种方式:

您可以使用

$scope.$parent.deleteThing();

替代

$scope.func();//here is where we want to run the function, but it does not work!

这样做不可行,因为传入的函数根据情况可能是任何东西。 - NimmoNet

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,