Angular ng-model ng-repeat清除所有输入

时间:2016-09-20 08:23:17

标签: angularjs input ng-repeat

为什么函数clear()在下面的示例中不起作用?

HTML

<!DOCTYPE html>
<html>

<head>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
  <link rel="stylesheet" href="style.css" />
  <script src="script.js"></script>
</head>

<body>
  <div class="wrapper" ng-app="app" ng-controller="AppController">
    <div class="form-control" ng-repeat="n in [] | range:number">
      <input type="text" ng-model="newVar" />
      <span>{{newVar}}</span>
    </div>
    <!-- //form controll -->
    <input type="range" ng-model="number" max="9" />
    <label>Repeat input fields {{number}} times</label>
    <button ng-click="clear()">clear</button>
  </div>
</body>

</html>

控制器

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

app.controller('AppController', function($scope) {
    $scope.number = 5;
    $scope.newVar = 0;
    $scope.clear = function() {
        $scope.newVar ='';
    }
});//AppController

app.filter('range', function () {
  return function (input, total) {
    total = parseInt(total);
    for (var i = 0; i < total; i++) {
      input.push(i);
    }
    return input;
  }; //filter range
});

这是我的 plnkr

2 个答案:

答案 0 :(得分:2)

ng-repeat为每个'repeat'创建一个子范围,因此您可以使用$parent访问控制器的范围。此外,您可以使用数组/对象存储所有值,而不是仅为视图中的所有不同行使用一个变量。您可以使用$index内的ng-repeat执行此操作:

<!DOCTYPE html>
<html>

<head>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
  <link rel="stylesheet" href="style.css" />
  <script src="script.js"></script>
</head>

<body>
  <div class="wrapper" ng-app="app" ng-controller="AppController">
    <div class="form-control" ng-repeat="n in [] | range:number">
      <input type="text" ng-model="$parent.newVar[$index]" />
      <span>{{newVar[$index]}}</span>
    </div>
    <!-- //form controll -->
    <input type="range" ng-model="number" max="9" />
    <label>Repeat input fields {{number}} times</label>
    <button ng-click="clear()">clear</button>
  </div>
</body>

</html>

这种方式clear()清除所有值,因为它将整个对象设置为空字符串。

这就是为什么我也会将clear函数改为这样的原因:

$scope.clear = function() {
        $scope.newVar = {};
}

答案 1 :(得分:0)

当您手动更新文本框值时,它实际上会在 childScope 中设置newVar值(由ng-repeat指令创建),因此不要将其绑定到newVar,而是尝试绑定值使用$parent.newVar,它会完美运作。

<!DOCTYPE html>
<html>

<head>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
  <link rel="stylesheet" href="style.css" />
  <script src="script.js"></script>
</head>

<body>
  <div class="wrapper" ng-app="app" ng-controller="AppController">
    <div class="form-control" ng-repeat="n in [] | range:number">
      <input type="text" ng-model="$parent.newVar" />
      <span>{{newVar}}</span>
    </div>
    <!-- //form controll -->
    <input type="range" ng-model="number" max="9" />
    <label>Repeat input fields {{number}} times</label>
    <button ng-click="clear()">clear</button>
  </div>
</body>

</html>

here是你的祸根