简体   繁体   中英

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

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

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 .

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).

<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. Or with 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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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