【问题标题】:click event in angular on transcluded children嵌入儿童的角度单击事件
【发布时间】:2015-02-02 22:59:31
【问题描述】:

我正在尝试在指令中的嵌入子元素上触发点击事件。它不工作。由于某种原因,我似乎无法访问父范围。

app.controller('myController', [
    '$scope',
    '$log',
    '$q',
    function ($scope, $log) {
      $scope.delete = function(){
        $log.log('delete clicked');
      };

      $scope.whatever = function(){
        $log.log('whatever clicked');
      };
    }
  ]);


  <!-- directive markup -->
  <span class="ui-menu-action">
    <span class="trigger" ng-click="showMenu = !showMenu">
       <i class="sl-icon sl-icon-box-arrow-down"></i>
    </span>
    <div class="actions" ng-show="showMenu" ng-mouseenter="cancelHide()"></div>
  </span>


  <!-- calling the directive -->
    <ui-menu-action>
      <ul>
        <li><a href ng-click="delete()">Delete</a></li>
        <li><a href ng-click="whatever()">Whatever</a></li>
      </ul>
    </ui-menu-action>


  app.directive('UiMenuAction', [
    '$http',
    '$tooltip',
    '$log',
    '$rootScope',
    '$timeout', function($http, $tooltip, $log, $rootScope, $timeout){
      return {
        restrict: 'E',
        replace: true,
        //scope: {},
        transclude: true,
        templateUrl: './scripts/modules/ui/templates/ui.menu.action.html',
        link: function(scope, element, attrs, ctrl, transclude){
          var to;
          scope.showMenu = false;
          scope.hideOnPageClick = attrs.hideonpageclick;

          $rootScope.$on('pageClick', function(e, $event){
            var isMenuClick = !!$($event.target).parents('.ui-menu-action').length;

            if ( scope.hideOnPageClick && !isMenuClick ) {
              scope.showMenu = false;
            }
          });

          scope.hideMenu = function(){
            if ( scope.hideOnPageClick ) return;

            to = $timeout(function(){
              scope.showMenu = false;
            }, 400);
          };

          scope.cancelHide = function(){
            if ( scope.hideOnPageClick ) return;

            if ( to ) {
              $timeout.cancel(to);
            }
          };

          transclude(scope.$parent, function(clone, scope) {
            element.find('.actions').append(clone);
          });
        }
      };
    }]);

【问题讨论】:

    标签: angularjs angularjs-ng-transclude


    【解决方案1】:

    你为什么不直接删除

          transclude(scope.$parent, function(clone, scope) {
            element.find('.actions').append(clone);
          });
    

    并将 ng-transclude 添加到您的标记中

    <div class="actions" ng-transclude ng-show="showMenu" ng-mouseenter="cancelHide()"></div>
    

    【讨论】:

    • 我做到了,虽然更好,但我仍然有同样的问题。嵌入标记中的事件不会冒泡到调用指令的父范围。
    • 你是什么意思“嵌入标记中的事件不会冒泡到调用指令的父范围”AFAIK,这只发生在你有一个独立的范围并且在你的指令中,你'已经注释掉了范围。
    猜你喜欢
    • 2018-12-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多