我正在尝试在 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
};
}
};
});
有没有人做过这样的事情,愿意分享一下?
最佳答案
尝试这样的事情:
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/