简体   繁体   中英

How to get form input value to replace form on submit with Angular.js

I'm new to Angular. I have a form in an ordered list. When a user inputs a value in the form and clicks "add", I'd like the value from the form to replace the form, and another list item added below with the same form allowing the user to add another item, etc., etc.

Below is what I've got so far. I have the ordered list with form input, but right now when you click "add", the item appears below as a separate list item instead of replacing the form. I'd like it to replace the form, then insert a new list item below with the same form so the user can continue to add items to the list in this manor.

items.html

<!doctype html>
<html ng-app>
  <head>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.6/angular.min.js"></script>
    <script src="items.js"></script>
  </head>
  <body>
    <h2>Items</h2>
    <div ng-controller="ItemCtrl">
      <ol>
        <li>
          <form ng-submit="addItem()">
           <input type="text" ng-model="itemText"  size="30"
                  placeholder="add new item to list">
           <input class="btn-primary" type="submit" value="add">
          </form>
        </li>
        <li ng-repeat="item in items">
          <span>{{item.text}}</span>
        </li>
      </ol>
    </div>
  </body>
</html>

items.js

function ItemCtrl($scope) {
  $scope.items = [];

  $scope.addItem = function() {
    $scope.items.push({text:$scope.itemText});
    $scope.itemText = '';
  };
}

http://jsfiddle.net/kL4rp/

How do I get that to work as described?

Thanks

Looks like you just need to switch the form and ng-repeat directive.

Like so:

<div ng-controller="ItemCtrl">
  <ol>
    <li ng-repeat="item in items">
      <span>{{item.text}}</span>
    </li>
    <li>
      <form ng-submit="addItem()">
       <input type="text" ng-model="itemText"  size="30"
              placeholder="add new item to list">
       <input class="btn-primary" type="submit" value="add">
      </form>
    </li>
  </ol>
</div>

jsfiddle example

I edited your fiddle:

http://jsfiddle.net/kL4rp/2/

I believe if you just place the ng-repeat of items above the form you will achieve the desired behavior.

    <li ng-repeat="item in items">
      <span>{{item.text}}</span>
    </li>
    <li>
      <form ng-submit="addItem()">
        <input type="text" ng-model="itemText"  size="30"
          placeholder="add new item to list">
        <input class="btn-primary" type="submit" value="add">
      </form>
    </li>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM