如何使用ajax在DIV中加载AngularJs页面

时间:2015-11-02 07:48:08

标签: php ajax angularjs

我创建了一个这样的表。

<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>

onclick ajax页面将被调用

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;
    }
});

在det.php页面中,将根据传递的参数动态创建user_det.js。

<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> 

如果我单独运行det.php页面angularjs页面运行完美,但是ajax成功功能页面未正确加载。所以我需要一些解决方案来加载ajax中的angularjs页面。

1 个答案:

答案 0 :(得分:4)

您可以添加一个将加载html和js文件的指令。

<强> 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);
        }
      });
    }
  };
});

进入点击方法

$.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>