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. BZOJ2535 [Noi2010]Plane 航空管制 【贪心 + 堆】

    题目链接 BZOJ2535 题解 航班之间的关系形成了一个拓扑图 而且航班若要合法,应尽量早出发 所以我们逆拓扑序选点,能在后面出发的尽量后面出发,不会使其它点变得更劣,容易知是正确的 第二问只需枚举 ...

  2. BZOJ2599 [IOI2011]Race 【点分治】

    题目 给一棵树,每条边有权.求一条简单路径,权值和等于K,且边的数量最小.N <= 200000, K <= 1000000 输入格式 第一行 两个整数 n, k 第二..n行 每行三个整 ...

  3. 「JOISC 2015 Day 1」卡片占卜

    题目描述 K 理事长是占卜好手,他精通各种形式的占卜.今天,他要用正面写着 I ,背面写着 O 的卡片占卜一下日本 IOI 国家队的选手选择情况. 占卜的方法如下: 首先,选取五个正整数 A,B,C, ...

  4. Codeforces Round #324 (Div. 2) A

    A. Olesya and Rodion time limit per test 1 second memory limit per test 256 megabytes input standard ...

  5. CodeForces 659D Bicycle Race (判断点是否为危险点)

    D - Bicycle Race Time Limit:1000MS     Memory Limit:262144KB     64bit IO Format:%I64d & %I64u S ...

  6. Application binary interface and method of interfacing binary application program to digital computer

    An application binary interface includes linkage structures for interfacing a binary application pro ...

  7. Webpack & The Hot Module Replacement热模块替换原理解析

    Webpack & The Hot Module Replacement热模块替换原理解析 The Hot Module Replacement(HMR)俗称热模块替换.主要用来当代码产生变化 ...

  8. VS2005重置所有设置

    1. 关闭VS 2. 在命令行运行microsoft visual studio 8\common7\ide\devenv.exe /setup /resetuserdata /resetsettin ...

  9. cpp调用dll

    c++ 显示调用 其他程序dll #pragma comment(lib, "DllTest.lib") int fnDllTest(void); int c = fnDllTes ...

  10. AC日记——[WC2013]糖果公园 cogs 1817

    [WC2013]糖果公园 思路: 带修改树上莫队(模板): 来,上代码: #include <cmath> #include <cstdio> #include <cst ...