Marco Marco - 6 months ago 38
AngularJS Question

AngularJS Directive to include file content

I´m trying to create a directive in AngularJS for a small templating issue. In my HTML-File I have this:

<div myinclude="header.tpl.html"></div>


My directive should transform this to that:

<div>{content of file: header.tpl.html}</div>


This is how far (or not) I´ve come, but I guess, I´m missing a piece:

myApp.directive('myinclude', function () {
return {
compile: function compile( tElement, tAttributes ) {
console.log(tAttributes.myinclude); // logs filename
return {
templateURL: tAttributes.myinclude
};
}
};
});


Has anyone done something like this before, and is willing to share?

Answer

Here is the working plunker.

Try something like this:

var app = angular.module('plunker', []);

app.controller('MainCtrl', function($scope) {
  $scope.name = 'World';
    $scope.setValue = function(ele) {
     console.log(ele)
    };
});

app.directive("myInclude",function(){
 return {
     restrict : 'A',
      link : function(scope, element, attrs){
          scope.getContentUrl = attrs["myInclude"];
      },
      template: "content of file : {{getContentUrl}}"
    }
});

HTML

<!DOCTYPE html>
<html ng-app="plunker">

  <head>
    <meta charset="utf-8" />
    <title>AngularJS Plunker</title>
    <script>document.write('<base href="' + document.location + '" />');</script>
    <link rel="stylesheet" href="style.css" />
    <script data-require="angular.js@1.4.x" src="https://code.angularjs.org/1.4.8/angular.js" data-semver="1.4.8"></script>
    <script src="app.js"></script>
  </head>

  <body ng-controller="MainCtrl">
    <p>Hello {{name}}!</p>

 <div my-include="header.tpl.html"></div>
  </body>

</html>
Comments