Nano
Nano

Reputation: 1398

Is there a way to show a property of a filtered array in angularjs filter?

I try to show just one specific property of a filtered array. Is there a way to show a property without using a custom method in my controller? I mean directly in the view?

my order.options array:

[
    {value: '0', text: 'random'},
    {value: '1', text: 'names'},
    {value: '2', text: 'ages'}
]

My view:

<span>{{order.options | filter:order.value}}</span><!--  I need help here -->                          
<select ng-model="order.value">
    <option value="{{option.value}}" ng-repeat="option in order.options">{{option.text}}</option>
</select>

If the user orders the list by changing the select, I want to show the text of the selected value somewhere (the value in order.options[INDEX].text)

For example, if the user selects 'random' in the select, random shoud be shown in a span before the select.

I have to use different values and texts in my options, because im ordering the list next to the select by the value (whis is a property of the list item)

Upvotes: 0

Views: 63

Answers (2)

Manish Kr. Shukla
Manish Kr. Shukla

Reputation: 4477

Why not use the selected option directly as the model value ??

<select ng-model="selectedOrder">
    <option ng-value="option" ng-repeat="option in order.options">{{option.text}}</option>
</select>

You can then use selectedOrder.value and selectedOrder.text independently, Directly in view, without any controller method invocation.

Upvotes: 0

sylwester
sylwester

Reputation: 16498

var app = angular.module('app', []);

app.controller('homeCtrl', function($scope) {

  $scope.order = {
    options:

      [{
      value: '0',
      text: 'random'
    }, {
      value: '1',
      text: 'names'
    }, {
      value: '2',
      text: 'ages'
    }]
  };
  
  //set default value for selectedOrder
  $scope.selectedOrder = $scope.order.options[0];


});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app="app">
  <div ng-controller="homeCtrl">


    <span>{{selectedOrder.text}}</span>
    <!--  I need help here -->
    <select ng-model="selectedOrder" ng-options="option.text for option in order.options">

    </select>

  </div>
</div>

Upvotes: 2

Related Questions