fra*_*ler 16 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="saveDetails()"
data-ng-disabled="!personalDetails.$valid">Save Changes</a>
</form>
Run Code Online (Sandbox Code Playgroud)
以前,我的指令看起来像这样,并且它有效.
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);
}
}
});
Run Code Online (Sandbox Code Playgroud)
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(' ', '') === '')
};
}
};
}]);
Run Code Online (Sandbox Code Playgroud)
所以我注意到的是element.html()现在检索templateUrl的内容而不是我的指令的内部HTML的内容.如果我的指令被templateUrl覆盖,我怎么能得到我的指令的内容?
cha*_*tfl 10
访问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();
});
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
19802 次 |
| 最近记录: |