user8012497
user8012497

Reputation:

How to create links for array elements in AngularJS

I am new to AngularJS. I want to create links for elements in the array. Suggest me some code or descriptives.

app.js

  app.controller('ItemsController', function($scope) {
  $scope.message = 'Items are displayed';
  $scope.items=['Appliances','Books','Cosmetics','Home & Furniture','Mens','women','kids'];

  });

items.html

 <div  ng-controller="ItemsController">

 <p><h1>Type a letter in the input field:</h1></p>

 <p><input type="text" ng-model="test"></p>
 {{message}}
 <ul><h2>
 <li ng-repeat="x in items| filter:test">
 {{ x }}
 </li>
 </h2></ul>

 </div>

Here is the sample output for the above code. Items displayed in the output should be links.

Upvotes: 1

Views: 503

Answers (2)

Manas
Manas

Reputation: 838

If you are using routing then just create an anchor tag in the li.

 <ul>
  <h2>
      <li ng-repeat="x in items| filter:test">
        <a href="#/details/{{x}}">{{x}}</a>
      </li>
 </h2>
</ul>

In the route configuration, just handle the specific route pertaining to the item. Like if you want to display the details for the item.

myApp.config(['$routeProvider',function($routeProvider){
$routeProvider.
when('/details/:item',{
    templateUrl:'partials/details.html',
    controller: 'DetailsController'
}).
otherwise({
    redirectTo : 'yourdefaultpath'
})

Item shall be available in your controller as a routeParam and then you can display your data accordingly. Hope this helps.

Upvotes: 1

cнŝdk
cнŝdk

Reputation: 32145

You can use ui-sref and declare your items as states using ngRoute in your app, this is how would be your code:

<ul>
    <li ng-repeat="x in items| filter:test">
      <a ui-sref="{{x}}"><h2>{{ x }}</h2></a>
    </li>
</ul>

Update your JS to add the states, like this:

app.config(function($stateProvider) {
  $stateProvider.state('Appliances', {
    url: 'Appliances',
    templateUrl: 'app/views/appliances.html'
  });
});

Upvotes: 0

Related Questions