Reputation: 698
I am trying to revert the value of input box when user clicks Cancel button. What I am doing wrong here? Here show button will backup the value of a in 'temp' variable and if the user cancels the input with the help of revert button it should reflect original values.
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.name={}
var temp=""
$scope.name.a = {"person":"Shah"};
$scope.editOn = false
$scope.abc= function(){
$scope.editOn= true
temp=$scope.name.a
}
$scope.cde= function(){
$scope.name.a = temp
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.9/angular.min.js"></script>
<!DOCTYPE html>
<html>
<body>
<div ng-app="myApp" ng-controller="myCtrl"><br>
{{name.a.person}} <br>
Name: <input ng-model="name.a.person" ng-show="editOn">
<button ng-click="abc()">show</button>
<button ng-click="cde()">revert</button>
</div>
</body>
</html>
Upvotes: 1
Views: 534
Reputation: 2376
You can achieve that with ng-change
and storing a string and not an object in your temp
variable. See snippet below:
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.name={}
$scope.changeName = () => {
$scope.name.a.person = $scope.inputModel;
}
var temp=""
$scope.name.a = {"person":"Shah"};
$scope.editOn = false
$scope.abc= function(){
$scope.editOn= true
temp = $scope.name.a.person
$scope.inputModel = temp;
}
$scope.cde = function(){
$scope.inputModel = temp
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.9/angular.min.js"></script>
<!DOCTYPE html>
<html>
<body>
<div ng-app="myApp" ng-controller="myCtrl"><br>
{{name.a.person}} <br>
Name: <input ng-change="changeName()" ng-model="inputModel" ng-show="editOn">
<button ng-click="abc()">show</button>
<button ng-click="cde()">revert</button>
</div>
</body>
</html>
Upvotes: 0
Reputation: 6233
There were two errors,
You are modifying temp variable everytime input value changes, so temp doesn't store the initial value anymore.
temp and name.a point to same object, they have same reference. So you'll have to copy the object so that temp and name.a have reference to different objects.
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.name={}
var temp=""
$scope.name.a = {"person":"Shah"};
$scope.editOn = false
temp=angular.copy($scope.name.a)
$scope.abc= function(){
$scope.editOn= true
}
$scope.cde= function(){
$scope.name.a = temp
console.log(temp)
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.9/angular.min.js"></script>
<!DOCTYPE html>
<html>
<body>
<div ng-app="myApp" ng-controller="myCtrl"><br>
{{name.a.person}} <br>
Name: <input ng-model="name.a.person" ng-show="editOn">
<button ng-click="abc()">show</button>
<button ng-click="cde()">revert</button>
</div>
</body>
</html>
Upvotes: 2