user3501278 user3501278 - 1 year ago 145
Javascript Question

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

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'">

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 Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download