1

在我的(表格)概述中,我有自定义指令。该指令显示客户详细信息并包含一个编辑按钮。单击此按钮时,会弹出一个编辑表单。当我更改客户的值时,我看到详细信息也已更新。由于绑定,这是偏离路线的,这正是我想要的。

但是,当我在编辑表单上按取消时,我想恢复原始值,这是我无法工作的。问题是详细信息包含已编辑的值,未恢复已编辑的值。

我创建了一个 plunker,其中包含我的代码的重要部分。它不起作用,但它应该让我了解我是如何设置一切的。


笨蛋

var module = angular.module('app', []);

module.directive('customerDetails', function ($http, CustomerService) {
  return {
      restrict: 'E',
      templateUrl: '/Customer/View',
      scope: {
          customerId: '=',
          showEditCustomerForm: '&customerEditForm'
      },
      link: function (scope, element, attr) {
          scope.customerData = {};

          CustomerService.getCustomerById(scope.customerId).then(function (response) {
              scope.customerData.customer = response;
          });
      }
  }
});

module.controller('DemoCtrl', function ($scope) {
  $scope.showEditCustomerForm = function (customer) {
      $scope.customerFormData = {};
      $scope.customerFormData.customer = customer; 
      $scope.customerFormData.originalCustomer = angular.copy(customer);

      $scope.showAddCustomer = true;
      $scope.showOverlay = true;
  };

  $scope.hideAddCustomerForm = function (restoreOriginal) {

    if (restoreOriginal) {
      // Here I want to restore the original customer to discard the changes, but this doesn't work
      // The View is not updated
      $scope.customerFormData.customer = $scope.customerFormData.originalCustomer;
    }

    $scope.showAddCustomer = false;
    $scope.showOverlay = false;
  }
});

<body ng-controller="DemoCtrl">
  <table>
    <tbody id="customerRows" data-ng-repeat="customer in customers">
      <tr>
        <td>
          <customer-Details customer-Id="customer.Id" customer-edit-form="showEditCustomerForm(customer)"></customer-Details>
        </td>
      </tr>
    </tbody>
  </table>

  <div data-ng-switch="showAddCustomer">
    <div data-ng-switch-when="true">
        <div class="overlay">
        </div>
        <div ng-include="'/Customer/Add'"></div>    
    </div>
  </div>
</body>
4

1 回答 1

2

@finishingmove:你非常接近。我终于有了答案。

而不是做

$scope.customerFormData.customer = angular.copy($scope.customerFormData.originalCustomer);

我必须做

angular.copy($scope.customerFormData.originalCustomer, $scope.customerFormData.customer);

解释见:

当一个对象从另一个对象复制时,为什么 Angular 不绑定数据? 并且 在控制器之间使用共享服务进行脏检查,一种方法有效,另一种方法无效?

于 2013-06-12T12:16:09.967 回答