JDH
JDH

Reputation: 159

Angular JS - dynamically add href links to icons using ng-repeat

I'm trying to use angular to create a table of different videos that are organized by topic, date, presenter and also are tagged.

I've used ng-repeat to repeat over my array of objects to produce a table.

However, how can I dynamically change the href link for the play button?

In the jsfiddle below, I've added a static row of what each should look like. the first column has a fontawesome icon that is linked to a video. How can I edit the function so that the href link is updated in the ng-repeat?

http://jsfiddle.net/jheimpel/f139z9zx/3/

function playerCtrl($scope) {

  $scope.topics = [
   {
    "play": "play",
    "topic": "topic 1",
    "date": "date 1",
    "presenter": "presenter 1",
    "tags": "tag"
  },
    {
    "play": "play",
    "topic": "topic 2",
    "date": "date 2",
    "presenter": "presenter 2",
    "tags": "tag"
  },     

  ];

}

Upvotes: 8

Views: 22332

Answers (3)

doldt
doldt

Reputation: 4506

You can put an <a> tag with dynamic href inside of the ng-repeat, it works just as you'd expect - though using ng-href is better, so your links dont break before the data bindings are ready.

I've updated your fiddle: here

So that the ng-repeat starts with:

    <tr ng-repeat="topic in topics">
        <td><a ng-href="#/{{topic.url}}"><i class="fa fa-play"></i></a></td>

(and I added that extra url field to your test data)

Upvotes: 15

Malek Hijazi
Malek Hijazi

Reputation: 4162

Add a link attribute to your array of objects like so:

$scope.topics = [
   {
"play": "play",
"topic": "topic 1",
"date": "date 1",
"presenter": "presenter 1",
"tags": "tag",
"link" : "url"
},
{
"play": "play",
"topic": "topic 2",
"date": "date 2",
"presenter": "presenter 2",
"tags": "tag"
"link" : "url"
},     

];

ng-repeat="topic in topics"

and in the href

<a href="{{topic.link}}">

Upvotes: 0

Rasalom
Rasalom

Reputation: 3111

If I understood you correctly, you just need to use ng-href:

<td><a ng-href="{{linkVar}}"><i class="fa fa-play"></i></a></td>

and ng-click on row:

<tr ng-repeat="topic in topics" ng-click="changeLink($index)">

http://jsfiddle.net/n8s7ns7h/

Upvotes: 1

Related Questions