【问题标题】:AngularJS, referencing other DOM items from a DirectiveAngularJS,从指令中引用其他 DOM 项
【发布时间】:2015-02-27 10:20:41
【问题描述】:

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

我想显示和隐藏菜单下方的弹出框(请参阅下面的 HTML),现在我可以使用简单的 ng-show 但我想使用指令以便我可以重用该功能并动态确定位置对于弹出框。但是我不知道如何在我的指令中引用弹出框。我没有使用 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 然后显示弹出框 - 有谁知道我怎么能在我的指令中引用弹出框还是我的方法错误?

.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!
                    }

                });

            });
        }
    };
});

【问题讨论】:

  • 将 ng-repeat 的 $index 作为属性传递给您的自定义指令。例如&lt;my-custom-directive data-position={{$index}}&gt; &lt;/my-custom-directive&gt; 然后在指令的链接函数中从 attrs 读取值。 link: function(scope, element, attrs)

标签: javascript angularjs


【解决方案1】:

你可以重复喜欢

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

  }

【讨论】:

  • 我想我把你弄糊涂了……或者我弄糊涂了。我想对
猜你喜欢
  • 2014-04-02
  • 2015-06-24
  • 2014-05-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多