Angular: Add ngClick from js

做~自己de王妃 提交于 2019-12-06 03:24:41

I created a directive:

  • It should be used in conjunction with ngIf.
  • ngIf should refer to an assignable variable on the scope
  • For example don't do this: ng-if='myFunc()' or ng-if='var1 || var2'

here is a plunker: http://plnkr.co/edit/fmNH2PbRrruRqGFYiui1?p=preview

Directive:

app.directive('errorBox', function($document, $parse){
  return {
    link: function(scope,elm,attrs) {
      var clickHandler = function(){
        scope.$apply(function(){
           $parse(attrs.ngIf).assign(scope.$parent,'')
        })
        $document.off('click', clickHandler);
      };

      $document.on('click', clickHandler)
    }
  }
});

html:

<div ng-if="errorMessage" error-box class="alert error">
  <div class="alert-text">{{ errorMessage }}</div>
</div>

You can add a $scope variable that keeps track if it's 'allowed' to click. Then you can do something like this

<div ng-click="isDisabled || yourAction()"></div>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!