在我的情况下如何将click事件添加到元素?

时间:2014-05-16 19:40:28

标签: javascript angularjs angularjs-directive

我有如下指令

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
                })
        }
    };
})

指令-的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>

我不确定如何找到li元素并在我的指令中指定一个click事件。

任何人都可以帮我吗?感谢。

2 个答案:

答案 0 :(得分:2)

如果您正在尝试创建类似手风琴菜单的内容,请查看ui-bootstrap http://angular-ui.github.io/bootstrap/#/accordion

如果没有,为什么不直接为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>

现在,scope.open将知道点击了哪个元素。或者使用ng-repeat:

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

其中navElems是一个对象数组,例如:

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

示例开放功能:

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

答案 1 :(得分:1)

你应该能够做到这一点

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') 
             });
        }
    };
})