Confirmation dialog directive on button type="submit" - AngularJS

时间:2015-07-28 17:02:21

标签: javascript angularjs

I want to create a directive for confirmation dialog, when I submit the form. The question I found here is similar, but it doesn't solve my issue:

<button confirm-ng-click="Reset password?" type="submit" class="md-primary">Reset</button>

And the JS:

(function () {
    'use strict';

    angular.module('haha', [])
        .directive('confirmNgClick', [ConfirmNgClick]);

    function ConfirmNgClick() {
        return {
            priority: -1,
            restrict: 'A',
            link: function (scope, element, attrs) {
                element.bind('click', function (event) {
                    var message = attrs.confirmNgClick;
                    if (message && !confirm(message)) {
                        event.stopImmediatePropagation();
                        event.preventDefault();
                    }
                })
            }
        }
    }
})();

So, when I click button, the dialog doesn't show up. What am I missing?

2 个答案:

答案 0 :(得分:2)

将代码插入小提琴并查看控制台会产生此错误:

未捕捉错误:[$ injector:nomod]模块&#39;哈哈&#39;不可用!您要么错误拼写了模块名称,要么忘记加载它。如果注册模块,请确保将依赖项指定为第二个参数。

注册模块时,需要指定一个数组作为第二个参数。

&#13;
&#13;
(function() {
  'use strict';

  // Notice second argument here
  angular.module('haha', [])
    .directive('confirmNgClick', [ConfirmNgClick]);

  function ConfirmNgClick() {
    return {
      priority: -1,
      restrict: 'A',
      link: function(scope, element, attrs) {
        element.bind('click', function(event) {
          var message = attrs.confirmNgClick;
          if (message && !confirm(message)) {
            event.stopImmediatePropagation();
            event.preventDefault();
          }
        })
      }
    }
  }
})();
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="haha">
  <button confirm-ng-click="Reset password?" type="submit" class="md-primary">Reset</button>
</div>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

我只是在这里猜测,但我认为您的问题如下

angular.module('haha')
    .directive('confirmNgClick', [ConfirmNgClick]);

第一次创建模块时,angular.module函数需要(至少)两个参数 See the related documentation说:

  

如果指定了 [第二个参数] ,则正在创建新模块。   如果未指定,则进一步检索模块   配置。

所以将上面的代码更改为

angular.module('haha', [])
    .directive('confirmNgClick', [ConfirmNgClick]);

请注意第二个[]参数。

See this plnkr for working example.

如果删除第二个[]参数,则顺便提一下控制台上会出现错误。