【问题标题】:Get original values of the model with angularJS after clicking on button单击按钮后使用 angularJS 获取模型的原始值
【发布时间】:2016-11-08 07:35:42
【问题描述】:

我曾经使用 BackboneJS 获取带有 this.model.changedthis.model._previousAttributes 的模型的原始值。

我想通过检测由文本字段、复选框设置的模型中的所有更改来使用与角度相同的功能,而不是像ng-change 那样在一个文本文本字段中。

我尝试在form的div中使用它,但没有成功。

我也试过用:

 $scope.policyL = savingsDraft.fromServer();
    $scope.$watch('policyL', function (oldV, newV) {
 });

但它也没有用。

我的视图代码示例:

form(role='form', ng-change='changed (policy, newP)' novalidate)
  .row
    .col-sm-4.form-group
      label.control-label Taux de rendement
      input.form-control(type='number',
        min=0,
        max=1,
        ng-model='policy.admin.depEarnRate')
    .col-sm-4.form-group
      label.control-label Frais de contrat
      input.form-control(type='number',
        min=0,
        ng-model='policy.admin.feesIni')

在我的控制器中:

$scope.accept = function () {
     $scope.change = function();
};

PS:我想点击accept按钮后得到原模型。

【问题讨论】:

    标签: javascript angularjs model-view-controller backbone.js


    【解决方案1】:

    你可以在控制器实例化时制作一个副本。然后每当 $watch 被触发时,将当前模型与副本进行比较。如果不同,请从副本中获取值。

    【讨论】:

      【解决方案2】:

      如果您有表单,最好保留一份原始数据的副本。如果需要,您可以轻松地重置回主副本。

      $scope.master = dataModel;
      $scope.dataModel = angular.copy($scope.master);
      
      
      $scope.reset = function () {
          $scope.dataModel = angular.copy($scope.master);
          $scope.yourForm.$setPristine();
      };
      

      然后,如果你真的想只从主控那里获取更改,我使用 Backbone 的 changedAttributes 函数并对其进行了修改以适应我们这里的情况。

      var changedAttributes = function(master, diff) {
          if (!diff) return false;
          var changed = {};
          for (var attr in diff) {
              var val = diff[attr];
              if (!_.isEqual(master[attr], val)) changed[attr] = val;
          }
          return _.size(changed) ? changed : false;
      },
      

      要使用这个:

      var changes = changedAttributes($scope.master, $scope.dataModel);
      if (changes) console.log("dataModel is different from master");
      

      要在 Angular 应用中包含下划线,angular-underscore 似乎效果很好。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-12-10
        • 2019-05-27
        • 2021-12-08
        • 1970-01-01
        • 2017-08-30
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多