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

answered May 9 '14 at 4:43
Marc Kline

8,6582534
 

How to dynamically load directive into page的更多相关文章

  1. Page事件执行顺序

    Page 执行中将按照如下顺序激活事件: Page.PreInit Page.Init Page.InitComplite Page.PreLoad Page.Load Page.LoadComple ...

  2. ASP.NET Page执行顺序【转】

    一.ASP.NET 母版页和内容页中的事件 母版页和内容页都可以包含控件的事件处理程序.对于控件而言,事件是在本地处理的,即内容页中的控件在内容页中引发事件,母版页中的控件在母版页中引发事件.控件事件 ...

  3. iphone dev 入门实例6:How To Use UIScrollView to Scroll and Zoom and Page

    http://www.raywenderlich.com/10518/how-to-use-uiscrollview-to-scroll-and-zoom-content Getting Starte ...

  4. Dynamically loading an external JavaScript or CSS file

    原文:   Dynamically loading an external JavaScript or CSS file 通过javascript动态加载css文件和javascript文件,主要是通 ...

  5. selenium page object model

    Page Object Model (POM) & Page Factory in Selenium: Ultimate Guide 来源:http://www.guru99.com/page ...

  6. TWebBrowser: Determine when a page with Frames is completed

    TWebBrowser: Determine when a page with Frames is completed 6 comments. Current rating: (3 votes). L ...

  7. Dynamically loading unmanaged OCX in C#

    You'll have to perform a number of steps that are normally taken of automatically when you use the t ...

  8. angular directive 深入理解

    由于业务的需要,最近angular 的diretive 研究的比较多,有和同事一起共同协作开发scada的项目, 对directive 有了进一步更深的理解. 感觉才开始真正理解了这句话的意思: In ...

  9. Selenium - WebDriver: Page Objects

    This chapter is a tutorial introduction to page objects design pattern. A page object represents an ...

随机推荐

  1. bzoj 3379 - [USACO2004] 交作业

    Description 一个数轴上有 \(n \le 1000\) 个位置, 每个位置有一个时间 \(t_i\) 要求在 时刻 \(t_i\) 后, 至少经过该位置一次. (去交作业) 求从 \(0\ ...

  2. python模块导入

    官方手册:https://docs.python.org/3/tutorial/modules.html 可执行文件和模块 python源代码文件按照功能可以分为两种类型: 用于执行的可执行程序文件 ...

  3. 汕头市队赛SRM15

    T1——czl SRM 15 众所周知,czl家养了一只可♂爱的***(已屏蔽),那只东西很贪吃,所以czl家很多零食仓库,然而这些仓库里有很多老鼠. 为了心爱的***,czl决定点燃纯艾条,用烟熏老 ...

  4. [ CodeVS冲杯之路 ] P1011

    不充钱,你怎么AC? 题目:http://codevs.cn/problem/1011/ 一开始以为是道数学题,列出了一个公式 后面验证,发现只能推出第一次,后面的还需要迭代,推翻这个公式 又去瞟了一 ...

  5. [ZJOI2008]树的统计——树链剖分

    本题是一个树链剖分裸题,由于比较菜,老是RE,后来发现是因为使用了全局变量. /************************************************************ ...

  6. vue-cli打包后图片路径取不到的问题

    今天准备把vue-cli build 的文件发到服务器上单发现会出现图片找不到的问题 解决办法如下 修改 assetsPublicPath: './' .打开webpack.prod.conf.js, ...

  7. UVA 10801 Lift Hopping 最短路

    2种方式直接代码就可以了.注意首次不需要60S的转换 #include <map> #include <set> #include <list> #include ...

  8. ubuntu14.04LTS openssh-server 手动安装配置步骤

    先用能上网的机器下载:zlib-1.2.5.tar.bz2.openssh-5.6p1.tar.gz.openssl-0.9.8o.tar.tar,接下来,准备安装. 步骤如下: 1.首先解压安装zl ...

  9. hdu 5086(递推)

    Revenge of Segment Tree Time Limit: 4000/2000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/ ...

  10. Kerberos(转:http://www.cnblogs.com/jankie/archive/2011/08/22/2149285.html)

    Kerberos介绍(全)   微软Windows Server 2003操作系统实现Kerberos 版本5的身份认证协议.Windows Server 2003同时也实现了公钥身份认证的扩展.Ke ...