Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 817
cc young Avatar asked Nov 09 '13 04:11

cc young


People also ask

How do ng-options work?

Definition and Usage. The ng-options directive fills a <select> element with <options>. The ng-options directive uses an array to fill the dropdown list. In many cases it would be easier to use the ng-repeat directive, but you have more flexibility when using the ng-options directive.

How do I get the index of an element in NG-repeat?

Note: The $index variable is used to get the Index of the Row created by ng-repeat directive. Each row of the HTML Table consists of a Button which has been assigned ng-click directive. The $index variable is passed as parameter to the GetRowIndex function.

What is Ng select in AngularJS?

AngularJS ng-selected Directive The ng-selected directive sets the selected attribute of an <option> element in a <select> list. The option will be selected if the expression inside the ng-selected attribute returns true. The ng-selected directive is necessary to be able to shift the value between true and false .

What does ng-repeat do?

Definition and Usage The ng-repeat directive repeats a set of HTML, a given number of times. The set of HTML will be repeated once per item in a collection. The collection must be an array or an object. Note: Each instance of the repetition is given its own scope, which consist of the current item.


1 Answers

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.

like image 150
Josh Avatar answered Oct 12 '22 02:10

Josh