简体   繁体   English

如何在我的情况下向元素添加点击事件?

[英]How to add click event to element in my case?

I have a directive like the following 我有一个类似以下的指令

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

app.directive('myNav', function () {
    return {
        restrict: 'E',
        templateUrl: "directives/directive-test.html",
        replace: true,
        link: function (scope, element, attrs) {
            //I want to add click event listen to li element
               element.on('mousedown', function(){
                    alert('test') //works on all ul but not individual li
                })
        }
    };
})

directive-test.html 指令-test.html

<ul>
    <li class='nav-btn' ng-click='open()'>
        //contents
    </li>
    <li class='nav-btn' ng-click='open()'>
        //contents
    </li>
    <li class='nav-btn' ng-click='open()'>
        //contents
    </li>
</ul>

I am not sure how to find the li element and assign a click event inside my directive. 我不确定如何找到li元素并在指令内分配click事件。

Can anyone help me about it? 有人可以帮我吗? Thanks. 谢谢。

If you are trying to create something resembling accordion menu check out ui-bootstrap http://angular-ui.github.io/bootstrap/#/accordion . 如果您尝试创建类似于手风琴菜单的内容,请查看ui-bootstrap http://angular-ui.github.io/bootstrap/#/accordion

If not, why not just provide an argument to open() so you know which element was clicked (you can use $index if you need ng-repeat). 如果不是,为什么不只给open()提供一个参数,以便知道单击了哪个元素(如果需要ng-repeat,则可以使用$ index)。

<ul>
    <li class='nav-btn' ng-click='open(0)'>
        //contents
    </li>
    <li class='nav-btn' ng-click='open(1)'>
        //contents
    </li>
    <li class='nav-btn' ng-click='open(2)'>
        //contents
    </li>
</ul>

Now scope.open will know which element was clicked. 现在scope.open将知道单击了哪个元素。 Or with ng-repeat: 或使用ng-repeat:

<ul>
    <li class="nav-btn" ng-repeat="el in navElems" ng-click="open($index)">
        {{el.contents}}
    </li>
</ul>

Where navElems would be an array of objects, for example: 其中navElems将是对象数组,例如:

scope.navElems = [
  { contents: "link1" },
  { contents: "link2" },
  { contents: "link3" }
];

And an example open function: 还有一个示例打开功能:

scope.open = function(index) {
  var el = navElems[index];
  // do stuff with el
};

You should be able to do this 您应该能够做到这一点

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

app.directive('myNav', function () {
    return {
        restrict: 'E',
        templateUrl: 'directives/directive-test.html',
        replace: true,
        link: function (scope, element, attrs) {
            element.find('li').on('mousedown', function(){
                alert('test') 
             });
        }
    };
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM