1

I have an HTML page with a button which fires on click a request to an external service. This post request returns an HTML page.

Is it possible to replace the current ngView with this HTML content?

$scope.clickEvent = function() {

  var url = '/external-service';
  var param = { someParameter: someValue };

  $http
    .post(url, param)
    .then(function (data) { // sucess

      // replace ngView with the data contents (which is a HTML)      

    }, function (data) { 
      // error
    });
}
mic
  • 13
  • 3

2 Answers2

0

This StackOverflow Answer shows pretty well how to add an element to some HTML by grabbing the element that they want to add HTML to

var btnhtml = '<button type="button" ng-click="addButton()">Click Me</button>';
var temp = $compile(btnhtml)($scope);
angular.element(document.getElementById('foo')).append(temp);

using angular.element then selecting the element and choosing append.

what you want to do is more like removing the element that is there and then adding elements of your own.

so grab the parent node, then parentNode.RemoveChild(elementYouWantGone) and then take that same parent node and then do a parentNode.append(variableHoldingHtmlYouWantThere)

Community
  • 1
  • 1
Malachi
  • 3,205
  • 4
  • 29
  • 46
  • I changed my answer after I re-read the question. my answer is super simple, and probably not very safe if there is malicious data coming from the response. – Malachi Feb 26 '16 at 15:13
  • 1
    Ty, that seems pretty close. If I grab the ngView node and replace its contents, it should work as I want. I will try. If it work, I will accept your answer. Thx. – mic Feb 26 '16 at 15:17
0

ngBindHtml should do the trick, don't forget to add ngSanitize to your dependencies and $sce.trustAsHtml(value) so you won't have problems.

You could have a div with ng-bind-html and your expression binded to it.

Remember to be careful with this. Malicious code might be coming from the response.

Example:

<div ng-app="myApp">
  <div ng-controller="testCtrl">
    <div ng-bind-html="myNewHtml"></div>
  </div>
</div>

$scope.clickEvent = function() {

    var url = '/external-service';
    var param = { someParameter: someValue };

    $http
        .post(url, param)
        .then(function(data) { // sucess
            $scope.myNewHtml = $sce.trustAsHtml(data.yourHtmlObject);
            // replace ngView with the data contents (which is a HTML)      

        }, function(data) {
            // error
        });
};

The codepen example is not grabbing the http response, but you can implement it.

Codepen: http://codepen.io/anon/pen/KzKPNp

Ariel
  • 1,507
  • 2
  • 20
  • 28