假设这个指令:
<validation-errors field="someField">Some errors: {{errors}}</validation-errors>
我以为我可以简单地创建指令函数:
return {
require: '^form',
restrict: 'E',
link: link,
scope: {
field: '@'
},
transclude: true,
template: '<span ng-show="errors" class="alert-danger" ng-transclude></span>'
};
function link(scope, el, attr, ctrl, transcludeFn) {
scope.errors = ctrl.Validator.getErrors(attr.field);
}
但是自Transclusion is the process of extracting a collection of DOM element from one part of the DOM and copying them to another part of the DOM, while maintaining their connection to the original AngularJS scope from where they were taken.
(来自文档)以来,范围并不像我想象的那样有效。
所以我尝试了哪个,除了&#34;一些错误&#34;部分重复:
transcludeFn(function(clone, transScope) {
scope.errors = transScope.errors = ctrl.Validator.getErrors(attr.field);
el.append(clone);
});
如果我删除el.append(clone);
,则无法正常工作。
使被抄送的内容分享指令模板范围的最佳方法是什么?
答案 0 :(得分:0)
如果你想使用指令创建错误,试试这样的东西,我已经更新了代码,以便它也编译模板,现在完全像ng-transclude
指令一样工作开箱即用。
'use strict';
/* Directives */
angular.module('myApp.directives', []).
directive('errordirective', ['$compile',function($compile) {
return {
restrict: 'E',
scope: {
field: '@',
},
transclude: true,
//Create some error text
controller: function() {
this.errorText = "Some Errors We Created";
//Make the template available to the link fn, and make it an angular element.
this.template = angular.element('<span class="alert-danger" ng-transclude></span>')
},
//Make the controller available easily
controllerAs: 'Errors',
//Bind the scope properties to the controller, only works with controllerAs
bindToController: true,
template: '<span class="alert-danger" ng-transclude></span>',
link: function(scope, elem, attrs, ctrl, transcludefn) {
//Replace the original element with the new one that has the error text from our controller
transcludefn(scope, function(el) {
var template = ctrl.template;
var html = el.html();
//Add the transcluded content to the template
template.html(html);
//Compile the template with the appropriate scope
template = $compile(template)(scope);
//Replace with the new template
elem.replaceWith(template);
});
}
};
}]);