首页 > AngularJS双向绑定的选择

AngularJS双向绑定的选择

AngularJS的双向绑定特性的确很好用,但是在实际使用中遇到了一些问题:我首先使用ng-repeat将数据重复展示出来(item in datas),然后在关联的modal对话框中提供修改功能(将item的对应项使用ng-model绑在modal的form上),但是由于双向绑定的原因,即便未点击保存按钮,在对话框中的修改也会实时影响到页面上的展示数据,这样有些影响体验,有没有好的解决方法呢?我也尝试在js中使用一个中间变量来保存未修改的数据,但是一旦item变化,中间变量也改变了。
相关代码
html:

<div ng-repeat="item in data">
{{item.name}}
{{item.age}}
</div>
<a data-toggle="modal" data-target="#mySettingModal{{item.id}}" ng-click="fresh(item)">modify</a>
<div class="modal fade" id="mySettingModal{{item.id}}" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
  <div class="modal-dialog" style="z-index: 1050">
        <form name="form">
          <div class="form-group">
            <label for="name" class="control-label">名称:</label>
               <input type="text" class="form-control" id="name" ng-model="item.name" />
          </div>
        </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>
    </div>
  </div>

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);
  }
});

angular.copy(item)

应该在modal里使用一个对象的副本,在用户点击确认后,再将修改提交的副本覆盖掉原来的数据。

使用angualr.copy的原因是它将对象深复制,如果只是简单的将对象的引用赋值给另一个变量是达不到你要的效果的。

这是angular文档对copy方法的描述

Creates a deep copy of source, which should be an object or an array.

https://docs.angularjs.org/api/ng/function/angular.copy

【热门文章】
【热门文章】