Search code examples
sqlangularjssql-serverng-optionsangularjs-ng-options

Default value pre-selected in select box with ng-options


I am trying to get default value selected (from database) in my select box using ng-options.

My view

<select class="form-control samlength modalinput" 
        ng-options="p.procid as p.procname for p in processes track by p.procid" 
        ng-model="p.procid">
  <option value="">-- choose an option --</option>
</select>

where p.procid is a value received from the database.

My data

procid  procname    time
    1   MyProcess   2018-05-30 13:34:54.097 3003162
    3   Testing     2018-05-31 18:31:32.467 3003162

If selected procid is 3, how can I get it to be selected by default?

FYI - I have tried multiple answers given in other threads. I have also tried ng-init but nothing helped.


Solution

  • You can keep your HTML as:

    <select class="form-control samlength modalinput" 
            ng-options="p.procid as p.procname for p in processes track by p.procid" 
            ng-model="selectedProcess">
      <option value="">-- choose an option --</option>
    </select>
    

    Now if we have a requirement to select a particular object in the array. We can do that by iterating through the array and comparing value at the given key:

    function functiontofindIndexByKeyValue(arraytosearch, key, valuetosearch) {
        for (var i = 0; i < arraytosearch.length; i++) {
          if (arraytosearch[i][key] == valuetosearch) {
            return i;
          }
        }
        return null;
      }
    

    Call this function as:

    var index = functiontofindIndexByKeyValue($scope.processes, "procid", procid);
    $scope.selectedProcess = $scope.processes[index];
    alert(index);
    

    Hope it works!