gpt4 book ai didi

javascript - 无法将动态添加的指令编译到页面中

转载 作者:行者123 更新时间:2023-11-29 19:11:18 25 4
gpt4 key购买 nike

我正在尝试将动态添加的元素指令添加到页面中,但它不起作用并且在添加它的页面中被编译。这是plunker代码。代码有什么问题?

http://plnkr.co/edit/BFPxAvEahT1I930mvB5r

<!DOCTYPE html>
<html ng-app="myApp">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.14/angular.min.js"></script>
<script>
var app = angular.module('myApp', []);
app.controller("fCtrl",function($scope,$compile){
$scope.xx = ['x','c','y','z','a'];
$scope.add = function(){
var templ = document.getElementById('test').innerHTML;
templ = templ+'<datan-type content="test1" con="{{xx}}"></datan-type>';
document.getElementById('test').innerHTML = templ;
//$compile(document.getElementById('test').innerHTML)($scope);
alert(document.getElementById('test').innerHTML);
}
});

app.directive('datanType', function ($compile) {
return {
restrict: 'E',
replace: true,
link: function (scope, ele, attrs) {
var testTemplate1 = '<h1 ng-repeat="x in arr">Test{{x}}</h1>';
var testTemplate2 = '<h1>Test2</h1>';
var testTemplate3 = '<h1>Test3</h1>';
var template = '';
scope.arr = eval(attrs.con);
switch(attrs.content){
case 'test1':
template = testTemplate1;
break;
case 'test2':
template = testTemplate2;
break;
case 'test3':
template = testTemplate3;
break;
}

ele.html(template);
$compile(ele.contents())(scope);

}
};
});



</script>
<meta charset="utf-8">
<title>JS Bin</title>
</head>
<body ng-controller="fCtrl">
<p>Result:</p>
<datan-type content="test1" con="{{xx}}"></datan-type>
<div id="test"></div>
<button ng-click="add()">Add Form Elem Eg - Error Area</button>
</body>
</html>

最佳答案

Gary,这让我很难受,所以我把找出愚蠢的语法作为我早上的目标:

Working Plnkr - Clicky

将您的 Controller 代码更改为:

var elementToAdd = angular.element('<datan-type content="test1" con="{{xx}}"></datan-type>');
$compile(elementToAdd)($scope);
document.getElementById('test').appendChild(elementToAdd[0]);

enter image description here

关于javascript - 无法将动态添加的指令编译到页面中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38660523/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com