在我的场景中,我有一个指令,它将有另一个指令标记作为范围参数。然后第一个指令需要生成新指令并将其附加到其中。它还需要为新生成的指令添加动态双向绑定属性。
我能够生成新的指令标签,但是当我尝试添加指令属性时,它会将其附加为字符串(值或简单字符串)。因此,当我尝试在新指令中将属性作为范围变量访问时,它给了我“未定义”。
HTML :
<div ng-controller="MainCtrl">
===
<directive1 tag="obj.tag" request-id="requestId"></directive1>
</div>
指令:
app.directive('directive1', function($compile) {
return {
restrict: 'E',
scope:{
tag:"=",
requestId:"="
},
link: function(scope, element, attrs) {
var el;
scope.$watch('tag', function (tpl) {
console.log("8888",tpl);
el = $compile(tpl)(scope);
el.attr('request-id', scope.requestId);
el = $compile(el)(scope);
element.append(el);
});
// attrs.$set('ngHide', false);
// attrs.$set('hide', null);
// $compile(element)(scope);
}
};
})
app.directive('test', function($compile) {
return {
restrict: 'E',
scope:{
requestId:"="
},
controllerAs: 'requestCtrl',
bindToController: true, //required in 1.3+ with controllerAs
controller:function(){
var requestCtrl=this;
console.log("----->>>> ",requestCtrl.requestId)
},
link: function(scope, element, attrs) {
}
};
});
控制器:
app.controller('MainCtrl', function($scope) {
$scope.obj={};
$scope.obj.tag="<test></test>";
$scope.requestId="123";
});
这里是plunker
您的 plunker 正在使用尚不支持的 angular 1.0.2 bindToController
,更改为 1.3 将使其作为您问题中所述的字符串绑定工作。
要将 requestId 用作 2 路绑定,您需要将字符串传递requestId
到 attr。
el.attr('request-id', 'requestId');
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句