angularjs - How to include data/scope from controller in a dynamically added directive? -
i'm trying figure out how include scope directive add dom on click event in controller.
step 1. on click event, call function in controller adds directive this
$scope.addmydirective = function(e, instanceofanobjectpassedinclickevent){ $(e.currenttarget).append($compile("<my-directive mydata='instanceofanobjectpassedinclickevent'/>")($scope)); } //i'm trying take `instanceofanobjectpassedinclickevent` , make available in directive through `mydata`
the above, part of got from answer, adds directive (and directive has template gets added dom), however, inside directive, i'm not able access of scope data mydata
says it's undefined
.
my directive
app.directive('mydirective', function(){ return { restrict: 'ae', scope: { mydata: '=' //also doesn't work if mydata: '@' }, template: '<div class="blah">yippee</div>', link: function(scope,elem,attrs) { console.log(scope) //inspecting scope shows mydata undefined } } }
update changed name of datafromclickedscope
in op make more clear. in controller action addmydirective
(see above) instanceofanobjectpassedinclickevent
instance of object passed controller method on click event try pass directive mydata='instanceofanobjectpassedinclickevent'
. however, if change =
@
in directive , try access scope.mydata in link function of directive, shows string "instanceofanobjectpassedinclickevent"
, not actual object data available me in method handles click event
when use mydata='instanceofanobjectpassedinclickevent'
in template need instanceofanobjectpassedinclickevent
defined in $scope. before compiling should assign variable in $scope. rename variable in code below, same names not confuse , clear formal parameter of function cannot visible in template.
$scope.addmydirective = function(e, instanceofanobjectpassedinclickevent){ $scope.myevent = instanceofanobjectpassedinclickevent; $(e.currenttarget).append($compile("<my-directive mydata='myevent'/>")($scope)); }
edit: adapted jsfiddle not using jquery no manipulate dom
Comments
Post a Comment