为什么angular不会更新我的模型

时间:2013-06-12 09:16:55

标签: angularjs angularjs-directive angularjs-scope

在我的(表)概述中,我有自定义指令。该指令显示客户详细信息并包含编辑按钮。单击此按钮时,将弹出编辑表单。当我更改客户的价值时,我发现细节也会更新。这是因为绑定,因此正是我想要的。

但是,当我在编辑表单上按取消时,我想恢复原始值,这是我无法工作的。问题是细节包含编辑的值,编辑的值不会被恢复。

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


The 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>

1 个答案:

答案 0 :(得分:2)

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

而不是做

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

我不得不做

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

有关解释,请参阅:

Why does Angular not databind data when an object is copied from another object?Dirty checking with shared service between controllers, One way works the other does not?