AngularJS的双向绑定特性的确很好用,但是在实际使用中遇到了一些问题:我首先使用ng-repeat将数据重复展示出来(item in datas),然后在关联的modal对话框中提供修改功能(将item的对应项使用ng-model绑在modal的form上),但是由于双向绑定的原因,即便未点击保存按钮,在对话框中的修改也会实时影响到页面上的展示数据,这样有些影响体验,有没有好的解决方法呢?我也尝试在js中使用一个中间变量来保存未修改的数据,但是一旦item变化,中间变量也改变了。
相关代码
html:
<p ng-repeat="item in data">
{{item.name}}
{{item.age}}
</p>
<a data-toggle="modal" data-target="#mySettingModal{{item.id}}" ng-click="fresh(item)">modify</a>
<p class="modal fade" id="mySettingModal{{item.id}}" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<p class="modal-dialog" style="z-index: 1050">
<form name="form">
<p class="form-group">
<label for="name" class="control-label">名称:</label>
<input type="text" class="form-control" id="name" ng-model="item.name" />
</p>
</form>
<button type="button" class="btn btn-default" data-dismiss="modal" ng-click="reset()">Close</button>
<button type="button" class="btn btn-primary" ng-click="updateSetting(item)">Save changes</button>
</p>
</p>
JS:
$http.get("/").success(function(data) {
$scope.data = data;
var interItem;
$scope.fresh = function(item) {
interItem = item;
console.log(interItem);
};
$scope.reset = function() {
console.log(interItem);
}
});
过去多啦不再A梦2017-05-15 16:54:05
angular.copy(item)
A copy of the object should be used in the modal. After the user clicks to confirm, the modified and submitted copy will overwrite the original data.
The reason for using angualr.copy
is that it deep copies the object. Simply assigning the reference of the object to another variable will not achieve the effect you want.
This is the description of the copy method from angular documentation
Creates a deep copy of source, which should be an object or an array.
https://docs.angularjs.org/api/ng/function/angular.copy