1

I have a problem using ng-value and ng-model. If I use ng-value, data does not bind. Is there a way to have both?

<select next-focus tabindex="0" ng-model="plan.tipo_plan" class="input-sm select-control">
    <option ng-repeat="p in planes" ng-value="{{p.id_tipo}}">{{p.tipo_plan}}</option>
</select>
  • Did you see this: https://stackoverflow.com/questions/28717523/whats-the-difference-between-ng-model-and-ng-value – Stradosphere Apr 16 '18 at 21:04
  • Is `plan.tipo_plan` a string and `p.id_tipo` numeric? – Lex Apr 16 '18 at 21:09
  • @Lex yes, that's correct – Martin Zarza Apr 16 '18 at 22:26
  • If you use `ng-options` instead of ` – Lex Apr 16 '18 at 22:31
  • @Lex ng-options works with objects. The data that needs to be displayed is a string, so I can´t show anything – Martin Zarza Apr 16 '18 at 22:32
  • You can use `ng-options` with primitive values. What do you mean "I can't show anything"? – Lex Apr 16 '18 at 22:33
  • @Lex in that 'select' element I show data from a database. Depending on the ID, it shows a different data when the page is loaded. If I use ng-options the data doesn´t display. Am I clear? – Martin Zarza Apr 16 '18 at 22:35
  • Sort of. If your `ng-model` value is not same as what you are putting in the value for your select then it will never work. For example, if you are storing "Plan A" in `plan.tipo_plan`, but the value 1 is in `p.id_tipo` the select will never show the selected value when the view loads. Or have I completely misunderstood? Perhaps you could expand your question to show a small sample. – Lex Apr 16 '18 at 22:39
  • @Lex For example, in 'plan.tipo_plan' I have a string 'Hello'. And one of my options is 'Hello' too, so that option has to be selected. But I want to change that selection. So I choose another option, 'Bye', for example, so the way to save that change in my database is through the option's ID, that's why I want 'ng-value' to be = p.id_tipo – Martin Zarza Apr 16 '18 at 22:45
  • Yeah, the ` – Lex Apr 16 '18 at 22:47
  • @Lex But the data bind works, if I remove 'value' or 'ng-value'. But if I use 'value', it saves the data. But doesn't display the default text – Martin Zarza Apr 16 '18 at 22:48
  • That's because if you have an ` – Lex Apr 16 '18 at 22:55
  • @Lex yes, that's correct. That's exactly what I want to do. Put 'value' attribute without my 'ng-model' be affected – Martin Zarza Apr 17 '18 at 12:09
  • Your `ng-model` should be the ID, not the string. Anywhere you need to display the string you'll have to decode the ID to its corresponding string. The `select` element will handle this automatically for you because it will show the text for the `option` where the value matches the selected ID. If you are just displaying it elsewhere in your app you'll have to decode. – Lex Apr 17 '18 at 13:49
  • @Lex Can you give me an example of what you said? – Martin Zarza Apr 17 '18 at 22:41

0 Answers0