我有一个用于表单验证样板的指令,我最近对其进行了重构。在扩展之前,请允许我进一步解释该指令。
指令用法:
<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>
以前,我的指令看起来像这样,并且它有效。
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);
}
}
});
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(' ', '') === '')
};
}
};
}]);
所以我注意到 element.html() 现在检索 templateUrl 的内容,而不是指令的内部 HTML 的内容。我还能如何在指令被 templateUrl 覆盖之前获取指令的内容?
最佳答案
要访问初始 html,可以在指令 Controller 中使用 $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();
});
}
关于javascript - 在 templateUrl 覆盖它之前检索 AngularJS 指令的内部 HTML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20110927/