简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM