Angular JS : Insert one directive into another directive dynamically

跟風遠走 提交于 2019-12-06 11:45:45

You can use the $compile service in Angular, make sure you include it in the dependency injection.

app.directive("firstDirective", ['$compile', function($compile) {
...
controller: function ($scope) {
    $scope.firstCtrl = function() {
         var ele = $compile('<second-directive></second-directive>')($scope);
         angular.element(document.querySelector('#insertSecond')).append(ele);                  
    } 
}

There is one more problem instead of templateUrl, template should be there

    <!DOCTYPE html>
     <html>
        <script data-require="angular.js@1.0.x" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.8/angular.min.js" data-semver="1.0.8"></script>

         <first-directive></first-directive>

     <script>
      var app = angular.module("myApp", []);
          app.directive("firstDirective", function($compile) {
              return {
              template : '<h1>This is first directive!</h1> <br / ><br / ><button type="button" ng-click="firstCtrl()">Click Me to second directive!</button> <div id="insertSecond"></div> ',
              controller: function ($scope) {
              $scope.firstCtrl = function() {
                var ele = $compile('<second-directive></second-directive>')($scope);
                angular.element(document.querySelector('#insertSecond')).append(ele);
             }
         },
          restrict: "EAC"

   }

});

          app.directive("secondDirective", function() {
             return {
             template : '<h1>This is second directive!</h1> <br / ><br / >',
             controller: function ($scope) {

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