m.e.conroy
m.e.conroy

Reputation: 3538

Stop a clicked link from loading and let the surrounding element with Angularjs ng-click handle the action

I have a table of courses and initially I made each row clickable, which would then switch templates in ng-view and show the course's details. My problem is that I need a search appliance's crawler to be able to follow links to the course's details in order to make them available for searching. I have done that by adding a link to the course's title in one of the table's cells but now I have the problem of having a student actually clicking both the title link and table row. Where/how do I cancel one of those actions, preferably the title link (I'd like to stop the page from loading twice)? Here is an excerpt of my template:

<thead>
    <tr>
        <th>Title</th>
        <th>Instructor</th>
        <th>Days</th>
        <th>Time</th>
    </tr>
</thead>
<tbody>
    <tr ng-repeat="course in catalog.courses | filter:isSubject" ng-click="loadCourse(course.regnum,course.id)">
        <td><a href="/schedule/#!/course/{{course.regnum}}/{{course.id}}">{{course.abbr}} {{course.num}} {{course.section}}: {{course.title}}</a></td>
        <td>{{course.instructor}}</td>
        <td>{{course.meeting_pattern}}</td>
        <td>{{course.start_time}} - {{course.end_time}}</td>
    </tr>
</tbody>

When someone clicks on the link in the first cell both the link and the row's function in ng-click are called and the page loads twice. I want to stop the link href action from happening and only let the ng-click action handle the request.

I know I have to stop the propagation some how but if I stop it on the <a> element will that affect the function on the <tr> element?

Upvotes: 1

Views: 1059

Answers (2)

m.e.conroy
m.e.conroy

Reputation: 3538

I found part of the solution here: How can I make an AngularJS directive to stopPropagation?

and used the preventDefault() instead of the stopPropagation() function.

<a href="/schedule/#!/course/{{course.regnum}}/{{course.id}}" stop-event="click">

then created a directive:

app.directive('stopEvent',function(){
    return {
        restrict: 'A',
        link : function(scope,el,attr){
            el.bind(attr.stopEvent,function(evt){
                evt.preventDefault();
            });
        }
    }
});

Upvotes: 0

TheSharpieOne
TheSharpieOne

Reputation: 25726

Add ng-click="$event.preventDefault();" to the link that you want to stop.

<tr ng-repeat="course in catalog.courses | filter:isSubject" ng-click="loadCourse(course.regnum,course.id)">
    <td><a href="/schedule/#!/course/{{course.regnum}}/{{course.id}}" ng-click="$event.preventDefault();">{{course.abbr}} {{course.num}} {{course.section}}: {{course.title}}</a></td>
    <td>{{course.instructor}}</td>
    <td>{{course.meeting_pattern}}</td>
    <td>{{course.start_time}} - {{course.end_time}}</td>
</tr>

Also, you were missing your closing </a> on that link.

Upvotes: 1

Related Questions