Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rendering dynamic HTML(angularjs content) content after ajax call in AngularJS

Tags:

angularjs

I am new to Angular getting stuck after making ajax call. How do I render/compile the html content once you inject in DOM so that I can still use the AngularJs functions.

Due to the way my backend is set up I have to get content via ajax ($http). And I am making the app without jQuery. I tried $compile and $apply but didn't work. What am I missing here.

I have the code set up at http://jsfiddle.net/rexonms/RB7FQ/3/ . I want the second div content to have the same properties as the first div.


HTML

<div ng-controller="MyCtrl" class="section">
  <input ng-model="contentA">
  <div>
      And the input is: {{contentA}}
  </div>
</div>

<div ng-controller="MyAjax" class="section">
  <div id="dumpAjax">
    {{ajaxData}}
  </div>
  <button ng-click=getajax()> Get Ajax</button>
</div>

SCRIPT

var myApp = angular.module('myApp',[]);

//myApp.directive('myDirective', function() {});
//myApp.factory('myService', function() {});

function MyCtrl($scope) {

}

function MyAjax($scope){
  var data = '<input ng-model="contentB">{{contentB}}';

  $scope.getajax = function(){
    $scope.ajaxData = data;
  }

}

Thanks in advance.

like image 663
rex Avatar asked Mar 20 '14 14:03

rex


2 Answers

ng-bind-html-unsafe is not available 1.2 and later verison of angular...

so you should use ng-bind-html which creates a binding that will innerHTML the result of evaluating the expression into the current element in a secure way.

using $scope variable in your string make it unsafe, so you should use $sce.trustAsHtml but this time variables in your string cannot be bind because they will be not compiled...

basically you should compile your string in order to bind your variables. Here comes custom directives you can create a directive which can replace with ng-html-bind...

Writing a custom directive which extends ng-bind-html with some extra functions can be a solution...

here is my PLUNKER

and here is your updated JSFIDDLE with my solution...

like image 167
Poyraz Yilmaz Avatar answered Nov 20 '22 12:11

Poyraz Yilmaz


Instead of {{ajaxData}}, you should use something like:

<div ng-bind-html-unsafe="ajaxData"></div>

However, you'd still need to set the proper model to bind the contentB and get it working.

like image 42
Shomz Avatar answered Nov 20 '22 12:11

Shomz