1

In my scenario, I have a directive, that will have another directive tag as scope parameter. The first directive then needs to generate new directive and append that inside it. It also needs to add the dynamic two-way bound attribute to the newly generated directive.

I am able to generate the new directive tag, but when I try to add the directive attribute, its append this as the string(value or simple string). So when I try to access the attribute as scope variable in newly directive it gives me 'undefined'.

HTML :

<div ng-controller="MainCtrl">
===
<directive1 tag="obj.tag" request-id="requestId"></directive1>
</div>

Directive :

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";
});

Here is the plunker

1 Answer 1

1

Your plunker is using angular 1.0.2 which doesn't support bindToController yet, changing to 1.3 will make it work as string binding as described in your question.

To use requestId as a 2 way binding, you need to pass the string requestId into the attr.

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

Working plunker

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.