使用ng-repeat创建动态列和行

时间:2017-04-24 05:33:55

标签: javascript html angularjs

我正在使用angularjs,我想用ng-repeat创建动态行但无法实现。看完我的代码后我会清楚。这是我的代码和jsfiddle: -

td.controllers.js

function TodoCtrl($scope) {
 $scope.products = [{
            name: 'Abc'
        }, {
            name: 'Bil'
        }, {
            name: 'Smart'
        }];
}

td.html

<div ng-app>
  <div ng-controller="TodoCtrl">
   <table class="table">
    <thead>
                            <tr>
                                <th rowspan="2">Month</th>
                                <th ng-repeat="product in products" colspan="2">{{product.name}}</th>
                            </tr>
                            <tr>
                                <th>A</th> //I want to dynamic it
                                <th>B</th> //
                            </tr>
                        </thead>
   </table>

  </div>
</div>

我的愿望输出是: -

-----------------------------
Month | Abc | Bil | Smart
      | A|B | A|B | A|B
----------------------------

2 个答案:

答案 0 :(得分:1)

<div ng-app>
  <div ng-controller="TodoCtrl">
   <table class="table">
    <thead>
                            <tr>
                                <th rowspan="2">Month</th>
                                <th ng-repeat="product in products">{{product.name}}</th>
                            </tr>
                            <tr>
                                <th></th> <!--I want to dynamic it-->
                                <th ng-repeat="product in products">A|B</th> 
                            </tr>
                        </thead>
   </table>

  </div>
</div>

试试这段代码 这里的表头是动态创建的,也是表数据。

如果你有任何问题,请告诉我

答案 1 :(得分:1)

试试这个

<html>
<head>
<script Src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.1/angular.js"></script>

<script>
	var app=angular.module("myapp", []);
	app.controller("namesctrl", function($scope){

		$scope.products = [{
        name: 'Abc'
    }, {
        name: 'Bil'
    }, {
        name: 'Smart'
    }];

	});

	
</script>
</head>
<body ng-app="myapp" ng-controller="namesctrl">
  <div>
   <table class="table">
    <thead>
    <tr>
        <th rowspan="2">Month</th>
        <th ng-repeat="product in products">{{product.name}}</th>
    </tr>
    <tr>
        <th></th>
        <th ng-repeat="product in products">A|B</th> 
    </tr>
    </thead>
   </table>

  </div>
</body>
</html>