在angularjs中,当ng-options的数组发生变化时,如何刷新`select`?

cc *_*ung 19 javascript angularjs angularjs-scope

有一个select基于任何数组.数组中的元素可能会改变.如何让角度控制器刷新阵列?

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>
  </select>
</form>

从控制台:

> 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

如何select刷新以便所有元素colorArr都是选项?

Jos*_*osh 26

Angular使用观察者,并且只有在摘要循环开始后才会更新UI .

通常你会通过UI中的某个事件添加到数组中,或者通过调用$ http服务来添加数组,并且这些服务会为你启动$ digest().

由于您只是直接添加到数组,因此Angular不知道任何更改,因此不会更新UI.

把你的陈述包裹在内scope.$apply(function(){ //code });.