For the most part, this is considered a bad-dog thing to do in AngularJs. But sometimes… it just has to be done. I came across this after hours and hours of fighting, then I looked deeper into ng-view. If the directive tag was in a different file loaded in via the view, it will render properly.
Scenario:
Main page and a button. The button opens a modal with a form. When the form is submitted, that data is used to make a new directive DOM element on the main page.
Problem:
The new instance of the directive is just string on a page. The directive never get applied. We want the div on 8888 to say ‘Hello World!. Without this $compile function, we would see <div>Hello World</div>. The directive is never applied.
<div ng-app="poc">
<div ng-controller="mainCtrl">
<div>Test 1 : sanity check</div>
<div xrx-hello-world></div>
<div>Test 2 : applied using getElementById(8888)</div>
<div id="8888">Replace Me</div>
<div xrx-add-button=""></div>
</div>
</div>
var poc = angular.module('poc', ['ngResource', 'ngSanitize']);
poc.directive("xrxHelloWorld", function () {
return {
priority: 50,
restrict: 'A',
replace: false,
transclude: true,
scope: false,
template: '<div>Hello World</div><div ng-transclude></div>',
};
});
poc.directive('xrxAddButton', function ($compile) {
return {
priority: 50,
restrict: 'A',
replace: false,
transclude: true,
scope: false,
template: '<button>Click</button><div ng-transclude></div>',
link: function (scope, element, attr) {
var btn = angular.element(element.children()[0]);
var handleClick = function () {
var directiveStr = '<div xrx-hello-world></div>';
var directiveDom = angular.element(directiveStr);
var newDomHome = angular.element($('#8888')).html(directiveDom);
$compile(newDomHome);
};
btn.bind('click', handleClick);
}
};
});
No comments:
Post a Comment