我的角1.5.8应用程序中有一个属性指令my-directive。我想将它添加到一个元素中,并且我还想传递两个额外的参数,一个是one-way绑定(@),另一个是two-way绑定(=)。
它可以正常工作,直到我尝试自定义指令的编译函数以添加额外的属性。one-way绑定仍然工作正常,但是two-way绑定就消失了。
这是扑通。
如果我注释掉编译函数,它将再次工作。我想我是在以某种方式覆盖默认行为,但我想不出如何防止这种情况发生。
我的编译功能:
compile: function compile(element, attrs) {
return {
pre: function preLink(scope, iElement, iAttrs, controller) {},
post: function postLink(scope, iElement, iAttrs, controller) {
if (!iAttrs.compiled) {
iElement.attr('compiled', true);
iElement.attr('ng-click', "$ctrl.onClick()");
$compile(iElement)(scope);
}
}
};
}发布于 2016-11-09 16:37:01
对于为什么会出现这种情况,我没有确切的答案,但是编译只适用于当前集合中的子元素。因此,您只需将$compile(...更改为以下代码即可解决此问题。
$compile(iElement.children())(scope);更新1
显然,iElement的作用域已经由父作用域定义。因此,编译将无法使用该元素,因为孤立的作用域仅在指令中工作。
但是,现在的问题是如何在编译阶段添加新的指令?可以通过将指令更改为以下代码来做到这一点:
.directive('myDirective', function($compile) {
return {
terminal: true,
priority: 1001,
restrict: 'A',
scope: {
myObject: '=myObject',
text: '@text'
},
transclude: true,
bindToController: true,
controller: function() {
var $ctrl = this;
$ctrl.onClick = onClick;
return $ctrl;
function onClick() {
alert("clicked");
}
},
controllerAs: '$ctrl',
template: '<pre>{{$ctrl}}</pre> {{ $ctrl.text }} - {{ $ctrl.myObject.attr1 }}',
compile: function compile(element, attrs) {
element.removeAttr("my-directive");
element.attr('compiled', true);
element.attr('ng-click', "$ctrl.onClick()");
return {
pre: function preLink(scope, iElement, iAttrs, controller) {},
post: function postLink(scope, iElement, iAttrs, controller) {
$compile(iElement)(scope);
}
};
}
};
});https://stackoverflow.com/questions/40510845
复制相似问题