繁体   English   中英

如何在单击按钮时在angular .js中动态添加行?

[英]how to add row dynamically in angular .js on button click?

当我获取静态数据时,我可以在angular.js中创建一个列表视图,我能够在给定的小提琴中创建list.as。 http://jsfiddle.net/65Cxv/50/。但是换句话说,我需要动态生成行,我需要在用户单击按钮时创建行。我需要创建具有相同文本示例(“列表”)但ID不同的列表像(“ 0”,“ 1”,“ 2” ...等)。是否可以生成列表..?我在这里尝试做..

<!DOCTYPE html>
<html ng-app="myApp">
<head>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.14/angular.min.js"></script>
<script src="//code.jquery.com/jquery.min.js"></script>
<link href="//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/css/bootstrap-combined.min.css" rel="stylesheet" type="text/css" />
<script src="//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/js/bootstrap.min.js"></script>

  <meta charset="utf-8">
  <title>JS Bin</title>
</head>
<body>
<button type="button" class="btn btn-primary">Primary</button>
<ul ng-controller="ListController">
    <li>
        <a ng-click=></a>
    </li>
</ul>



</body>

</html>

JS代码:

var myApp = angular.module('myApp',[]);

myApp.controller('ListController', function($scope) {
  alert('--')
]);

您可以通过将新对象推送到数据数组中来添加数据模型:

$scope.items = [
    {name: 'item1', content: 'content1'},
    {name: 'item2', content: 'content2'},
    {name: 'item3', content: 'content3'}
];
/* bind this to `ng-model` of 2 inputs in html*/
$scope.activeItem={ name: '', content:''}

$scope.addItem=function(){
   $scope.items.push( $scope.activeItem);
   $scope.activeItem={} /* reset active item*/

}

在html中使用

<button ng-click="addItem()">Add</button>

DEMO

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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