I have following situation. I created angularjs directive, which works great inside angularjs world. But I need to get compiled version of that directive from code which lives outside of angular. I know it's ugly way of doing this, from angularjs prospective, but right now I have js library, which accepts only html, and makes some transformations on that, and returns html, which I need. That js library knows nothing about Angular, and works only with html. For demo purposes I've created simple directive, simple controller, and simple page. You can see it on plunker here . Directive should be compiled and for example alerted after button click.
Here is js code:
function drawDirective()
{
var htmlForCompile = '<div ng-controller="testController as tc"><coold settings="tc.settings"></coold></div>';
var injector = angular.injector(['ng', 'examples']);
var htmlOut = '';
injector.invoke(function ($compile) {
//how to receive scope ???
var scope = angular.element(htmlForCompile).scope();
htmlOut = $compile(htmlForCompile)(scope);
alert(htmlOut);
});
}
angular.module('examples', []);
(function ()
{
var cnt = 'testController';
angular.module('examples').controller(cnt, testController);//register
testController.$inject = ['$scope'];
function testController($scope) {
var vm = this;
var settings = {};
settings.value = "this is test output";
vm.settings = settings;
}
angular.module('examples').directive('coold', function ($compile) {
return coold($compile);
});
function coold(compile){
var directiveReturn = {
cmp : compile,
restrict: 'AEC',
templateUrl: function(elem, attr) {
return 'template.html';
},
scope: {
settings: "=settings"
}
};
return directiveReturn;
}
})();
Html code:
<head>
<link rel="stylesheet" href="style.css">
<script data-require="[email protected]" data-semver="1.5.0" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.0/angular.js"></script>
<script src="script.js"></script>
</head>
<body>
<div ng-app="examples" id="insideAngular">
<div ng-controller="testController as tc">
<coold settings="tc.settings"></coold>
</div>
</div>
<div id="nonAngularJS">
<button id="click" onclick="return drawDirective()">Draw directive</button>
</div>
</body>
</html>
and template which is used by directive:
<div>
<span>{{settings.value}}</span>
</div>