将所有值保存在ng-repeat格式的输入框中

Save all the values in input text box that is in ng-repeat

本文关键字:格式 输入 ng-repeat 存在 保存      更新时间:2023-09-26

我想知道如何保存在ng-repeat内的输入文本框中输入的值,只需单击一个按钮。我见过这样的例子,从文本框中获取值,让用户单独保存每个文本框。下面是一个示例代码:

$scope.items=[1,2,3,4]
<div ng-repeat="item in items">
<input type="text" ng-model=item.id>
</div>
<button type="button" ng-click="saveAllValues()">Save</button>

您只需将ng-model绑定到另一个对象,并使用$index来引用ng-repeat内的索引:

var myApp = angular.module('myApp', []);
myApp.controller('MyCtrl', function($scope) {
  $scope.items = [1, 2, 3, 4];
  $scope.values = [];
  
  $scope.saveAllValues = function() {
    alert($scope.values);
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="MyCtrl">
  <div ng-repeat="item in items">
    <input type="text" ng-model="values[$index]">
  </div>
  <button type="button" ng-click="saveAllValues()">Save</button>
</div>

var myApp = angular.module('myApp', []);
myApp.controller('MyCtrl', function($scope) {
      $scope.items = [1, 2, 3, 4];   
      $scope.saveAllValues = function() {
        alert($scope.items);
      }
    });
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="MyCtrl">
  <div ng-repeat="$index in items">
    <input type="text" ng-model='items[$index]'>
  </div>
  <button type="button" ng-click="saveAllValues(items)">Save</button>
</div>

试试这个:

您需要在您的模型中使用.符号。参考这个

angular.module('myApp', [])
  .controller('myController', function($scope) {
    $scope.items = [{
      value: 0
    }, {
      value: 1
    }, {
      value: 2
    }]
    $scope.saveAllValues = function(items) {
      alert(JSON.stringify(items));
    };
  });
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<!DOCTYPE html>
<html lang="en" ng-app="myApp">
<head>
  <meta charset="UTF-8">
  <title></title>
  <script src="js/angular.min.js"></script>
</head>
<body ng-controller="myController">
  <div ng-repeat="item in items">
    <input type="text" ng-model='item.value'>
  </div>
  <button type="button" ng-click="saveAllValues(items)">Save</button>
</body>
</html>

我被困在同样的情况下,发现了一些很好的"ng-model-option"设置是更新模糊,你准备好保存个人输入值,同时做"ng-repeat"。你需要添加新版本的angularjs,试试这个"https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.5/angular.js"

var myApp = angular.module('myApp', []);
myApp.controller('MyCtrl', function($scope) {
  $scope.items = ['red', 'blue', 'green', 'yellow'];
  
  $scope.saveAllValues = function() {
    alert($scope.items );
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.5/angular.js"></script>
<div ng-app="myApp" ng-controller="MyCtrl">
  <div ng-repeat="item in items">
    <input type="text" ng-model="items[$index]" ng-model-options="{updateOn:'blur'}">
  </div>
  <button type="button" ng-click="saveAllValues()">Save</button>
</div>