Search code examples
javascriptangularjsangular-directiveng-optionsangularjs-select

How to translate ids to objects in ng-option angular?


I have array of ids and I need to use this array as source of my ng-option directive inside of select. I certainly could find objects with corresponding id in my collection and create an array of objects to use it instead of array of ids but I wonder is there a way of doing it dynamicaly somehow? Like setting a function as source of ng-option?


Solution

  • You can do it with the help of filtering by id inside ngOptions directive expression:

    angular.module('demo', []).controller('MainCtrl', function($scope) {
        $scope.ids = [1, 4];
        $scope.objects = [
            {id: 1, name: 'One'},
            {id: 2, name: 'Two'},
            {id: 4, name: 'Four'}
        ];
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.6/angular.min.js"></script>
    <div ng-app="demo" ng-controller="MainCtrl">
    
        <pre>{{objects}}</pre>
        <pre>{{ids}}</pre>
    
        <select ng-model="model" 
                ng-options="id as (objects | filter:{id: id})[0].name for id in ids">
        </select>
    
        {{model}}
    
    </div>