如何在单击按钮时动态添加指令
How to dynamically add directives on button-click
我已经看过 post 同一主题的这篇文章:
Dynamically add directive in AngularJS
但我对 angular 不够熟悉,无法在我的案例中使用此解决方案。
在我的例子中,我试图在单击按钮后将指令(基于外部 html)动态添加到 div:
<div class="charges" id="charges">
<my-headcharges></my-headCharges>
<my-charges></my-charges>
</div>
Nou 可以看到我的 div 有两个我创建并放置在 div 硬编码下的指令。现在我想添加相同的指令,但要添加很多次,并且是在单击按钮之后。
谢谢:)
您可以使用ng-repeat
var myApp = angular.module("myApp", []);
myApp.controller("myController", ["$scope",
function($scope) {
$scope.items = []
$scope.addTimes = function() {
$scope.items.push({
name : new Array(7).join().split(',').map(function(it){return String.fromCharCode(Math.floor(Math.random() * (122 - 97 + 1)) + 97)}).join("")
});
};
}
]);
<html ng-app="myApp">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
</head>
<body ng-controller="myController">
<button ng-click="addTimes()">Add</button>
<div class="charges" ng-repeat="item in items">
<my-headcharges>Hello {{item.name}}</my-headCharges>
<my-charges></my-charges>
</div>
</body>
</html>
我已经看过 post 同一主题的这篇文章: Dynamically add directive in AngularJS
但我对 angular 不够熟悉,无法在我的案例中使用此解决方案。
在我的例子中,我试图在单击按钮后将指令(基于外部 html)动态添加到 div:
<div class="charges" id="charges">
<my-headcharges></my-headCharges>
<my-charges></my-charges>
</div>
Nou 可以看到我的 div 有两个我创建并放置在 div 硬编码下的指令。现在我想添加相同的指令,但要添加很多次,并且是在单击按钮之后。
谢谢:)
您可以使用ng-repeat
var myApp = angular.module("myApp", []);
myApp.controller("myController", ["$scope",
function($scope) {
$scope.items = []
$scope.addTimes = function() {
$scope.items.push({
name : new Array(7).join().split(',').map(function(it){return String.fromCharCode(Math.floor(Math.random() * (122 - 97 + 1)) + 97)}).join("")
});
};
}
]);
<html ng-app="myApp">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
</head>
<body ng-controller="myController">
<button ng-click="addTimes()">Add</button>
<div class="charges" ng-repeat="item in items">
<my-headcharges>Hello {{item.name}}</my-headCharges>
<my-charges></my-charges>
</div>
</body>
</html>