[英]create HTML element dynamically
我對angular js非常陌生。 我想在單擊特定div時創建一個輸入框。 在這里,我需要在div上重復創建元素。
<div><div ng-repeat ng-click="create();"></div><div>
最好的方法是什么?
Angular中的DOM操作是通過指令完成的
(此處有關於“創建操縱DOM的指令”的段落)
首先,通讀這篇出色的文章: 如果我有jQuery背景,我如何在Angular中思考
Angular團隊還提供了一個非常簡潔的教程,絕對值得一看: http : //docs.angularjs.org/tutorial
當您將Angular圍繞在概念上時,Angular非常容易使用並且很有趣,但是陷入寒冷可能會讓人不知所措。 從慢開始,不要嘗試從一開始就使用每個功能。 經常閱讀。
我強烈推薦egghead.io作為學習資源。 那里的視頻教程很小,易於觀看和理解。 對於初學者和中級者都是一個好地方。 從底部開始。
有些人在Angular方面做得很棒。 查看http://builtwith.angularjs.org/並查看一些源代碼。
使用數組和ng-repeat來做到這一點。 看下面的代碼。 我將范圍變量創建為一個空數組。 然后創建一個函數以將值添加到該數組。
app.controller('MainCtrl', function($scope) {
$scope.inputFields = [];
$scope.count = 0;
$scope.addField = function(){
$scope.inputFields.push({name:"inputText"+$scope.count++});
}
});
我在這個數組上使用了ng-repeat。 並在div的click事件上調用了該函數。
<div ng-click="addField()">Click here to add</div>
<div ng-repeat="inputField in inputFields">
<input type="text" name="inputField.name">
</div>
檢查此工作鏈接
我如下創建addField()。
$scope.addField = function(){
$scope.newTextField = "<input type='text' name='myTxt'>";
}
為了在我的視圖文件中呈現此html,我創建了一個名為compile的新指令,如下所示。
app.directive('compile', function($compile) {
// directive factory creates a link function
return function(scope, element, attrs) {
scope.$watch(
function(scope) {
// watch the 'compile' expression for changes
return scope.$eval(attrs.compile);
},
function(value) {
// when the 'compile' expression changes
// assign it into the current DOM
element.html(value);
// compile the new DOM and link it to the current
// scope.
// NOTE: we only compile .childNodes so that
// we don't get into infinite loop compiling ourselves
$compile(element.contents())(scope);
}
);
};
});
然后在我的view.html文件中使用了此指令
<body ng-controller="MainCtrl">
<div ng-click="addField()">Click to Add</div>
<div compile="newTextField"></div>
</body>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.