【问题标题】:Angular: how to save edited values?Angular:如何保存编辑的值?
【发布时间】:2017-09-11 19:15:52
【问题描述】:

这是我的 plnkr http://plnkr.co/edit/0W1SZll1BOK5uuEtdycy?p=preview

我正在尝试从我的编辑联系人模式中保存已编辑的值。

这是一个从对象中获取当前值的编辑方法:

$scope.edit = function(terminal) {
$scope.name = terminal.name;
$scope.last = terminal.last;
$scope.age = terminal.age;
}

我阅读了有关角度复制的内容,还有其他内容吗? 任何人都可以帮助我,我很高兴学习如何做到这一点

【问题讨论】:

    标签: angularjs


    【解决方案1】:

    在将对象或数组的值分配给另一个变量时使用 angular.copy,并且该对象值不应更改。

    如果没有深度复制或使用 angular.copy,更改属性值或添加任何新属性会更新所有引用同一对象的对象。您的 JS 将如下所示:

    $scope.edit = function(terminal) {
        $scope.name = angular.copy(terminal.name);
        $scope.last = angular.copy(terminal.last);
        $scope.age = angular.copy(terminal.age);
        }
    

    【讨论】:

    • 谢谢 hamza,有一个问题:我用 php 将数据保存到数据库,我需要新函数来保存编辑值吗?还是复制方法会自动执行此操作?
    • 使用相同的 angular.copy 将这些值放入一些额外的 javascript 变量中,而不是放入一些额外的 $scope 变量中,因为 $scope 告诉我们哪些值将与我们的视图绑定。
    【解决方案2】:

    您一开始就没有使用 ng-model 中的一个对象,而是使用单独的范围属性,从而创建了许多额外的手动工作。

    还有一条黄金法则是if you don't have a dot in ng-model you are doing it wrong

    执行以下操作:

    <input ng-model="terminal.name">
    <input ng-model="terminal.age">
    

    然后按照以下思路进行操作:

    $scope.edit = function(terminal) {
        // store reference to terminal being edited
        $scope.currentTerminal = terminal;
        // make a copy so live one is not affected -- will be used in form
        $scope.terminal = angular.copy(terminal);
    }
    
    $scope.save = function(){
      // update stored original with changes
      angular.extend($scope.currentTerminal,  $scope.terminal);
      // reset terminal used in form
      $scope.terminal ={};
    }
    

    我强烈建议你摆脱 jQuery 和 bootstrap.js 并使用 angular-ui-bootstrap insted

    【讨论】:

    • 谢谢 charlietfl,有一个问题:我用 php 将数据保存到数据库中,我需要新函数来保存编辑值吗?还是 extend 方法会自动做到这一点?
    • 更有理由使用一个对象...非常简单地将其粘贴到 $http 中并且仅在成功时更新视图版本
    • 嗨 charlietfl,尝试像 u sed 一样用点做 ngmodel,但是当我点击编辑按钮,然后点击添加按钮时,添加表单输入上有值
    【解决方案3】:

    您需要传递要编辑的行的索引。单击编辑按钮时传递索引。

    script.js 中的更改

    $scope.edit = function(terminal,index) {
    
        $scope.name = terminal.name;
        $scope.last = terminal.last;
        $scope.age = terminal.age;
        $scope.edit_index = index
    
     }
    
    
    $scope.saveEdit =function(){
        index = $scope.edit_index
        $scope.terminals[index].name = $scope.name;
    
      }
    

    index.html 的变化

    <td> <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#editModalLong" ng-click="edit(terminal,$index)">Edit</button>
    
    <button type="button" class="btn btn-primary" data-dismiss="modal" ng-click="saveEdit()">Save</button>
    

    http://plnkr.co/edit/GpVB2dUiHCY6NslQDuBe?p=preview

    【讨论】:

      猜你喜欢
      • 2022-01-26
      • 2020-04-04
      • 2011-09-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-11-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多