AngularJS,引用指令中的其他DOM项

AngularJS, referencing other DOM items from a Directive

本文关键字:其他 DOM 引用 指令 AngularJS      更新时间:2024-06-12

我有一个导航栏,它使用REST服务提供的数据中的ng-repeat。当我们点击一些菜单项时,我们导航到一个新的视图,当我们点击其他项目时,我们执行其他任务,如显示/隐藏菜单、显示信息弹出窗口等。

我想显示和隐藏菜单下面的popover(请参阅下面的HTML),现在我可以使用一个简单的ng-show,但我想使用一个指令,这样我就可以重用该功能,并动态地确定popover的位置。然而,我不知道如何在我的指令中引用popover。我没有使用jQuery,所以我不能使用$(#id)选择器和

这是我的HTML:

  <div class="container-fluid ">
    <div class="row" data-toggle-nav-popup>
        <div class="col-xs-2 main-nav-cell" data-ng-repeat="nav in mainNavigation.topNavi" data-url="{{ nav.link }}" data-ng-click="menuRedirect(nav.link)" data-ng-class="{'is-active' :  menuOpen && $index === 0 }">
            <div> {{ nav.name }} </div>
            <div class="item-counter" data-ng-show="nav.value > 0"> {{ nav.value }} </div>
        </div>
    </div>
</div>

<!-- PopOver - default is hidden, data-ng-show was an old implementation where we fixed the CSS position and just toggled a $scope.variable -->
<div class="nav-popover" data-ng-show="showPopover">
    <div class="nav-arrow"></div>
    <div class="nav-popover-inner">
        <div class="nav-popover-content">
            <!-- content to go here...  -->
            Content Holder
        </div>
    </div>
</div>  

这是我的指令,你可以看到我设置了一个超时,这样ng-repeat就完成了,然后我给指令DIV的子级分配了一个点击事件,确定点击它的data-url值,如果与我的要求匹配,我从点击的项目返回一些定位属性,然后在算法中使用这些属性(简单求和)来更改popOver的左/上css,然后显示popover-有人知道我如何在指令中引用popover吗,或者我的方法错了吗?

.directive('toggleNavPopup', function ($timeout) {
    'use strict';
    return{
        restrict: 'A',
        priority: 800,
        link: function (scope, element) {
            $timeout(function () {
                var list = angular.element(element);
                list.children().on('click', function (evt) {

                    // determine if we have clicked the 'div' with data-url === 'message'
                    if(evt.target.getAttribute('data-url') === '/message') {
                        console.log('I would like th use the following to positon the PopOver', evt.target.offsetLeft, evt.target.clientWidth);
                        // position the popOver using value, how do I reference it, no jQuery!
                    }
                });
            });
        }
    };
});

你可以像一样重复

data-ng-repeat="nav in mainNavigation.topNavi track by $index" 
    data-url="{{ nav.link }}" data-position={{ $index }}

然后在指令的链接函数中:

  link: function(scope, element, attrs){
      url = attrs.url
      position = attrs.position
      // Do something based on the position
  }