Add new text box on click of a button in angular js

不想你离开。 提交于 2019-12-02 03:33:43

In you code, you are doing:-

        $scope.addContact = function()
        {
          $scope.contact.push({$scope.contact})
        }

This is where the problem is. If you just need to add an empty textbox, you just need to add an empty contact to contacts, and ng-repeat will take care of adding the new textbox in the list. Another thing is that you were pushing into contact, and not contacts.

Also, ngSubmit is used inside a form, which you do not have. So, use ng-click instead. Here is a plunker showing the code working.

            $scope.addContact = function()
            {
              $scope.contacts.push({ name: '' });
            }

You should replace your ng-submit with ng-click that will solve your problem And with that you need to change your object structure to persist a value, like you need to add contact number in contact object like contact.number

Markup

<ul>
    <li ng-repeat="contact in contacts">
      <input type="text" ng-model="contact.number" />
    </li>
    <li>
      <button type="button" ng-click="addContact()">add</button>
    </li>
</ul>

Code

angular.module('controllerAsExample', [])
.controller('SettingsController1', function($scope) {
  $scope.contacts = []
  $scope.addContact = function() {
    $scope.contacts.push({
    })
  }
});

Demo Plunkr

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