javascript 在 templateUrl 覆盖之前检索 AngularJS 指令的内部 HTML
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20110927/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Retrieve inner HTML of AngularJS directive before templateUrl overrides it
提问by francisco.preller
I have a directive I use for form validation boilerplate which I recently refactored. Allow me to explain the directive a little further before expanding.
我有一个用于表单验证样板的指令,我最近对其进行了重构。在展开之前,请允许我进一步解释该指令。
The directive usage:
指令用法:
<form class="form-horizontal" name="personalDetails" validated-form>
<!-- Pass buttons into form through here -->
<a href="" class="btn btn-success"
data-ng-click="saveDetails()"
data-ng-disabled="!personalDetails.$valid">Save Changes</a>
</form>
Previously, my directive looked something like this, and it worked.
以前,我的指令看起来像这样,并且有效。
app.directive('validatedForm', function($compile, $sce) {
return {
restrict: 'A',
scope: true,
link: function(scope, element, attrs) {
var template = //... HTML boilerplate code
var buttons = element.html(); // Get contents of element before overriding
element.html(template + buttons);
$compile(element.contents())(scope);
}
}
});
The html template was becoming messy, and I wanted to wrap the buttons 'inside' of the template, rather than after them. So I refactored into what I thought was a much better directive.
html 模板变得凌乱,我想将按钮包裹在模板的“内部”,而不是在它们之后。所以我重构了我认为更好的指令。
app.directive('validatedForm', ['$compile', '$sce', function ($compile, $sce) {
var domContent = null;
return {
restrict: 'AE',
scope: true,
templateUrl: '/Content/ngViews/directives/validated-form.html',
link: function(scope, element, attrs) {
// This now returns the contents of templateUrl
// instead of what the directive had as inner HTML
domContent = element.html();
// Scope
scope.form = {
caption: attrs.caption,
location: 'Content/ngViews/forms/' + attrs.name + '.html',
buttons: $sce.trustAsHtml(domContent),
showButtons: !(domContent.replace(' ', '') === '')
};
}
};
}]);
So what I'm noticing is that element.html() now retrieves the contents of the templateUrl instead of the contents of the inner HTML of my directive. How else can I get the contents of my directive before it gets overriden by the templateUrl?
所以我注意到 element.html() 现在检索 templateUrl 的内容而不是指令的内部 HTML 的内容。在我的指令被 templateUrl 覆盖之前,我还能如何获取它的内容?
采纳答案by charlietfl
To access the iniital html can use $transclude
within directive controller. This is a slight change from earlier versions so assumes using 1.2
要访问初始 html,可以$transclude
在指令控制器中使用。这与早期版本略有不同,因此假设使用 1.2
controller:function($scope,$transclude){
$transclude(function(clone,scope){
/* for demo am converting to html string*/
$scope.buttons=angular.element('<div>').append(clone).html();
});
}