当用户单击取消按钮时,我试图恢复输入框的值。我在这里做错了什么?在这里, show 按钮将备份in'temp'变量的值,如果用户在 revert 按钮的帮助下取消输入,则它应反映原始值。
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>
答案 0 :(得分:2)
有两个错误,
每当输入值更改时,您都在修改temp变量,因此temp不再存储初始值。
temp和name.a指向同一对象,它们具有相同的引用。因此,您必须复制对象,以便temp和name.a引用不同的对象。
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>
答案 1 :(得分:0)
您可以使用ng-change
并在您的temp
变量中存储字符串而不是对象来实现。参见下面的代码段:
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>