natedaswas natedaswas - 3 months ago 7
AngularJS Question

Can I pass args in the html tag of my custom angular element?

I am using angular 1, I have a directive being returned as an element called "store". So the store element will ng-repeat through each object in an array of json I am using to store all of my products.

<div class="list-group">
<div class="list-group-item" ng-repeat="product in store.products">
<h3>{{product.name}} <em class="pull-right">{{product.price | currency}} Spaces left: {{product.spots}}</em></h3>
</div>
</div>


This works fine on one of my pages where I want to angular repeat through all of the objects. On another page though I want to show the same information but I only want to show certain products. For example, if the key value for feature is set to true.

Is there a way in my tag to pass arguments to specify that I only want to display the first two elements in the array or only display it if it equals a certain key value?

Answer

You can use filters in your ng-repeat directive:

<div class="list-group">
  <div class="list-group-item" ng-repeat="product in store.products | query:feature | limitTo:5">
    <h3>{{product.name}} <em class="pull-right">{{product.price | currency}} Spaces left: {{product.spots}}</em></h3>
  </div>
</div>

You can pass arguments to your custom directives as well. Where you define your directive, you can write:

return {
        restrict: 'EA',
        scope: {
            max: '=',
        },
        ...
        template: '
        <div class="list-group">
          <div class="list-group-item" ng-repeat="product in store.products | query:feature | limitTo:max">
            <h3>{{product.name}} <em class="pull-right">{{product.price | currency}} Spaces left: {{product.spots}}</em></h3>
          </div>
        </div>'
        };

And now you can write:

<store max="5" />

This will iterate over the first 5 elements in the array and only display them if feature is true.

Comments