angular.copy使用
效果:
初始状态:
输入信息后未保存状态:
点击save后状态:
当输入框内容和master内容不一致时:
点击reset使得user的信息被重置为master中信息:
具体代码:
1 <!DOCTYPE HTML> 2 <html ng-app="app"> 3 <head><script src="./angular.min.js"></script></head> 4 <body> 5 <div ng-controller="exampleController"> 6 <form> 7 name:<input type="text" ng-model="user.name" /> 8 <br/> 9 email:<input type="email" ng-model="user.email"/> 10 <br/> 11 gender: 12 <input type="radio" ng-model="user.gender" value="male"/> 13 <input type="radio" ng-model="user.gender" value="female"/> 14 </form> 15 <button ng-click="reset()" >reset</button> 16 <button ng-click="save(user)">save</button> 17 <p>user={{user}}</p> 18 <p>master={{master}}</p> 19 </div> 20 <script> 21 var app=angular.module(‘app‘,[]); 22 app.controller(‘exampleController‘,function($scope){ 23 $scope.master={}; 24 $scope.save = function(user){ 25 $scope.master=angular.copy(user);//将user的内容复制给master 26 }; 27 $scope.reset=function(){ 28 angular.copy($scope.master,$scope.user);//将master内容复制给user 29 }; 30 $scope.reset(); 31 }); 32 </script> 33 34 </body> 35 </html>
时间: 2024-10-06 18:26:13