Angular custom directive added dynamically
Managing scope before $compiling template on the fly
by Kyrylo Slatin
HTML
<div ng-controller="ctrl">
<div class='customContainer' ng-click="addDirective(this, 123)">Add directive</div>
</div>
CSS
.customContainer {
min-width: 40px;
min-height: 40px;
background-color: yellow;
}
JavaScript
angular.module('app', []);
angular.module('app').controller('ctrl', function ($scope, $rootScope, $compile) {
$scope.addDirective = function (element, data) {
$scope.myEvent = data;
element.innerHtml += ($compile("<my-directive mydata='myEvent'/>")($scope));
};
});
angular.module('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.mydata); //inspecting scope shows that mydata is undefined
}
}
});
angular.bootstrap(document, ['app']);