Search code examples
angularjsangularjs-select

AngularJS Select item for the element to edit


I want to know how to put an element selected in select that is alimented with data from JSON coming from REST API : here is my code :

<select ng-model="TransferCtrl.transfert.driver" ng-selected="TransferCtrl.transfert.driver.id == d.id">
 <option ng-repeat="d in TransferCtrl.drivers" value="{{ d }}">{{ d.firstName }}</option>
</select>

and here is my logic in the controller :

StaffService.getAllDrivers().then(
        function(response){
          vm.drivers = response.data;
        },
        function(error){
          console.log('error : ' + error)
        }
);

and the selected driver is showed in a modal to be edited,so I want that the driver be selected in the list on the edit time,how proceed please ?


Solution

  • You simply need to set your selected item to a variable $scope.selectedItem when your select has changed.

    PS. Don't use ng-repeat on select but use ng-options.

    <select ng-options='d.firstName for d in TransferCtrl.drivers' ng-change='selectedTemplate(d)'></select>
    

    controller:

    $scope.selectedTemplate = function(item){
      $scope.selectedItem = item;
    }
    

    modal:

    <div>
      <h1>selectedItem.firstName</h1>
    </div>