本文介绍了在 angularjs 中,当 ng-options 的数组发生变化时,你如何获得一个 `select` 来刷新?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有一个基于任何数组的 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=''>--选择颜色--</option></选择>

来自控制台:

>scope = angular.element(document.querySelector('select')).scope();>scope.colorArr.push( { id:'bk', name:'black' } );3笔记!选择下拉菜单仍然只有棕色和白色,没有黑色

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

解决方案

Angular 使用 观察者,并且只有在 摘要循环已启动.

通常您会通过 UI 中的某个事件或通过调用 $http 服务,那些负责启动 $digest() 给你.

由于您只是直接向数组中添加内容,Angular 并不知道有任何更改,因此不会更新 UI.

将您的语句包装在 scope.$apply(function(){//code }); 中.

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>
  </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?

解决方案

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.

这篇关于在 angularjs 中,当 ng-options 的数组发生变化时,你如何获得一个 `select` 来刷新?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-03 09:40