Leahcim
Leahcim

Reputation: 42069

How to include data/scope from controller in a dynamically added directive?

I'm trying to figure out how to include scope with a directive that I add to the dom on a click event in a controller.

Step 1. On a click event, I call a function in my controller that adds a directive like this

$scope.addMyDirective = function(e, instanceOfAnObjectPassedInClickEvent){
   $(e.currentTarget).append($compile("<my-directive mydata='instanceOfAnObjectPassedInClickEvent'/>")($scope));

}
   //I'm trying to take the `instanceOfAnObjectPassedInClickEvent` and make it available in the directive through `mydata`

The above, part of which I got from this SO answer, successfully adds the directive (and the directive has a template that gets added to the dom), however, inside the directive, I'm not able to access any of the scope data mydata it says it's undefined.

My directive

app.directive('myDirective', function(){

    return {
       restrict: 'AE',
       scope: {
         mydata: '='
         //also doesn't work if I do mydata: '@'
       },
       template: '<div class="blah">yippee</div>',
       link: function(scope,elem,attrs) {
              console.log(scope) //inspecting scope shows that mydata is undefined
         }
    }
}

Update I changed the name of datafromclickedscope in the OP to make it more clear. In the controller action addMyDirective (see above) instanceOfAnObjectPassedInClickEvent is an instance of an object passed into the controller method on a click event that I try to pass into the directive as mydata='instanceOfAnObjectPassedInClickEvent'. However, even if I change = to @ in the directive and I try to access scope.mydata in the link function of the directive, it just shows a string like this "instanceOfAnObjectPassedInClickEvent", not the actual object data that is available to me in my method that handles the click event

Upvotes: 0

Views: 67

Answers (1)

Kirill Slatin
Kirill Slatin

Reputation: 6173

When you use mydata='instanceOfAnObjectPassedInClickEvent' in a template you need instanceOfAnObjectPassedInClickEvent to defined in $scope. So before compiling you should assign a variable in $scope. I will rename this variable in code below, so that same names would not confuse you and it would be clear that a formal parameter of a function cannot be visible in a template.

$scope.addMyDirective = function(e, instanceOfAnObjectPassedInClickEvent){
   $scope.myEvent = instanceOfAnObjectPassedInClickEvent;
   $(e.currentTarget).append($compile("<my-directive mydata='myEvent'/>")($scope));
}

EDIT: slightly adapted jsfiddle not using JQuery no manipulate DOM

Upvotes: 1

Related Questions