0

How can I set the selected value of a dropdown when I edit an item ?

<div class="form-group">
    <label for="category" class="col-sm-2 control-label">Category</label>
    <div class="col-sm-10">
        <select ng-model="quiz.category" ng-options="category as category.name for category in categories" required>
            <option></option>
        </select>
    </div>
</div>

And when I click on edit

$scope.editQuiz = function(quiz)
    {   
        $scope.quiz = {};
        $scope.quiz.name = quiz.name // this works fine
        $scope.quiz.category = quiz.category[0]; // ?????
        console.log($scope.quiz.category);
        //$scope.quiz = quiz;  

    }

Method to get categories:

$scope.getCategories = function() {
    $http.get('http://localhost/myappi/API/index.php/Api/categories').
        success(function(data) {

            $scope.categories = data;   
        })
        .error(function(err) {
        console.log('error',err);
    })
    };
Cristian
  • 275
  • 4
  • 17

3 Answers3

0

Changing the select's ngModel is definitely the way to go. You can check out this solution, since I believe it deals with the same problem.

$scope.options = [{ name: "a", id: 1 }, { name: "b", id: 2 }]; $scope.selectedOption = $scope.options[1];

<select data-ng-options="o.name for o in options" data-ng-model="selectedOption"></select>

Can you send us your data structure sample?

Community
  • 1
  • 1
Nemanja Milosavljevic
  • 1,251
  • 18
  • 33
0

Ok if you really want to keep quiz.category as an array.
At first when you get the quiz assign quiz.category to an new object. e.g:

$scope.tmp = { category: quiz.category[0] };

We have to do that since quiz.category is an array but the value of the ng-options is an object.

now we can bind that var to the options like this:

<select ng-model="tmp.category" ng-options="category as category.name for category in categories" required>
        <option></option>
</select>

and finally in your function you replace the old value with the new:

$scope.quiz.category[0] = tmp.category;

Hope it makes sense

koox00
  • 2,691
  • 2
  • 15
  • 25
0

Use "track by" inside the ng-options

category as category.name for category in categories track by category.id

working example

puemos
  • 1,109
  • 9
  • 12