Unable to use element directive correctly

放肆的年华 提交于 2020-03-04 07:00:24

问题


I am trying to add a dynamic template and compile it within a directive. But when I use the directive to add dynamically it does not show the compiled version of the template I have. What is going wrong. It is a small error which I am unable to catch.

Here is the plunker: http://plnkr.co/edit/0BalxNnQYVxEd3mAjexx

UPDATE: Changes in the directive string in add() function

<!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>

回答1:


Give restriction to both Element (E) and Attribute (A)

$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("<tmpl-adder  counter='{{counter}}' searchconditionsstring='searchConditionsString' searchconditionsnumber='searchConditionsNumber' searchoperator='searchOperator' searchtype='searchType' content='addertmpl' searchopts='searchOpts'></tmpl-adder>");
            $compile(elementToAdd[0])($scope);
            newdiv.innerHTML = elementToAdd[0].outerHTML;
            console.log("elementToAdd[0]", elementToAdd)
            document.getElementById('dynamicInput').appendChild(newdiv);
            alert(newdiv.innerHTML);
            $scope.counter++;
        }
    };


app.directive('datanType', function ($compile) {
  return { 
    restrict: 'EA',
    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);  
      
    }
  };
});
<div datan-type content="test1" counter="0"></div>

This is working fine on my plunkr



来源:https://stackoverflow.com/questions/38713555/unable-to-use-element-directive-correctly

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!