Dark star
Dark star

Reputation: 5832

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

Upvotes: 1

Views: 1851

Answers (3)

Himanshu Jain
Himanshu Jain

Reputation: 538

ng-Repeat have the tendency to bind your iterating object as well. Below is the example for the same.

<div ng-repeat='ele in elements'>
<p ng-click='ShowAlert(ele)'>{{ele.name}}</p>
</div>

Specify below mentioned code in your linked controller.

$scope.ShowAlert=function(element){
alert(element.Name);
}

Upvotes: 0

Łukasz
Łukasz

Reputation: 2171

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/

Upvotes: 2

Vivek Pratap Singh
Vivek Pratap Singh

Reputation: 9974

Possible reason could be that you Javascript is getting executed before the DOM is ready. You should use ng-click as It's good to build through Angular way when you are using AngularJS in you application.

Upvotes: 1

Related Questions