Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
364 views
in Technique[技术] by (71.8m points)

javascript - in angularjs, how do you get a `select` to refresh when the array for ng-options changes?

have an select based on any array. the elements in the array may change. how do I get the angular controller to refresh the array?

module.js

var langMod = angular.module('langMod', []);
langMod.controller( .controller( 'colorCntl', function($scope) {
  $scope.color = 'wt';
  $scope.colorArr = [
    { id: 'br', name: 'brown' },
    { id: 'wt', name: 'white' }
  ];
});

index.html

<form ng-controller='wordCntl' >
  <select ng-model="color" ng-options="c.id as c.name for c in colorArr">
     <option value=''>-- chose color --</option>
  &lt/select>
</form>

from the console:

> scope = angular.element(document.querySelector('select')).scope();
> scope.colorArr.push( { id:'bk', name:'black' } );
  3
note! the select dropdown still only has brown and white, not black

how do I get the select to refresh so that all elements in colorArr are options?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Angular uses watchers, and will only update the UI if a digest loop has been kicked off.

Normally you would be adding to the array via some event in the UI, or by calling the $http service, and those take care of kicking off a $digest() for you.

Since you are just adding directly to the array, Angular does not know anything has changed, and therefore does not update the UI.

Wrap your statement inside of a scope.$apply(function(){ //code }); instead.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...