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

have an select based on any array.the elements in the array may change.how do I get the angular con

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?

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?

Share Improve this question asked Nov 9, 2013 at 4:36 cc youngcc young 20.2k32 gold badges94 silver badges150 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 26

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.

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1738376549a4045786.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信