How to dynamically load directive into page

后端 未结 1 1642
我寻月下人不归
我寻月下人不归 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 = '';
            var compiled = $compile(htm)(scope);
            elem.append(compiled);
          });
        }
      }
    })
    .directive('childDirective', function(){
      return {
        restrict: 'E',
        template: '
    Content: {{data.key}}
    ' } }) .factory('Resource', function($http){ var Resource = {}; Resource.loadData = function(){ return $http.get('test.json'); } return Resource; })

    HTML

    
      
    
    

    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)
提交回复
热议问题