我已经创建了一个加载模板的指令
app.directive('youtubeTrailer', function() {
return {
restrict: 'E',
scope: {
show: '=info'
},
link: function(scope, element, attrs) {
scope.hideModal = function() {
scope.show = false;
};
},
templateUrl: '../assets/angular-app/templates/_container-trailer.html',
};
});
这是ng-click操作,
%a{"ng-click" => "toggleModal()"}
Trailer {{$index+1}}
调用此函数,
$scope.modalShown = false;
$scope.toggleModal = function() {
$scope.modalShown = !$scope.modalShown;
};
然后显示指令,
%youtube-trailer{:info => "modalShown", :show => "modalShown"}
这很好用,但我的问题是模板显示在内联代码中。我想仅在单击toggleModal()
函数时检索它。
答案 0 :(得分:1)
angular.module('test', [])
.directive('customDirective', ['$http', '$templateCache', '$compile', function($http, $templateCache, $compile) {
function getTemplate() {
return '<div>Hello, {{ name }}!</div>';
};
return {
restrict: 'A',
link : function(scope, element, attrs, fn) {
// instead of that you need to load and cache real template via $http
var template = getTemplate();
scope.name = 'world';
element.replaceWith($compile(template)(scope));
}
};
}]);
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="test">
<div custom-directive></div>
</div>
&#13;
您只需要使用Angular $http
服务并在此事件处理程序中手动加载您的文件。
之后你需要编译它并插入你的指令元素:
element.replaceWith($compile(template)(scope));
您还可以使用{ cache: $templateCache }
设置$http
来加载一次加载模板。
示例:(内部指令)
// you need to have injected following dependencies here:
// $http, $compile, $templateCache
link: function(scope, element, attrs, fn) {
//...
scope.onSomeClick = function() {
$http.get(templateUrl, { cache: $templateCache })
.then(function(template) {
element.replaceWith($compile(template)(scope));
});
};
//...
}