2015-09-14 37 views
0

我有使用驗證數字字段的test.html angularjs一個非常簡單的形式...使用Ajax把外部angularjs元素在HTML頁面

http://plnkr.co/edit/mfxdTxGUXLZswzl1nyF2?p=preview

<div ng-app="myApp"> 
<script> 
angular.module('myApp', []) 
.controller('myController', ['$scope', function($scope) { }]); 
</script> 

<form name="myForm" ng-controller="myController"> 
    <input name="numberField" ng-model="myModel" type="number" value="" /> 
    <p ng-show="myForm.numberField.$error.number">Not valid number!</p> 
</form> 
</div> 
</html> 

我希望把這種形式爲不同的html頁面...

<html> 
<div id="test"> 
<!--I want my angular js number element to go here--> 
</div> 
</html> 

通常當我做這樣的事我使用JavaScript,並作出reques噸至頁面,並使用innerHTML到地方,我想它,像這樣的形式...

<script> 
var xRequest1; 
    xRequest1=new XMLHttpRequest(); 
    xRequest1.onreadystatechange=function() 
    { 
     if((xRequest1.readyState==4) && (xRequest1.status==200)) 
     { 
      document.getElementById("test").innerHTML=xRequest1.responseText; 
     } 
    } 
    xRequest1.open("post","test.html",true); 
    xRequest1.send(); 
</script> 

但是這是行不通的,任何想法,我怎麼能做到這一點?或者這甚至有可能?我以前從未使用過angularjs。提前致謝!

+1

你可以使用NG-包括哪些內容? – Ronnie

回答

0
  • 如果你是從頭開始構建的角度應用程序,然後,你應該考慮 ,將在主索引ng-app並採用NG-包括作爲 @Ronnie指出。

  • 但是,如果你被迫整合的角度,在一個地方遺留 代碼,您可以使用angular.boostrap手動引導角的應用程序,之後,盡顯 DIV#測試在Ajax回調:

Here is a working demo using your exemple.

var xRequest1; 
    xRequest1=new XMLHttpRequest(); 
    xRequest1.onreadystatechange=function() 
    { 
     if((xRequest1.readyState==4) && (xRequest1.status==200)) 
     { 
      document.getElementById("test").innerHTML=xRequest1.responseText; 
      // bootstrap your app here ... 
      angular.bootstrap(document.getElementById('test'), ['myApp']); 
     } 
    } 
    xRequest1.open("get","test.html",true); 
    xRequest1.send(); 
+0

非常感謝!我一直試圖讓這項工作太長時間。出於好奇,爲什麼我需要在我的主頁面中有angular.module('myApp'...腳本?因爲所有這些都在我的頁面中,所以調用我的測試div來填充它。世界,但我不能讓它工作,除非我在主頁面。 – jeeves2007