$scope更新,而应该创建一个新条目



我希望在文本框中输入内容并按下按钮时添加新条目,但相反,我第一次创建的同一条目正在更新。代码:

var app = angular.module("myApp", []);
app.controller("myCtrl", function($scope) {
  $scope.ss = [];
  $scope.getPlate = function() {
    //$scope.plate1= abc;
    $scope.ss = [
      {plate1: 'some plate 1'},
      {plate1: 'some plate 2'},
      {plate1: 'some plate 3'},
      {plate1: $scope.newplate}
    ]
    var i = 0;    
    for (i=0; i<$scope.ss.plate1.length; i++) {
      alert(i);
    }
  }
});

.html:

<div ng-controller="myCtrl">
    <table>
        <tr ng-repeat="xx in ss">
            <td>
                {{xx.plate1}}
            </td>
            <td>
            </td>
        </tr>
    </table>
    <input type="text" ng-model="newplate"/>
    <input type="button" ng-click="getPlate()"/>
</div>

请帮忙。

你只是覆盖了$scope.ss数组中的第四个对象。您应该在单击按钮时将新对象推送到数组中:

var app = angular.module("myApp",[]);
app.controller("myCtrl", function($scope){
   $scope.ss = [
      {plate1: 'some plate 1'},
      {plate1: 'some plate 2'},
      {plate1: 'some plate 3'},
      {plate1: $scope.newplate}
   ];
    $scope.addPlate = function(){
      $scope.ss.push({plate1: $scope.newplate});
      $scope.newplate = ''; //To clear the input box after adding a new item
    };
});

.HTML:

<div ng-controller="myCtrl">
  <table>
    <tr ng-repeat="xx in ss">
      <td>{{xx.plate1}}</td>
      <td></td>
    </tr>
  </table>
  <input type="text" ng-model="newplate"/>
  <input type="button" ng-click="addPlate()"/>
</div>

相关内容

最新更新