简体   繁体   中英

How can I detect when a USER changes the value in a select drop down using AngularJS?

I have the following:

<select data-ng-model="selectedTestAccount" data-ng-options="item.Id as item.Name for item in testAccounts">
   <option value="">Select Account</option>
</select>

It was suggested to me that I could watch for the value of this select to change with the following:

$scope.$watch('testAccounts', function(){
  /* get updated values and update other select "model" on success*/
  alert("hello");
});

But this does not seem to work. For one thing it gives an alert as soon as the select appears on the screen and before the user has selected anything. Also am I correct in saying that I should be watching for a change in selectedTestAccount? Finally one more question. How can I show the value of selectedTestAccount in an alert box?

As said, you can get it as the first argument, no need to get it from scope. Use

$scope.$watch('selectedTestAccount', function(newValue){
  alert(newValue);
});

Beware that you always get a undefined as the first change for a $watch .

What about putting an "ng-change" to your select?

In your example it would be something like this:

<select data-ng-model="selectedTestAccount" ng-change="updateSelectedAccount(selectedTestAccount)" data-ng-options="item.Id as item.Name for item in testAccounts"></select>

And then in your controller

$scope.updateSelectedAccount = function (selectedTestAccount) {
        console.log(selectedTestAccount);
    }

PS Sorry, just noticed how old this question is :) Hope this might help somebody in the future.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM