0

My basic use-case is this - When a particular route is hit (#/abc) I need to make a POST call to the server and render the HTML sent as a response. Since the HTML depends on the server call, I did not favor writing this logic into $routeProvider.when.

My solution -

  • Open the route
  • Load a blank view in the ng-view (used in the other parts of app)
  • The blank view contains a div with <div ng-bind-html=responseHtml></div>
  • In the controller, make a $http.post and with the data returned, I set the above expression to $scope.responseHtml = $sce.trustAsHtml(data);

This is working perfectly fine, however, I am unable to set any bindings in the responseHtml.

The accompanying JSFiddle is here - http://jsfiddle.net/prakhar1989/LX26M/2/

I'm not sure if what I'm doing is the correct way to do it (this is my first Ng app). Any guidance will be greatly appreciated!

Thanks!

1 Answer 1

2

Made this for you: http://jsfiddle.net/BgW3u/

You are passing the HTML to the directive and the related scope and it will $compile it.

app.directive("ngCompile", function($compile){
    return {
        scope: {
            "ngCompile": "=",
            "ngCompileScope": "="
        },        
        link: function($scope, $element){                    
            $scope.compile = function(){
                $element.html($scope.ngCompile);  
                $compile($element.contents())($scope.ngCompileScope);
            }            
            $scope.$watch("ngCompile",function(){
               $scope.compile();
            });
        }
    }
});

OR without isolated scope:

app.directive('ngCompile', function ($compile) {
  return {
    restrict: 'A',
    replace: true,
    link: function (scope, ele, attrs) {
      scope.$watch(attrs.ngCompile, function(html) {
        ele.html(html);
        $compile(ele.contents())(scope);
      });
    }
  };
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.