最簡單的辦法,將在所有場合的工作是使leader
的副本,當你加載它,並比較當前leader
與您按下按鈕時製作的副本一起使用。
function TodoCtrl($scope) {
// initialization
var originalLeader = null;
$scope.leader = null;
$scope.mode = 'edit';
// this is where you get your leader data, in my example
// I simply set it to demo data but you can load the
// data using AJAX for example
var loadLeader = function() {
var leaderData = {
mobile: '000',
work: '111'
};
originalLeader = angular.copy(leaderData);
$scope.leader = leaderData;
}
// loadLeader will be invoked on page load
loadLeader();
$scope.save_profile = function (leader) {
// you have access to your original data and current data,
// you can compare them and do whatever you want with them
console.log('originalLeader ', originalLeader);
console.log('leader ', leader);
// for example
if (leader.mobile != originalLeader.mobile) {
alert('Mobile has changed from ' + originalLeader.mobile + ' to ' + leader.mobile);
}
};
}
一些答案建議使用$scope.$watch
,可以實現用你的解決方案,但你必須要小心,因爲$scope.$watch
回調將在每個變化被調用。爲了說明我的意思,讓我們添加一些像這樣的代碼:
$scope.$watch('leader.mobile', function(newVal,oldVal) {
console.log('newVal ', newVal);
console.log('oldVal ', oldVal);
});
讓leader.mobile
是000
在初始時間。
您鍵入1
文本框,現在leader.mobile
是0001
,回調函數將被調用,並且日誌將是:
newVal 0001
oldVal 000
現在你按backspace
和刪除1
你以前鍵入的leader.mobile
變量現在000
和日誌:
newVal 000
oldVal 0001
您當前的數據是一樣的首發數據,但$scope.$watch
被調用了兩次,並且很難確定數據是否真的發生了變化。你會需要實現,像這樣一些額外的代碼,東西:
// be careful about this, you need to set to null if you reload the data
var originalMobile = null;
$scope.$watch('leader.mobile', function(newVal,oldVal) {
// set originalMobile to value only if this is first
// invocation of the watch callback, ie. if originalMobile
// was not set yet
if (originalMobile == null) {
originalMobile = oldVal;
}
});
$scope.save_profile = function(leader) {
if (leader.mobile != originalMobile) {
// ...
}
}
對於該文本框在這兩個文本框,你想這樣做 –
我假設你要比較它們在文本框原始值按下按鈕時加載文本框中最終變量的時間。我對麼? – stjepano