在ng上生成动态html点击 [英] generate dynamic html on ng click
问题描述
我想在ng-click上插入包含ng-bind和指令的动态html元素.我想在
I want to insert dynamic html element which contains ng-bind and directive on ng-click. I want to insert new html elements inside
HTML看起来像这样
Html looks like this
<body data-ng-controller="controller">
<div id="toolbox">
<label>Page Width</label>
<input type="text" data-ng-model="pageWidth" />
<input type="button" value="H1" data-ng-click="createH1()" />
</div>
<div id="editor">
<div data-ng-style="{width:pageWidth + 'px'}" data-ng-page>
</div>
</div>
</body>
控制器>
app.controller('controller', ['$scope', function ($scope) {
$scope.createH1 = function () {
document.getElementById("page").innerHTML = document.getElementById("page").innerHTML + ("<div class='h1' data-ng-h1 draggable></div>");
};
}]);
上面的控制器正在插入html元素,但是新的html元素的指令不起作用.
The above controller is inserting html element, but the directives of new html elements are not working.
但是我知道,除非我们$ compile template/html,否则它们将无法工作.
如果我使用app.directive(ngPage,..)添加我的动态html,则它会在应用启动时插入.但是我只想在按钮ng-click上插入.
However I came to know that unless we $compile template/html they'll not work.
If I use app.directive( ngPage, ..) to add my dynamic html, it is inserting while app is started. But I want to insert only on button ng-click.
我是angular js的新手,有些困惑,请帮帮我. 预先感谢.
I'm new to angular js, a bit confused please help me out with this. Thanks in advance.
推荐答案
我将始终喜欢通过指令进行DOM操作.因此,这里的代码如下所示
I will Always prefer to do DOM manipulation from directive. So here code will look like below
HTML
<body ng-controller="MainCtrl as vm">
<button add-html>click me</button>
<div id="page">
This will be replaced by text
</div>
</body>
代码
app.directive('addHtml', function($compile){
return {
restrict: 'AE',
link: function(scope, element, attrs){
var html = `<div class='h1' data-ng-h1 draggable>Test</div>`,
compiledElement = $compile(html)(scope);
element.on('click', function(event){
var pageElement = angular.element(document.getElementById("page"));
pageElement.empty()
pageElement.append(compiledElement);
})
}
}
});
Plunkr 此处
这篇关于在ng上生成动态html点击的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!