Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to dynamically load directive into page

Tags:

angularjs

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?

like image 373
Immortal Avatar asked May 09 '14 04:05

Immortal


People also ask

How to dynamically load HTML content into a web page?

Three Ways to Dynamically Load HTML Content into a Web Page 1 Introduction. The three methods presented in this article for replacing HTML content dynamically (in response to user actions) all work fine; I will demonstrate all three and you can choose ... 2 Background. ... 3 Using the code. ... 4 Points of Interest. ... 5 History. ...

How to dynamically manipulate HTML content with JavaScript?

There are a number of ways to dynamically manipulate HTML contents with Javascript: Directly change the contents with innerHTML and outerHTML. Create new HTML elements and insert them. Load and insert HTML contents with AJAX.

What is a dynamic HTML page?

Let us first know what actually is a dynamic HTML page. Dynamic HTML page, as the name suggests refers to an HTML page that is dynamic in such a way that it is customizable and changeable according to user input. For example:- Using CSS we can change the background color of the web page each time the user clicks a button on the webpage.

What is the active tab in a directive?

(Office,Customer,Employee) The directive decorator’s configuration property specifies the directive’s CSS attribute selector, [active-tab]. It’s the brackets ( []) that make it an attribute selector.


1 Answers

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

like image 57
Marc Kline Avatar answered Sep 22 '22 19:09

Marc Kline