Angular JS:在 ng-change 上获取 ng-model [英] Angular JS: get ng-model on ng-change
问题描述
我有以下 HTML
<select ng-model="country" ng-options="c.name for c in countries" ng-change="filterByCountry"></select>
这是由以下带有国家/地区列表的对象提供的
That is beeing fed by the following object with a list of countries
$scope.countries = [{name:Afeganistão, country:AF}, {name:África do Sul, country:ZA}, name:Albânia, country:AL}, {name:Alemanha, country:DE}, {name:Andorra, country:AD} ...];
当我更改下拉值时,我希望我的模型 ($scope.country) 在 filterByCountry 函数内更新,但事实并非如此.我在这里错过了什么?
When I change my dropdown value I was expecting my model ($scope.country) to be updated, inside filterByCountry function, but it isn't. What am I missing here?
推荐答案
ng-change
处理程序在 ng-model
实际更新之前被触发.如果您希望 filterByCountry
在每次 $scope.country
更改时触发(而不是仅在下拉列表更改时),您应该使用以下代码:
The ng-change
handler is fired before the ng-model
is actually updated. If you want filterByCountry
to be fired every time $scope.country
changes (rather than just when the dropdown changes), you should use the following instead:
$scope.$watch('country', filterByCountry);
我总是发现在可能的情况下对 $scope
中的变化做出反应比对 DOM 事件做出反应更有用.
I always find it more useful to react to changes in my $scope
rather than DOM events when possible.
这篇关于Angular JS:在 ng-change 上获取 ng-model的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!