Angularjs问题追加表

时间:2014-06-26 05:09:44

标签: javascript angularjs append

我正在学习Angularjs(我还很新鲜)。我试图在按钮单击时向表添加一行。我基于本教程中的代码 - http://plnkr.co/edit/64e1nGNkc4vYynEY6IQz?p=preview

我的代码附加了内容,但它遗漏了和标签,并且正在添加标签。此外,我尝试只添加一个像'test'这样的简单字符串,并在字符串中添加标签...为什么添加我没有包含的标签?

我的HTML -

      <div ng-controller="growingTable">
        <div ng-controller="incomeController">
          <table class="table table-striped">
            <tr>
              <td>Account</td>
              <td>Budget</td>
              <td>%</td>
              <td>Enter Amount</td>
              <td>Total</td>
              <td>%</td>
            </tr>
            <tr>
              <tr ng-repeat="r in rows">
                <td><input class="form-control" placeholder="Account" ng-model="r.account"></td>
                <td><input class="form-control" ng-model="r.funding.startingEstimate"y placeholder="Budgeted"></td>
                <td class="warning">20%</td>
                <td>{{funding.needed}}</td>
                <td class="warning">$500</td>
                <td class="warning">50%</td>
              </tr>
            </table>
            <button class="btn btn-primary"ng-click="addField()">ADD FIELD</button>
          </div>
        </div>
      </div>
    </div>
  </div>
</body>

Javascript -

var app = angular.module('myApp', []);
app.controller('incomeController', function($scope) {
 $scope.funding = { startingEstimate: 0 };
 computeNeeded = function() {
$scope.funding.needed = $scope.funding.startingEstimate / 100;
};
$scope.$watch('funding.startingEstimate', computeNeeded);
});

app.controller('growingTable', function($scope){
$scope.rows = [];

$scope.addField = function(){
    $scope.rows.push({        
    });
}    
});    

这是在表中的行之后追加的代码。桌子元素怎么了?为什么它会添加span标签??

<input class="form-control ng-scope" placeholder="Account">
<input class="form-control ng-scope ng-pristine ng-valid" placeholder="Budgeted" ng-model="funding.startingEstimate">
<span class="ng-scope ng-binding">20%$50050%</span>

谢谢!

1 个答案:

答案 0 :(得分:0)

另一种方法是在控制器中创建一个数组并使用ng-repeat来生成表。这样,你的“添加字段”就可以了。函数只需要在数组上创建一个新元素,Angular将为你处理更新html。

例如,您的HTML将是:

<div ng-app="app">
<div ng-controller="growingTable">
<table>
    <tr ng-repeat="r in rows">
        <td><input class="form-control" placeholder="Account" ng-model="r.account"></td>
        <td><input class="form-control" ng-model="r.startingEstimate" placeholder="Budgeted"></td>
        <td class="warning">20%</td>
        <td>{{r.needed}}</td>
        <td class="warning">$500</td>
        <td class="warning">50%</td>
     </tr>
</table>

 <button ng-click="addField()">ADD FIELD</button>
        <br>
           {{rows}}
 </div>

你的应用程序看起来像:

angular.module('app', []);

angular.module('app').controller('growingTable', function($scope){
$scope.rows = [];

$scope.addField = function(){
    $scope.rows.push({
        account : '',
        startingEstimate : '',
        needed : ''
    });
}

});

您将找到工作版http://jsfiddle.net/y53Yd/