Adding lines to a form using AngularJS

一曲冷凌霜 提交于 2019-12-25 09:57:33

问题


I am trying to create a form that users can press the '+' sign and add a new line. I do this by calling a function when a button is clicked and then pushing a new line into the array. The new lines are not being created, however. The function below that removes the line seems to be working.

Here is the js:

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

myApp.controller('myController', ['$scope', '$q', function($scope, $q) {
    $scope.arr = [1,2];
    $scope.addLine = function(index){
        $scope.arr.push();
    }
    $scope.removeLine = function(index){
        $scope.arr.splice(index, 1);
    }
}]);

回答1:


You need to push something into the array.

Push() Definition and Usage: The push() method adds new items to the end of an array, and returns the new length.

Note: The new item(s) will be added at the end of the array.

Note: This method changes the length of the array.

Tip: To add items at the beginning of an array, use the unshift() method.

http://www.w3schools.com/jsref/jsref_push.asp

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

myApp.controller('myController', ['$scope',
  function($scope) {

    $scope.arr = [1, 2];
    $scope.addLine = function(index) {
      $scope.arr.push(index);
    }
    $scope.removeLine = function(index) {
      $scope.arr.splice(index, 1);
    }
  }
]);
<!doctype html>
<html ng-app="myApp">

<head>
  <title>Hello AngularJS</title>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
</head>

<body>
  <div ng-controller="myController">
    <button name="addLine" ng-click="addLine(arr.length+1)">Add Line</button>
    {{ arr | json}}

    <ul>
      <li data-ng-repeat="x in arr">
        {{ x }}  - <button name="addLine" ng-click="removeLine($index)">Remove Line</button>
      </li>
    </ul>

  </div>
</body>

</html>



回答2:


Look this:

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

app.controller('AppController', ['$scope', function($scope) {
    $scope.arr = [1,2];
    $scope.addLine = function(last){
        $scope.arr.push(last + 1);
    }
    $scope.removeLine = function(index){
        $scope.arr.splice(index, 1);
    }
}]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="App" ng-controller="AppController">
    <button ng-click="addLine(arr.length)">Add Line</button>
    <hr/>
    <div data-ng-repeat="x in arr">
        Line: {{x}} <button ng-click="removeLine($index)">Del</button>
    </div>
</div>


来源:https://stackoverflow.com/questions/33662034/adding-lines-to-a-form-using-angularjs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!