有一个 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
中的所有元素都是选项?
1 回答
Angular使用watchers,并且只有在digest loop被启动后才会更新UI .
通常你会通过UI中的某个事件添加到数组中,或者通过调用$http service来添加数组,然后为你开始$digest() .
由于您只是直接添加到数组,因此Angular不知道任何更改,因此不会更新UI .
将您的陈述包裹在
scope.$apply(function(){ //code });
中 .