我有一个指令,我使用了最近重构的表单验证样板。请允许我在扩展之前进一步解释指令。
指令用法:
<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覆盖之前,我还能如何去获得它的内容?
发布于 2018-04-09 09:15:04
访问iniital 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();
});
}
https://stackoverflow.com/questions/-100005263
复制相似问题