AngularJS: Binding JavaScript Received in XHR to the View -
working on reporting application reports generated (in html) birt report engine object. report data comes json string recieved xhr. json string contains combination of html , javascript (a function call, specifically). once received, report data stuffed display in view. view put using angularjs.
i did research , found binding html/javascript view in angular requires use of $compile. using basis, put code include data , execute code bound string defined explicitly in $scope. - unless i'm going overlooking after staring @ same stuff couple hours, approach i'm using not work $scope data defined xhr. here's plunkr show general idea implemented. suggestions appreciated.
the html
<!doctype html> <html data-ng-app="example"> <head lang="en"> <meta charset="utf-8"> <title></title> <link href="//maxcdn.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css" rel="stylesheet"> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.10/angular.js"></script> <script src="//cdnjs.cloudflare.com/ajax/libs/angular-ui-bootstrap/0.11.0/ui-bootstrap-tpls.js"></script> <script src="//cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.20/angular-sanitize.js"></script> <script src="script.js"></script> </head> <body ng-controller="controller" > <h1>static content</h1> <p><button href="javascript: void(null)" role="link" ng-click="loadsubreport('recv_po_detail.rptdesign', 'static')">po000007</button></p> <h1>html static string</h1> <div compile="snippet"></div> <h1>html server string</h1> <div compile="html.body"></div> <hr /> <button ng-click="alert()">show xhr data</button> </body> </html> the javascript
var app = angular.module('example', []); app.controller('controller', ['$scope', '$compile', '$http', function ($scope, $compile, $http){ $scope.snippet="<p><button href=\"javascript: void(null)\" ng-click=\"loadsubreport('recv_po_detail.rptdesign', 'compiled')\">po000007</button></p>"; $http.get('data.json') .success(function (data) { $scope.html = data; }); $scope.loadsubreport = function (filename, source) { alert("called " + source); }; $scope.alert = function () {{ alert($scope.html.body); }} }]); app.directive('compile', ['$compile', function ($compile) { "use strict"; return function (scope, element, attrs) { var ensurecompilerunsonce = scope.$watch( function (scope) { return scope.$eval(attrs.compile); }, function (value) { element.html(value); $compile(element.contents())(scope); ensurecompilerunsonce(); } ); }; }]);
your watch goes off right @ start, when html.body still undefined. run ensurecompilerunsonce() , unwatch scope. proper report, once loaded, never gets compiled. uncommented line ensurecompilerunsonce() , nice view of report.
Comments
Post a Comment