How to dynamically load directive into page

后端 未结 1 1640
我寻月下人不归
我寻月下人不归 2020-12-29 10:43

I have an html file with a controller and a directive with a template url. I want to load/compile the directive conditionally in the controller:

Controller:

<
相关标签:
1条回答
  • 2020-12-29 11:11

    Here is a general template for you to reference that abstracts and also demonstrates a few Angular concepts:

    JS

    .directive('parentDirective', function(Resource, $compile){
      return {
        restrict: 'E',
        link: function(scope, elem, attrs){
          Resource.loadData().then(function(result){
            scope.data = result.data;
            var htm = '<child-directive></child-directive>';
            var compiled = $compile(htm)(scope);
            elem.append(compiled);
          });
        }
      }
    })
    .directive('childDirective', function(){
      return {
        restrict: 'E',
        template: '<div>Content: {{data.key}}</div>'
      }
    })
    .factory('Resource', function($http){
      var Resource = {};
    
      Resource.loadData = function(){
        return $http.get('test.json');
      }
    
      return Resource;
    })
    

    HTML

    <body ng-app="myApp">
      <parent-directive></parent-directive>
    </body>
    

    Notice that there is no controller code. This is because controllers should never manipulate the DOM - one reason is that it will make your code a PITA to test. So, I put everything in directives, where it should probably be in your case as well.

    I also moved the $http service into a factory. Anything state/model related should be in a service. Among other reasons, by doing this, you can inject it almost anywhere (including inside of directives) to access your data without worrying about it disappearing when a controller unloads.

    EDIT

    You should also consider the dissenting view of the dynamic loading approach in general in the accepted answer of Dynamically adding Angular directives

    0 讨论(0)
提交回复
热议问题