user3501278 user3501278 - 4 months ago 21
Javascript Question

ng-init overriding ng-model in the select options (plunker added)

https://plnkr.co/edit/RgGzgGkBPaxvKHNE688K?p=preview

In the above example,I am hard coding the select options and initializing to the color 'red' via ng-init attribute. I wanted to show the color 'red' default on page load.

<select ng-model="mycolor" ng-init="mycolor = 'red'">
<option>red</option>
<option>green</option>
</select>


In the controller, I updated 'mycolor' to 'green' but the selectbox still shows 'red' because of ng-init attribute. ( I am doing this because mycolor will be retrieved from the backend)

app.controller('MainCtrl', function($scope) {
$scope.mycolor = 'green';
});


How to tackle this? In short what I wanted to achieve is, I want to show red color default value in the select box on page load and if any change happens to mycolor in the backend it should be overridden to the new color. In my case it is green.

Answer

You can do

<select ng-model="mycolor" ng-init="mycolor = mycolor || 'red'">

So the mycolor model will be set to itself if there is a value, otherwise default to 'red'.

See plunker. I have a timeout of 5 seconds to change the color to blue to simulate a backend change as an example.