javascript - 用于包含文件内容的 AngularJS 指令

标签 javascript angularjs angularjs-directive

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

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

我的指令应该将这个转换成那个:

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

这是我已经(或没有)多远,但我想,我错过了一 block :

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

有没有人做过这样的事情,愿意分享一下?

最佳答案

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>

关于javascript - 用于包含文件内容的 AngularJS 指令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34195825/

相关文章:

javascript - 何时在无限滚动上获取更多内容?

javascript - 如何在 Protractor 测试中访问 Angular 对象

javascript - 在 angularjs 中预取模板有什么好处吗?

angularjs - 有条件选择指令

javascript - 防止复选框输入条件上的无限循环

javascript - 形式中的受控组件

javascript - AngularJS 树指令和单击事件的 JIT 编译

javascript - 隔离作用域无法访问作用域链中更高层的变量

javascript - HTML5 Canvas 油漆重画lineJoin不圆 Angular

javascript - 如何在 JavaScript (AngularJS) 中使用 JodaTime