Bai*_*ith 111 angularjs ng-options
我正在使用ng-options从下拉列表中选择值.我希望能够将旧值与新值进行比较.ng-change适用于获取下拉的新值,但我如何同时获得新值和原始值?
<select ng-change="updateValue(user)" ng-model="user.id" ng-options="user.id as user.name for user in users"></select>
Run Code Online (Sandbox Code Playgroud)
例如,假设我想让控制器记录,"你以前的user.name是BILL,你当前的用户名是PHILLIPE."
db-*_*inf 269
使用角度{{表达式}},您可以将旧用户或user.id值作为文字字符串添加到ng-change属性:
<select ng-change="updateValue(user, '{{user.id}}')"
ng-model="user.id" ng-options="user.id as user.name for user in users">
</select>
Run Code Online (Sandbox Code Playgroud)
在ngChange上,updateValue的第一个参数将是新的用户值,第二个参数将是上次使用angular更新select-tag时形成的文字,具有旧的user.id值.
小智 14
你也可以使用
<select ng-change="updateValue(user, oldValue)"
ng-init="oldValue=0"
ng-focus="oldValue=user.id"
ng-model="user.id" ng-options="user.id as user.name for user in users">
</select>
Run Code Online (Sandbox Code Playgroud)
TGH*_*TGH 13
只需在控制器中保留currentValue变量,并在每次更改时更新.然后,您可以在每次更新之前将其与新值进行比较.
使用手表的想法也很好,但我认为一个简单的变量是最简单和最合理的解决方案.
Viv*_*day 13
您可以使用类似ng-change = someMethod({{user.id}})的内容.通过将值保持在{{expression}}边,它将在线计算表达式并为您提供当前值(调用ng-change方法之前的值).
<select ng-model="selectedValue" ng-change="change(selectedValue, '{{selectedValue}}')">
Run Code Online (Sandbox Code Playgroud)
您可以使用示波器手表:
$scope.$watch('user', function(newValue, oldValue) {
// access new and old value here
console.log("Your former user.name was "+oldValue.name+", you're current user name is "+newValue.name+".");
});
Run Code Online (Sandbox Code Playgroud)
https://docs.angularjs.org/api/ng/type/$rootScope.Scope#$watch
| 归档时间: |
|
| 查看次数: |
126938 次 |
| 最近记录: |