Sajad Abedi Sajad Abedi - 5 months ago 28
Javascript Question

bind click event to the element in ng-repeat angular

I have menu and use

ng-repeat
for loop to the my category and in this loop i have a link tag and I want to when clicked on this link do something in js file.
But I can't access to the tag a in javascript and add click event to this element.

Here is my ng-repeat code:

<li class="has-children" ng-repeat="category in categories |filter:{ level: 1 } : true" ng-if="$index < 5">
<a class="parent-link">{{category.categoryName}}</a>
<ul class="is-hidden">
<li class="go-back"><a>{{category.categoryName}}</a></li>
<li ng-repeat="submenu in categories |filter:{ parentID: category.categoryID } : true"><a>{{submenu.categoryName}}</a></li>
</ul>
</li>


Here is my js file (this code doesn't fire):

$(".parent-link").on("click", function(e) {
console.log("clicked");
e.prenvetDefault()
});

Answer

Use ng-click. It can be used as attribute of element. Example usage:

HTML:

<div ng-click="changeWord()">
   {{word}}
</div>

Controller:

$scope.changeWord = function () {
    $scope.word = 'I am changed';
}

See http://jsfiddle.net/ax6k3z1e/