Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to trigger ng-change on a select that contains a ng-repeat

I have two select box, the second select box updates itself when the first select box changes.

<label>Region</label>
<select ng-model="region" 
        ng-change="clear(1)" 
        ng-options="l.region for l in locations"
></select>
<br />
<label>Country</label>
<select ng-model='country'
        ng-change="clear(2)" 
        ng-options="c.country for c in region.countries"
></select>

My locations is a json object that looks like this :

[
  {region: "Europe", countries: [{country: "France"}, {country: "UK"}/*, ...*/]},
  {region: "Africa", countries: [{country: "Cameroon"}, {country: "Algeria"}]}
  /*, ...*/
]

This all works fine this way.

It begins to be complicated when I want to set the value of the first select box to Europe, and I want to trigger the ng-change event on the second select box.

Any idea on how to do this?

like image 343
Ant Avatar asked Apr 21 '13 15:04

Ant


People also ask

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 can I use instead of NG-repeat?

You can consider using transclusion inside a custom directive, to achieve the behavior you are looking for without using ng-repeat.

What is difference between ng-repeat and Ng-options?

ng-options is the directive which is designed specifically to populate the items of a dropdown list. One major advantage using ng-options for the dropdown is, it allows us to pass the selected value to be an object. Whereas, using ng-repeat the selected value can only be string.


1 Answers

You want to trigger the ng-change event on the second select box, which is equivalent to the scenario when the model region is changed. So you can use a watcher to achieve it.

$scope.$watch('region', function (newValue, oldValue) {
    console.log(newValue, oldValue);
})
like image 110
zs2020 Avatar answered Sep 21 '22 17:09

zs2020