AngularJS指令包含文件内容

时间:2015-12-10 07:16:41

标签: javascript angularjs angularjs-directive

我正在尝试在AngularJS中为一个小的模板问题创建一个指令。在我的HTML文件中,我有这个:

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

我的指令应该将其转换为:

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

这是我到底有多远(但不是),但我想,我错过了一篇文章:

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

之前有没有人这样做过,并愿意分享?

2 个答案:

答案 0 :(得分:1)

<强> Here is the working plunker.

尝试这样的事情:

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>

答案 1 :(得分:0)

它的工作......

app.directive('productDescription',function(){
return {
restrict:'E',
templateUrl: 'product-description.html'
};
});