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. Codeforces Round #324 (Div. 2) B

    B. Kolya and Tanya time limit per test 1 second memory limit per test 256 megabytes input standard i ...

  2. Java中同一个类中不同的synchronized方法是否可以并发执行?

    答案是: 不可以,因为都是获取到对象本身的锁. 多个线程访问同一个类的synchronized方法时, 都是串行执行的 ! 就算有多个cpu也不例外 ! synchronized方法使用了类java的 ...

  3. AtCoder Grand Contest 018 A

    A - Getting Difference Time limit時間制限 : 2sec / Memory limitメモリ制限 : 256MB 配点 : 300 点 問題文 箱に N 個のボールが入 ...

  4. table 实现 九宫格布局

    九宫格布局 最近遇到一个题目,是实现一个九宫格布局的.实现的效果大概是下图这种这样子的: (鼠标悬浮的时候,九宫格的边框颜色是改变的.) 首先想到的是直接使用<table>进行布局,原因很 ...

  5. JS操作checkBox

    代码如下: <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w ...

  6. 牧场行走(LCA)

    神奇传送门 好吧,这题很有意思.. 第一眼撇的时候还以为是(SPFA)呜.... 然后发现要Q次询问就想到了LCA 但是发现不是求LCA.. 于是想到了一个神奇的定律: 两点的LCA一定在u到v的最短 ...

  7. 使用matlab判断男声与女声

    (转自) http://wenku.baidu.com/view/1d55480fbe1e650e52ea99a3.html %filename:manwoman.m %different man f ...

  8. 在cocos2d中实现真正意思上的图片放大和缩小

    http://www.cnblogs.com/dinghing154/archive/2012/08/05/2623970.html 在编写程序的时候我们常常使用self.scale来让我们使用的图片 ...

  9. Scala学习随笔——控制语句

    Scala只内置了为数不多的几种程序控制语句:if.while.for.try catch以及函数调用,这是因为从Scala诞生开始就包含了函数字面量,Scala内核没有定义过多的控制结构,而是可以通 ...

  10. JS或jsp获取Session中保存的值

    JS是不能读取Session中的值的 . session是服务器对象, javascript是客户端脚本,你能做的操作就是把这个值用 <%=%>输出到页面的javascript中参与运算, ...