Ng-repeat selected option from secondary object/array values matching?


#1

I’m looking to give the selected="selected" value to an <option> in my ng-repeat list based on a secondary variable that I’m creating, which stores the selected option value that was passed previously.

So I have a service that returns var things =[] to populate a select list. I submit the values which then goes to another controller to show detail on your current selection. And when going back to the page (with the select lists) I want to apply the previously submitted values to now be the current selectd item.

I pass the value of the selected list item to the same service and store in var currentparams =[] where my data in currentparams may hold the values from option1 (below) or option2 (not shown but similar treatment) as {"option1":"mythingvalue", "option2":"myotherthingvaluenotshown"}

<select name="option1" data-ng-model="param_thing">
<option data-ng-repeat="thing in things" value="{{thing.id}}" data-ng-bind-html="thing.name"></option>
</select>

So how do I then iterate within that list to compare if the value of {{thing.id}} matches option1:mythingvalue?


#2

I’m sort of half-stuck now as I can set the value on a static list, but not one using ng-repeat.

On a static list, I can just set the $scope.model_name to equal the value of desired selected option in my controller.

View:

<select name="test" data-ng-model="param_test">
        <option value="">-- test select --</option>
        <option value="1">test1</option>
        <option value="2">test2</option>
        <option value="3">test3</option>
      </select>

Ctrl:

$scope.param_test = "2";

Which does indeed set the test2 as the selected option. Great.

HOWEVER on my dynamic list, if I manually set $scope.model_name = "value i want selected" in the controller; it builds the list and doesn’t apply the selected value. (I would assume because ng-repeat is fired after the $scope.model_name = "value", meaning that it wasn’t applied or didn’t exist at the time and is thus ignored one way or the other)

So I’m not quite sure what to do.


#3

How about not setting the model until after the service has returned the values?

MyService.getParams().then(
    function(results) {
        $scope.items = results;
    }
)

#4

.then is not an available function

The only place I’ve ever been able to use .success, .error or .then is on an $http.get()


#5

if .then is not an available function, then your service is not returning a promise. If you don’t need a promise, then just do this:

$scope.items = MyService.getParams();

#6

Did you ever figure this out?