好好爱自己!

How to dynamically load directive into page

https://stackoverflow.com/questions/23556398/how-to-dynamically-load-directive-into-page

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:

app.controller('TestController', function TestController($http, $scope, $compile) {

$scope.loadData = function (pageId) {
    var pUrl = <some url>
    $http({
        method: 'GET',
        url: pUrl
    }).success(function (data, status) {
        $scope.pData = data;
        var htm = '<test-directive></test-directive>';
        var elm = angular.element("#id").append(htm);
        $compile(elm)($scope);
    }).error(function (data, status) {
        alert('error');
    });
};

$scope.loadData();

});

Directive:

'use strict';

app.directive('testdirective', function ($http) {
var uDirective = {};

uDirective.restrict = 'E';
uDirective.templateUrl = 'js/directives/testdirective.html';
uDirective.controller = function ($scope, $element, $attrs) {
$scope.showDirectiveData();

    $scope.showDirectiveData = function () {
        $scope.directiveDataCollection = <get data>;
    };
};

uDirective.compile = function (element, attributes) {
    // do one-time configuration of element.

    var linkFunction = function ($scope, element, atttributes) {
    };

    return linkFunction;
};

return uDirective;
});

Template used in Directive

<div>
   <div ng-repeat="directiveData in directiveDataCollection">
      <span><h4>{{directiveData.Title}}</h4></span>
   </div>
</div>

How do i get to compile the code in the TestController, load the directive dynamically, and finally load the content and append the content in scope?

--------------------------------------------------------------------------------------------------------------------------------------------------

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

 
posted @   立志做一个好的程序员  阅读(327)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 25岁的心里话
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现
历史上的今天:
2017-05-18 angularJS 系列(七)
2016-05-18 php 缓存之 APC 和apcu
2016-05-18 用c++写一个 “hello,world” 的 FastCGI程序

不断学习创作,与自己快乐相处

点击右上角即可分享
微信分享提示