I am currently developing an AngularJS website that fetches data from a web service/API. One API returns HTML and AngularJS code in order to dynamically add controllers or other new Angular components as needed. This specific string will be included in the API response.
<div id="homecontainer" class="flex-center p-page" loader style="overflow:hidden;">
<div class="column-1">
<div class="grid m-0 col-xs-12">
<div ng-repeat="Widget in V3Widgets track by $index" class="grid-item">
<div class="grid-sizer"></div>
{{Widget}}
</div>
</div>
<div ng-controller="WelcomeController">
{{greeting}}
</div>
<script>
var app = angular.module('demo', [])
//RestService is Another Module Which is Already Functioning Properly
.controller('WelcomeController', function ($scope, RestService) {
$scope.greeting = 'Welcome!';
});
angular.bootstrap(document, ['demo']);
</script>
</div>
</div>
I now have a directive that binds this string to the page.
<renderdynamicwidgethtml ng-if="Widget.Id==null && Widget.Html!=null" html="Widget.Html"/>
The JavaScript for the directive:
.directive('renderdynamicwidgethtml', ['$compile', function ($compile) {
return function (scope, element, attrs) {
scope.$watch(
function (scope) {
return scope.$eval(attrs.html);
},
function (value) {
element.html(value);
$compile(element.contents())(scope);
}
);
};
}])
scope.$eval
should convert the string into Angular components, but unfortunately it failed with the following error message.
[ng:btstrpd] http://errors.angularjs.org/1.3.17/ng/btstrpd?p0=document