加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

angularjs – ng-click在使用嵌套指令时首次使用$compile后停止

发布时间:2020-12-17 08:46:05 所属栏目:安全 来源:网络整理
导读:我有一个使用辅助/包装指令的Angular模态指令.这样我总是可以使用相同的包装器,只需在不同的模态内容所需的位置加载不同的模板. 问题:此代码段有效,但仅适用于模态的第一个生命周期.所以我可以发射模态,关闭模态并再次发射它.但是一旦模态打开,第二次ng-cli
我有一个使用辅助/包装指令的Angular模态指令.这样我总是可以使用相同的包装器,只需在不同的模态内容所需的位置加载不同的模板.

问题:此代码段有效,但仅适用于模态的第一个生命周期.所以我可以发射模态,关闭模态并再次发射它.但是一旦模态打开,第二次ng-click指令都不起作用.任何提示都只是超级.

用法

<button my-modal="views/login.html">Launch Login-specific Modal</button>

指令模块(app.js)

angular.module('myModal',[])

.directive('modalWrapper',function(){
  return {
    replace: true,templateUrl: 'views/modal.html',controller: function($scope,$element){
      $scope.close = function(){
        $element.remove();
      };
      // NOTE: I use this array to showcase that ng-repeat still works the second time although ng-click stops functioning properly.
      $scope.others = ["One","Two","Three"];
    }
  }
})

.directive('myModal',function( $compile){

      function link(scope,element,attr){

      scope.partial = attr.myModal; // NOTE: Loads sub template via ng-include

      var ngModal = $compile('<div modal-wrapper></div>')(scope);

      element.on('click',function(){
        angular.element('body').append(ngModal);
      });

      scope.yo = function(){
        alert("Yo from inside template.");
      };

    }

    return {
      link: link,scope: {}
    }
});

模板

modal.html

<div class="my-modal">
    <p>Modal Wrapper</p>
    <div ng-include="partial"></div>
  <button ng-click="close()">Close</button>
  <p>This just proves that other directives still work (ng-repeat),but ng-click does not.</p>
  <div ng-repeat="stuff in others">
    <p>{{stuff}}</p>
  </div>
</div>

的login.html

<h1>Well hey there,I'm the login template.</h1>
<button ng-click="yo()">Say Yo</button>
我认为问题是你正在破坏编译ng-click的范围.

调用scope.close()时,会发生$element.remove().这两者都从DOM中删除元素,并破坏它所附加的范围.这将导致您的ng-click被取消注册.

不幸的是(截至上次我检查过),element.detach()也会破坏范围,所以最好的办法是将元素编译并附加到body只有一次.在此之后,您可以使用element.show()和element.hide()来显示和隐藏模态.或者,您可以在每次要显示模式时重新编译模态.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读