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:

  1. app.controller('TestController', function TestController($http, $scope, $compile) {
  2. $scope.loadData = function (pageId) {
  3. var pUrl = <some url>
  4. $http({
  5. method: 'GET',
  6. url: pUrl
  7. }).success(function (data, status) {
  8. $scope.pData = data;
  9. var htm = '<test-directive></test-directive>';
  10. var elm = angular.element("#id").append(htm);
  11. $compile(elm)($scope);
  12. }).error(function (data, status) {
  13. alert('error');
  14. });
  15. };
  16. $scope.loadData();
  17. });

Directive:

  1. 'use strict';
  2. app.directive('testdirective', function ($http) {
  3. var uDirective = {};
  4. uDirective.restrict = 'E';
  5. uDirective.templateUrl = 'js/directives/testdirective.html';
  6. uDirective.controller = function ($scope, $element, $attrs) {
  7. $scope.showDirectiveData();
  8. $scope.showDirectiveData = function () {
  9. $scope.directiveDataCollection = <get data>;
  10. };
  11. };
  12. uDirective.compile = function (element, attributes) {
  13. // do one-time configuration of element.
  14. var linkFunction = function ($scope, element, atttributes) {
  15. };
  16. return linkFunction;
  17. };
  18. return uDirective;
  19. });

Template used in Directive

  1. <div>
  2. <div ng-repeat="directiveData in directiveDataCollection">
  3. <span><h4>{{directiveData.Title}}</h4></span>
  4. </div>
  5. </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

  1. .directive('parentDirective', function(Resource, $compile){
  2. return {
  3. restrict: 'E',
  4. link: function(scope, elem, attrs){
  5. Resource.loadData().then(function(result){
  6. scope.data = result.data;
  7. var htm = '<child-directive></child-directive>';
  8. var compiled = $compile(htm)(scope);
  9. elem.append(compiled);
  10. });
  11. }
  12. }
  13. })
  14. .directive('childDirective', function(){
  15. return {
  16. restrict: 'E',
  17. template: '<div>Content: {{data.key}}</div>'
  18. }
  19. })
  20. .factory('Resource', function($http){
  21. var Resource = {};
  22. Resource.loadData = function(){
  23. return $http.get('test.json');
  24. }
  25. return Resource;
  26. })

HTML

  1. <body ng-app="myApp">
  2. <parent-directive></parent-directive>
  3. </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. 洛谷 P3765 总统选举 解题报告

    P3765 总统选举 题目背景 黑恶势力的反攻计划被小C成功摧毁,黑恶势力只好投降.秋之国的人民解放了,举国欢庆.此时,原秋之国总统因没能守护好国土,申请辞职,并请秋之国人民的大救星小C钦定下一任.作 ...

  2. spring in action学习笔记十六:配置数据源的几种方式

    第一种方式:JNDI的方式. 用xml配置的方式的代码如下: 1 <jee:jndi-lookup jndi-name="/jdbc/spittrDS" resource-r ...

  3. vue组件中使用iframe元素

    需要在本页面中展示vue组件中的超链接,地址栏不改变的方法: <template> <div class="accept-container"> <d ...

  4. poj 3729 Facer’s string

    Facer’s string Time Limit: 3000MS   Memory Limit: 65536K Total Submissions: 2155   Accepted: 644 Des ...

  5. .net yield return

    yield在迭代器块中用于向枚举数对象提供值或发出迭代结束信号.它的形式为下列之一: yield return <expression>; yield break; 计算表达式并以枚举数对 ...

  6. 【linux高级程序设计】(第九章)进程间通信-管道 3

    有名管道 无名管道和有名管道: 1. 管道是特殊类型的文件,在满足先入先出的原则写可以读写,不能定位读写位置. 2.管道是单向的. 3.无名管道阻塞于读写位置,而有名管道阻塞在创建位置. 4.无名管道 ...

  7. myeclipse10.7配置resin4.0.36

    Resin-4.0.35 (built Tue, 12 Feb 2013 10:05:50 PST) Copyright(c) 1998-2012 Caucho Technology.  All ri ...

  8. 陕西师范大学第七届程序设计竞赛网络同步赛 F WWX的礼物【数学/k进制下x^n的位数/log】

    链接:https://www.nowcoder.com/acm/contest/121/F来源:牛客网 题目描述 WWX的女朋友送给了他一个礼物,可是礼物却被一把K进制密码锁锁住了.在礼物盒上还有一张 ...

  9. ZOJ 3937 More Health Points (2016 浙江省赛 B题,可持久维护凸壳)

    题目链接  2016 ZJCPC Problem B 题意  CF 660F的树上版本. 其他做的方法都差不多,关键是把凸壳放到树上. 每次确定扔掉几个元素的时候直接$O(1)$修改(先不清楚这个位置 ...

  10. Python的程序结构[4] -> 函数/Function[0] -> 函数与方法的区别

    函数与方法的区别 / Distinction of Function and Method 关于函数与方法的区别,可根据两者的定义看出, 函数function -- A series of state ...