Javascript 在templateUrl覆盖AngularJS指令之前检索该指令的内部HTML
我有一个用于表单验证样板的指令,我最近对其进行了重构。在扩展之前,请允许我进一步解释一下该指令 指令用法:Javascript 在templateUrl覆盖AngularJS指令之前检索该指令的内部HTML,javascript,angularjs,Javascript,Angularjs,我有一个用于表单验证样板的指令,我最近对其进行了重构。在扩展之前,请允许我进一步解释一下该指令 指令用法: <form class="form-horizontal" name="personalDetails" validated-form> <!-- Pass buttons into form through here --> <a href="" class="btn btn-success" data-ng-click=
<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>
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,可以在指令控制器中使用
$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();
});
}
控制器:函数($scope,$transclude){
$transclude(功能(克隆,范围){
/*对于演示,我正在转换为html字符串*/
$scope.buttons=angular.element(“”).append(clone.html();
});
}
这正是您所说的,并且是正确的答案,不过作为后续操作-使用$sce通过ng bind HTML将传递的HTML绑定到templateUrl。trustAsHtml()会弄乱随作用域传递的单击事件。这是因为指令中出现了一个新的控制器吗?老实说,不知道你用它干什么。。。仅仅从作用域传入html并不能编译它。创建演示。总的来说,我对你正在做的事情有点困惑……只是给了你一种按要求访问html的方法。您可以使用plunker导入templateURL…只需创建一个包含html的文件,并将url调整到同一目录(仅文件)即可。谢谢,这会让您的工作时间更长一些。如果我发现问题所在,将发布更新。可能与我的代码有关。就像我说的,不管怎样,这都是实际问题的正确答案,谢谢!这怎么行
$transclude
似乎无法注入控制器。@EliranMalka您必须在指令的返回函数中添加一个transclude:true
(通常是链接的位置)
controller:function($scope,$transclude){
$transclude(function(clone,scope){
/* for demo am converting to html string*/
$scope.buttons=angular.element('<div>').append(clone).html();
});
}