我正在使用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>
例如,假设我想要控制器记录“您以前的用户名称为BILL,您当前的用户名称为PHILLIPE。”
我正在使用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>
例如,假设我想要控制器记录“您以前的用户名称为BILL,您当前的用户名称为PHILLIPE。”
使用一个角括号表达式{{expression}},你可以将旧的用户或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>
在ngChange事件中,updateValue方法的第一个参数将是新的用户值,第二个参数将是上次由Angular更新select标记时所形成的文本字面量,其使用旧的user.id值。
user.id
是数字时才能不使用引号运行...如果user.id
是字符串或GUID,则无法正常工作。 - Tamas。
<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>
您可以使用类似ng-change=someMethod({{user.id}})的方式。 通过将您的值保留在{{expression}}内,它会在行内计算表达式,并为您提供当前值(在调用ng-change方法之前的值)。
<select ng-model="selectedValue" ng-change="change(selectedValue, '{{selectedValue}}')">
在控制器中保留一个currentValue变量,在每次更改时更新它。然后,在更新之前每次将其与新值进行比较。
使用$watch的想法也不错,但我认为简单的变量是最简单和最合乎逻辑的解决方案。
您可以使用作用域监视(scope watch):
$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+".");
});
https://docs.angularjs.org/api/ng/type/$rootScope.Scope#$watch
$watch
会在变量改变时触发。监视器增加了复杂性,并且容易在代码更改其值时创建更新周期。 - Rhys van der Waerden你可以随时这样做:
... ng-model="file.PLIK_STATUS" ng-change="file.PLIK_STATUS = setFileStatus(file.PLIK_ID,file.PLIK_STATUS,'{{file.PLIK_STATUS}}')" ...
在控制器中:
$scope.setFileStatus = function (plik_id, new_status, old_status) {
var answer = confirm('Czy na pewno zmienić status dla pliku ?');
if (answer) {
podasysService.setFileStatus(plik_id, new_status).then(function (result) {
return new_status;
});
}else{
return old_status;
}
};