I am new to angularjs. In my project i am getting an HTML file as http response. ng-bind-html works with html code. But the angularjs code inside html is not getting compiled. I tried the solutions with $compile ,nothing works. Please suggest a good solution for this.
Lets say we have a sample code like this:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>TEST</title>
<script src="angular.js"></script>
</head>
<body ng-app="myapp">
<div ng-controller="myController">
<p compile="htmlresponse"></p>
</div>
<script>
var app = angular.module('myapp', []);
app.controller('myController', function ($rootScope,$sce) {
$http.get(,,,,).success(function(data){
$rootScope.htmlResponse=$sce.trustAsHtml(data);
}
});
app.directive('compile', function($compile) {
// directive factory creates a link function
return function(scope, element, attrs) {
scope.$watch(
function(scope) {
return scope.$eval(attrs.compile);
},
function(htmlResponse) {
element.html(htmlResponse);
$compile(element.contents())(scope);
}
);
};
});
</script>
</body>
</html>
This works fine if i get only HTML as response. When i get HTML with angularjs(which includes app.module,app.controller,app.directives), only the html part is getting compiled. Please help me with this issue.
Here is my sample response.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>TEST</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.1/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.1/angular-animate.min.js"></script>
</head>
<body ng-app="myapp">
<div ng-controller="myController">
{{name.myname}}
</div>
<script>
var app = angular.module('myapp', []);
app.controller('myController', function ($scope) {
$scope.name={};
$scope.name.myname = "stack";
});
</script>
</body>
</html>
I tried with iframe,, and it works,,, :) Either we have to save the response in an HTML file and use it like this,,,,,,,
<iframe src="htmlResponse.html"> </iframe>
Or we can directly assign the rootscope variable to it.
<iframe width="100%" height="500px" ng-attr-srcdoc="{{htmlResponse}}"></iframe>