【问题标题】:element.on('click') on a directive within ng-if doesn't workng-if 中指令上的 element.on('click') 不起作用
【发布时间】:2016-02-16 01:49:18
【问题描述】:

如果用户未登录,我会在链接上使用指令来提供模式登录。到目前为止,它适用于所有用例。在新情况下,该指令是 ng-if 部分的一部分。

在 sn-p 上,第一个链接工作正常,第二个不起作用。 element.on('click', function(evt) {…}) 永远不会调用。并且不检查权限,也不会向用户提示任何模态登录。

好的,如果我使用 ng-show 而不是 ng-if,那么两个链接都可以工作。因为 ng-show 不会从 DOM 中移除元素,也不会像 ng-if 那样创建子作用域。但在我的用例中,我必须使用 ng-if。我能做些什么?如何提供一个在 ng-if 和其他 ng-x 指令中也起作用的点击事件?

var app = angular.module('myapp', []);

app.controller('MyCtrl', function($timeout) {
  // something stupid here
  var vm = this;
  vm.bar = false;
  $timeout(function() {
    vm.bar = true;
  });
});

/**
 * I need an isolate scope, because some user state checks
 * will take place in the directive. And there are different
 * login forms based on type and other attributes.
 */
app.directive('modalLogin', function() {
  return {
    restrict: 'A',
    scope: {
      type: '@mlType'
    },
    compile: function(element, attrs) {
      if (element[0].nodeName !== ('A')) {
        // use directive only at links
        return function() {};
      }

      return function(scope) {
        function checkPermissions() {
          // do the magic here
          alert('foo');
        }

        element.on('click', function(evt) {
          evt.preventDefault();
          checkPermissions();
        })
      }
    }
  }
})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<section ng-app="myapp" ng-controller="MyCtrl as FOO">
  <div>
    <!-- it works -->
    <a href="/myroute/" modal-login ml-type="simple-login">Klick me, I'm working well</a>
  </div>

  <!-- it doesn't work -->
  <div ng-if="FOO.bar">
    <a href="/another-route/" modal-login ml-type="theme-login">Klick me, I'm nested within a ng-if</a>
  </div>
</section>

【问题讨论】:

  • 如果去掉控制器中的$timeout会发生什么?
  • 如果我使用 vm.bar = true; 而不使用 $timeout - 是一样的 ;(

标签: angularjs angularjs-directive event-handling angular-ng-if


【解决方案1】:

使用link 代替compile

link: function(scope, element) {

  function checkPermissions() {
    alert('foo');
  }

  element.on('click', function(evt) {
    evt.preventDefault();
    checkPermissions();
  });

}

【讨论】:

  • 谢谢,它似乎工作正常(第一次检查)。我会用改变后的方法做一些测试。
猜你喜欢
  • 2017-11-14
  • 2018-09-07
  • 1970-01-01
  • 2013-05-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多