在我的场景中,我有一个指令,它将另一个指令标记作为范围参数。然后第一个指令需要生成新指令并将其附加到其中。它还需要将动态双向绑定(bind)属性添加到新生成的指令中。
我能够生成新的指令标签,但是当我尝试添加指令属性时,它会将其附加为字符串(值或简单字符串)。 因此,当我尝试在新指令中将属性作为范围变量访问时,它会给我“未定义”。
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) {
}
};
});
Controller :
app.controller('MainCtrl', function($scope) {
$scope.obj={};
$scope.obj.tag="<test></test>";
$scope.requestId="123";
});
这是 plunker
最佳答案
您的 plunker 使用的是 angular 1.0.2,它不支持 bindToController
但是,更改为 1.3 将使它像您的问题中所述的字符串绑定(bind)一样工作。
要将 requestId 用作双向绑定(bind),您需要将字符串 requestId
传递到 attr。
el.attr('request-id', 'requestId');
关于javascript - AngularJS 自定义生成的指令动态属性绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45668822/