1

I have a single controller with multiple views which are navigated with ui-router.

One of these views has a select input. The options for this select are loaded from array with simple objects. My model value is integer, so I want to bind to a property inside the object (as we know, Angular treats option values as strings and does strict comparison, so I need a directive to convert to/from integer, and this part seems to work fine in my code). It works fine, as long as I stay on the view with select. But the problems start when I switch between views. Although the model preserves its value, the select gets reset and shows wrong value.

How to make select survive ui-router's navigation?

Here is a Plunker to show the issue: http://embed.plnkr.co/dVQTtHpu7GYqOyN2yyVH/preview

4
  • @JustMartin Every time controller get initialized when you navigate to page back. Which mean you should keep selected option value in service. Commented Aug 18, 2015 at 13:36
  • @Mohan Singh: My case is a bit non-standard - I don't specify controller for the state. My ng-controller is outside - the same controller instance for both views - and even its constructor is called only once and not while navigating. If controller would get reinitialized, then the model value also would be lost, but it is not - it stays and is displayed correctly when I switch between views. Only select value is being displayed wrong. Commented Aug 18, 2015 at 13:40
  • Why do not you ng-options ? Commented Aug 18, 2015 at 13:49
  • @Mohan Singh Because as much as I tried, it was loading entire selected object into my model, and not just the id property. But it seems, I was not clever enough - see the accepted answer. Commented Aug 18, 2015 at 13:58

1 Answer 1

4
<select ng-model="cntrlr.model.lang_id" ng-options="idx*1 as var.name for (idx, var) in cntrlr.languages">
        </select>

http://embed.plnkr.co/lBmsDLUXJjfIf2Tc08UI/preview

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks, this works. What a smart use of ng-options, I would never think of such a trick.
Actually I found it myself in some question in stack-overflow one day but could not find the original answer it was from. Sorry so credits is not 100% from me
There is just one drawback I found - it works fine as long as "id" fields are in the same sequence as idx, but if they are not, then still I cannot bind directly to model.lang_id but have to use some intermediate model value which then selects the right record by index from languages.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.