我是angularJs的新手。有人能指出我从angularJs到html动态显示链接的简单方法。
我想要显示" n"动态html中的(n> = 0)个按钮,我得到的值是' n'来自db。假设如果n是5,当我加载html页面时应该显示5个按钮,而且我想知道用户点击了哪个按钮。
任何指针都会非常有用。
答案 0 :(得分:0)
视图:
<button ng-repeat="n in getNumber(number) track by $index"
ng-click="pressed(n)">
This button repeats n times
</button>
控制器
$scope.number = 5; // MyService.getN();
// ng-repeat only accepts collection as parameter
$scope.getNumber = function (num) {
return new Array(num);
}
$scope.pressed = function(num) {
alert("Pressed button " + num);
}
示例:jsfiddle
答案 1 :(得分:0)
你可以通过使用&#34; ng-repeat&#34;来实现这一点。指令。
尝试以下代码:
HTML:
<div ng-app="app">
<div ng-controller="AppCtrl">
<button ng-repeat="n in getArray(number)" id="button-{{$index}}" ng-click="getButtonClicked($index)" >This button repeats times</button>
</div>
脚本:
var myApp = angular.module('app',[]);
myApp.controller('AppCtrl' , function($scope){
$scope.number = 5;
$scope.getArray = function(num){
var array = [];
for(var i = 0 ; i < num;i++){
array[i] = i +1;
}
return array;
}
$scope.getButtonClicked = function(buttonNumber){
alert(buttonNumber + 1 + " is clicked");
}
});
答案 2 :(得分:0)
devqon的答案是完全正确的,但如果您使用的是Angular 1.3,最好不要使用$ scope,而是使用'Controller as vm'语法。基本上代码与上面的答案完全相同,但只是根据最佳实践编写。
app.controller('MainCtrl', function() {
var amountOfButtons = 5;
this.buttons= new Array(amountOfButtons);
this.handleButtonClick = handleButtonClick;
function handleButtonClick(index){
console.log('Clicked: ' + index);
}
});
<body ng-controller="MainCtrl as vm">
<button ng-repeat="button in vm.buttons track by $index" ng-click='vm.handleButtonClick($index)'>button {{::$index}}</button>
</body>
答案 3 :(得分:0)
在你的代码中使用ng-repeat,这是最好也是最简单的方法..只是寻找我的小提琴示例..更容易.. 你将如下..
<div ng-controller="MyCtrl">
<button ng-repeat="button in buttons(number) track by $index" ng-click="click($index+1)">Button</button>
</div>
你的角度脚本很简单如下..
var myApp = angular.module('myApp', []);
myApp.controller("MyCtrl", function ($scope) {
$scope.number = 5;//predefined amount of buttons
// ng-repeat only accepts collection as parameter
$scope.buttons = function (noOfButtons) {
return new Array(noOfButtons);
}
//this will trigger when clicked a button
$scope.click = function(buttonNo) {
alert("Clicked button " + buttonNo);
//button number is tracked by $index
}
});