2017-08-14 109 views
1

在我的方案中,我有一个指令,将有另一个指令标记作为范围参数。第一条指令然后需要生成新的指令并将其添加到其中。它还需要将动态双向绑定属性添加到新生成的指令中。AngularJS自定义生成的指令动态属性绑定

我能够生成新的指令标记,但是当我尝试添加指令属性时,它将其作为字符串(值或简单字符串)追加。 因此,当我试图在新指令中作为范围变量访问属性时,它给了我'未定义'。

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

回答

1

你plunker使用角1.0 .2它不支持bindToController,但更改为1.3将使其按您的问题中所述的字符串绑定工作。

要使用requestId作为双向绑定,您需要将字符串requestId传递给attr。

el.attr('request-id', 'requestId'); 

Working plunker