0

What is the efficient way to preselect an option based on some filter? My elements are e.g.:

[ {"name":"CSS1-1","id":"ce5e6a4299c68f0407b277fed38b4c657f20cfe8"},
   . . .
  {"name":"CSS1-2","id":"00f75732b5760a5bb36842e1db950d243bec87db" ]

and I want the element with id= 00f75732b5760a5bb36842e1db950d243bec87db preselected. In html

 <select ng-model="currentCss"
   ng-options="item.name for item in csss" />
 </select>

Data filled in here:

$scope.getCsss = function () {
    $http.get('/csss')
        .success(function (data, status, headers, config) {
            $scope.csss = data;                 
                $scope.currentCss =  ? ? ? 
                // I can start looping and comparing, 
                //but there must be a better way               
        }). . .
Assen Kolov
  • 4,143
  • 2
  • 22
  • 32
  • Related http://stackoverflow.com/q/17329495/1331430 – Fabrício Matté Nov 19 '13 at 20:46
  • It is a bit similar but not very much. OP in the other issue didn't know about ng-model. The answer suggests using ng-model and setting a value equal to one of the options, all strings. I want to do the same, but my options are not strings. With strings "a"=="a" is true, with objects ["a"] == ["a"] is not. – Assen Kolov Nov 19 '13 at 20:56

1 Answers1

1

You want a track by expression in your ng-options

<select ng-model="currentCss"
   ng-options="item.name for item in csss track by item.id" />
 </select>

Then you can set an object with that id to select the correct ng-model value:

$scope.getCsss = function () {
    $http.get('/csss')
        .success(function (data, status, headers, config) {
            $scope.csss = data;                 
            $scope.currentCss =  { id: data.currentId }; // not sure the format here            
        })

This is is an excerpt from the docs:

trackexpr: Used when working with an array of objects. The result of this expression will be used to identify the objects in the array. The trackexpr will most likely refer to the value variable (e.g. value.propertyName).

Davin Tryon
  • 66,517
  • 15
  • 143
  • 132
  • Thhat's what I needed, thanks! Another useful sentence from the docs about the case track by item.id: Two objects are considered equivalent as long as their id property is same. – Assen Kolov Nov 19 '13 at 21:08