Я пытаюсь добавить динамический шаблон и скомпилировать его в рамках директивы. Но когда я использую директиву для динамического добавления, она не отображает скомпилированную версию шаблона, который у меня есть. Что происходит не так. Это небольшая ошибка, которую я не могу поймать.Неправильно использовать директиву элемента
Вот plunker: http://plnkr.co/edit/0BalxNnQYVxEd3mAjexx
UPDATE: Изменения в директиву строки в оных функции()
<!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.addertmpl = "test1";
$scope.searchType=2;
$scope.counter = 1;
$scope.searchConditionsNumber = [ "equals","does not equal","is at least","is at most","is between","is in","is not in"];
$scope.searchConditionsString = ["equals","contain","does not equal","is in","is not in"];
$scope.searchOperator = ["AND","OR","BRACKET-OPEN","BRACKET-CLOSE"];
$scope.searchOpts = [{
editable:false,
group:"Project Info",
groupseditable:false,
header:"NEW-IN",
illegalValue:null,
name:"PR_NEW",
showing:true,
type:"String"
},{
editable:false,
group:"Project Info",
groupseditable:false,
header:"NEW-IN",
illegalValue:null,
name:"PR_NEW",
showing:true,
type:"String"
},{
editable:false,
group:"Project Info",
groupseditable:false,
header:"NEW-IN",
illegalValue:null,
name:"PR_NEW",
showing:true,
type:"String"
},{
editable:false,
group:"Project Info",
groupseditable:false,
header:"NEW-IN",
illegalValue:null,
name:"PR_NEW",
showing:true,
type:"String"
}];
$scope.add = function(){
var limit = 10;
if ($scope.counter == limit) {
alert("You have reached the limit of adding " + vc.counter + " inputs");
}
else {
var newdiv = document.createElement('div');
newdiv.id = "div-"+$scope.counter;
var elementToAdd = angular.element("<datan-type counter='{{counter}}' searchconditionsstring='searchConditionsString' searchconditionsnumber='searchConditionsNumber' searchoperator='searchOperator' searchtype='searchType' content='addertmpl' searchopts='searchOpts'></datan-type>");
$compile(elementToAdd[0])($scope);
newdiv.innerHTML = elementToAdd[0];
document.getElementById('dynamicInput').appendChild(newdiv);
console.log(elementToAdd);
alert(newdiv.innerHTML);
$scope.counter++;
}
};
});
app.directive('datanType', function ($compile) {
return {
restrict: 'E',
replace: true,
link: function (scope, ele, attrs) {
var testTemplate1 = "<span class='mdl-textfield mdl-js-textfield input-padding-left'>"+
"<select class='mdl-textfield__input mdl-select' id='f"+(attrs.counter)+"' name='f"+(attrs.counter)+"' type='select' ng-model='searchOpts.selectedSearch["+(attrs.counter)+"].f"+(attrs.counter)+"' ng-change='searchOptsOnSelect("+(attrs.counter)+")'>"+
"<option value='' selected>Criteria</option>"+
"<option ng-repeat='item in searchOpts track by $index' id='f"+(attrs.counter)+"-{{$index}}-{{item.type}}' value='{{item.name}}'>{{item.name}}</option>"+
"</select>"+
"<select class='mdl-textfield__input mdl-select' id='o0' name='o0' type='select' ng-if='searchType === 2' ng-model='searchOpts.selectedSearch[0].o0' ng-options='item for item in searchConditionsString'>"+
"<option value='' selected>Condition</option>"+
"</select>"+
"<select class='mdl-textfield__input mdl-select' id='o0' name='o0' type='select' ng-if='searchType === 3' ng-model='searchOpts.selectedSearch[0].o0' ng-options='item for item in searchConditionsNumber'>"+
"<option value='' selected>Condition</option>"+
"</select>"+
"<input class='mdl-textfield__input' id='v"+(attrs.counter)+"' name='v"+(attrs.counter)+"' type='text' ng-model='searchOpts.selectedSearch["+(attrs.counter)+"].v"+(attrs.counter)+"' placeholder='%Search Value'>"+
"<select class='mdl-textfield__input mdl-select' id='c"+(attrs.counter)+"' name='c"+(attrs.counter)+"' type='select' ng-model='searchOpts.selectedSearch["+(attrs.counter)+"].c"+(attrs.counter)+"' ng-options='item for item in searchOperator'>"+
"<option value=''>Operator</option>"+
"</select>"+
"<br><br>"+
"</span>"
var testTemplate2 = '<h1>Test2</h1>';
var testTemplate3 = '<h1>Test3</h1>';
var template = '';
switch(attrs.content){
case 'test1':
template = testTemplate1;
break;
case 'test2':
template = testTemplate2;
break;
case 'test3':
template = testTemplate3;
break;
}
ele.html(template);
alert(ele.html());
$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" counter="0"></datan-type>
<div id="dynamicInput" class="test"></div>
<button ng-click="add()">Add Form Elem Eg - Error Area</button>
</body>
</html>
Что вы на самом деле пытаетесь сделать здесь? не имеет смысла пытаться создавать угловые директивы в строках, а затем попытаться скомпилировать строку; директивы не могут быть связаны до тех пор, пока они не находятся в DOM, но к тому времени, когда компиляция добавляет их таким образом, их слишком поздно оценивать. Есть гораздо более простые способы динамического добавления контента в угловые. – Claies
Я нахожусь в проекте с прецедентом. – Gary
@ У вас есть альтернатива для той же логики? – Gary