How to load AngularJs page in DIV using ajax

I created a table like this.

<table>
<tr>
 <th>Name<th>
 <th>Dept<th>
 <th>Num<th>
</tr>
<tr onclick="detail('xyz','1')">
  <td>abc</td>
  <td>xyz</td>
  <td>1</td>
</tr>
</table>
<div id='content'></div>

While onclick the ajax page will be called

function detail(dept,no){
$.ajax({
    url:"det.php?dept="+dept+"&no="+no,
    success:function(data){
        $.getScript("../bootstrap/js/user_det.js");
        document.getElementById('content').innerHTML=data;
    }
});

On the det.php page, user_det.js will be created dynamically according to the passed parameter.

<script src='bootstrap/js/user_det.js'> </script>
<div  ng-app="myApp" ng-controller="MyController">
  <div  ng-repeat = "val in sample_det">
     <div>{{val.dept}}</div>
     <div>{{val.id}}</div>
     <div>{{val.date}}</div>
  </div>
</div> 

If I run the det.php page separately, the angularjs page works fine, but the success function is ajax, the page is not loaded properly. So I need some solution to load angularjs page in ajax.

+4
source share
1 answer

You can add a directive that will load your html and js files.

HTML:

<div id='content' load-content></div>

JS:

app.directive('loadContent', function($compile) {
  return {
    link: function(scope, elem, attrs) {

      $.ajax({
        url: "det.php?dept=" + dept + "&no=" + no,
        success: function(data) {

          //append this js into this page header
          $.getScript("../bootstrap/js/user_det.js");

          //create an angular element. (this is still our "view")
          var el = angular.element(data);

          //compile the view into a function.
          compiled = $compile(el);

          //append our view to the element of the directive.
          elem.append(el);

          //bind our view to the scope!
          //(try commenting out this line to see what happens!)
          compiled(scope);
        }
      });
    }
  };
});

On click method

$.ajax({
    url: "det.php?dept=" + dept + "&no=" + no,
    success: function (data) {

        //append this js into this page header
        $.getScript("../bootstrap/js/user_det.js");

        //create an angular element. (this is still our "view")
        var el = angular.element(data);

        //compile the view into a function.
        compiled = $compile(el);

        //append our view to the element of the directive.
        var elem = angular.element("#content");
        elem.append(el);

        //bind our view to the scope!
        //(try commenting out this line to see what happens!)
        compiled(scope);
    }
});

HTML <div id='content'></div>

+4
source

Source: https://habr.com/ru/post/1614103/


All Articles