1

I have an array of attributes of users

$scope.userAttributes = [{
    id: 112,
    order: "first"
}, {
    id: 232,
    order: "second"
}, {
    id: 353,
    order: "third"
}, {
    id: 485,
    order: "fourth"
}];

and I want to use order attribute as a dropdown options with this code piece

<select ng-model= "users.number " class="form-control" ng-options="t.order for t in userAttributes"> 
   <option ng-selected="{{t.id== users.number}}">{{t.order}}</option> 
</select>

I also have array of users

$scope.users = [{
    number: 112,
    age: "eigth",
    name: "alice"
}, {
    number: 232,
    age: "ten",
    name: "jack"
}, {
    number: 353,
    age: "twelve",
    name: "kevin"
}];

I will have a form through that I will change the order of users using a dropdown list but I want to see the order attribute to be pre-selected according to the number of users. For example, when I choose Kevin, at the dropdown list "third" should be there as selected(as if I did it with ng-selected) and when I change "third" to "first", the number of kevin should be changed as 232.

georgeawg
  • 48,608
  • 13
  • 72
  • 95

1 Answers1

0

angular.module('app', []).controller('ctrl', function($scope) {
  $scope.userAttributes = [
    { id: 112, order: "first" }, 
    { id: 232, order: "second" },
    { id: 353, order: "third" }, 
    { id: 485, order: "fourth" }
  ];
  $scope.orderChanged = () => $scope.user.number = $scope.order.id;
  
  $scope.users = [
    { number: 112, age: "eigth", name: "alice" },
    { number: 232, age: "ten", name: "jack" },
    { number: 353, age: "twelve", name: "kevin" }
  ];
  $scope.user = $scope.users[0];
  $scope.userChanged = () => 
    $scope.order = $scope.userAttributes.find(x => x.id == $scope.user.number);
  $scope.userChanged();
})
.active{
  background-color:orange;
}
<script src="//code.angularjs.org/snapshot/angular.min.js"></script>

<div ng-app='app' ng-controller='ctrl'>
  <select ng-model= "order" ng-options="t.order for t in userAttributes" ng-change='orderChanged()'>     
  </select>
  <select ng-model= "user" ng-options="u.number for u in users" ng-change='userChanged()'>     
  </select> 
  <br>
  <ul ng-repeat='user1 in users'>
    <li ng-class='{active: user1 === user}'>{{user1}}</li>
  </ul>  
</div>
Slava Utesinov
  • 13,410
  • 2
  • 19
  • 26