首页 > 解决方案 > 如何在 Angular JS 中拼接具有空属性的对象?

问题描述

我正在尝试编写一个函数,允许我添加一个具有空属性的新行。$scope.book 对象具有以下属性

我想出了如何使用对象函数 removeBook() 删除它们。

我似乎无法弄清楚如何在函数 addBook(){} 中添加具有空属性的新书对象。这是我的代码。

如何添加具有空属性的对象?

<!doctype html>
    <html lang='en' ng-app>
      <head>
       <title>Book Shopping Cart</title>

      <script src="js/angular10.js"></script>
      <script>
        function CartControler($scope) {
          $scope.books = [
            {title: 'Absolute Java',    
                qty: 1, price: 114.95},
            {title: 'Pro HTML5',        
                qty: 1, price: 27.95},
            {title: 'Head First HTML5', 
                qty: 1, price: 27.89}
          ];

          $scope.addBook = function (index) {
            console.log("add new book");
            $scope.splice();
          }

          $scope.removeBook = function(index) {
            $scope.books.splice(index, 1);
          }

        }
      </script>
      <link rel="stylesheet" href="css/ex05.css">
      </head>

      <body ng-controller="CartControler">

        <table>
          <caption><b>My Books</b></caption>
          <thead>
            <tr>
                <th>Title</th>
                <th>Qty</th>
                <th>UnitPrice</th>
                <th>Line Total</th>
                <th>Total</th>
            </tr>
          </thead>
          <tbody >
            <tr ng-repeat="book in books">
                <td><input ng-model="book.title"></td>
                <td>
                    <input ng-model="book.qty" size="2">
                </td>
                <td>
                    <input ng-model="book.price" >
                </td>
                <td>{{book.price * book.qty | currency}}</td>
                <td>
                    <button ng-click="removeBook($index)">
                        Remove
                    </button>
                </td>
            </tr>
          </tbody>
          <tfoot>
            <tr>
              <th>
                <button ng-click="addBook($index)">New</button>
              </th>
              <th></th>
              <th></th>
              <th>
                <button ng-click="">Save</button>
              </th>
              <th></th>

            </tr>
          </tfoot>
        </table>
      </body>
    </html>

标签: arraysangularjsjavascript-objects

解决方案


推荐阅读