2016-01-20 62 views
0

我使用代码通过单击添加行来添加行和2列。 “我的需要就是”, 先填入输入栏中的值, 之后点击添加项目按钮,值必须以表格结构显示。 是初学者。不能使用for循环。 任何人都可以请解决这个问题。如何使用angularjs动态添加行?

尝试代码:https://jsfiddle.net/idris9791_/a7L832LL/

<html > 
    <head> 
    <meta charset="utf-8"> 
    <meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width"> 

    <title>Add Rows</title> 


    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.9/angular.min.js"></script> 

    <body ng-controller="MainController" ng-app="MyApp"> 

    <a href="#" class="button" ng-click="addRow()">Add Row</a> 
    <form> 
    First Name : <input name="myInput" ng-model="user.firstName" required> 
    First Name : <input name="myInput" ng-model="user.lastName" required> 
    </form> 


<table> 
    <thead> 
    <tr> 
     <th>Some Header</th> 
    </tr> 
    </thead> 
    <tbody> 
    <tr ng-repeat="rowContent in rows"> 
    <td>{{rowContent.firstName}}</td> 
    <td>{{rowContent.lastName}}</td> 
</tr> 
    </tbody> 
</table>  
<script> 
angular.module('MyApp', []) 
.controller('MainController', [ '$scope', function($scope) { 

    $scope.rows = []; 

    $scope.counter = 0; 

    $scope.addRow = function() { 

    $scope.row.push({ 
    firstName: $scope.firstName, 
    lastName: $scope.lastName 
}); 

    $scope.counter++; 

    } 
}]); 
</script> 

    </body> 
</html> 

回答

4

你所输入的输入值实际推入rows数组:

$scope.row.push({ 
    firstName: $scope.firstName, 
    lastName: $scope.lastName 
}); 

我会更新HTML阅读:

<a href="#" class="button" ng-click="addRow()">Add Row</a> 
First Name : <input ng-model="firstName" required> 
Last Name : <input ng-model="lastName" required> 

然后:

<tr ng-repeat="rowContent in rows"> 
    <td>{{rowContent.firstName}}</td> 
    <td>{{rowContent.lastName}}</td> 
</tr> 

确保角度包含正确,并且您的控制器也正确使用。

+0

是的,现在我包括角。但仍然没有工作。我从我身边检查。 – Idris

+0

@Idris您可以在上面添加更多代码吗? – Chewpers

+0

是的,我更新了代码 – Idris