angular.js - AngularJS two-way binding options
天蓬老师
天蓬老师 2017-05-15 16:52:05
0
1
658

The two-way binding feature of AngularJS is indeed very useful, but I encountered some problems in actual use: I first used ng-repeat to display the data repeatedly (item in datas), and then provide the modification function in the associated modal dialog box (binding the corresponding item to the modal form using ng-model), but due to two-way binding, even if the save button is not clicked, in the dialog box The modification will also affect the display data on the page in real time, which will affect the experience. Is there a good solution? I also tried to use an intermediate variable in js to save the unmodified data, but once the item changes, the intermediate variable also changes.
Related code
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);
  }
});
天蓬老师
天蓬老师

欢迎选择我的课程,让我们一起见证您的进步~~

reply all(1)
过去多啦不再A梦

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

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template