简体   繁体   中英

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.

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.

the problem is that ngInit is a directive and the angular life is basically

  1. compile
  2. controller
  3. pre-link
  4. post-link

and therefor you cant "override" something in the controller upon a directive (unless its specially uses compile).

it would seem more logical to put watchers on whatever need change and the the watchers callback change 'mycolor'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM