Reputation: 14250
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.
Upvotes: 0
Views: 91
Reputation: 2935
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
};
Upvotes: 2
Reputation: 2667
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')
});
}
};
})
Upvotes: 1