2016-11-07 87 views
0

我是AngularJS的新手。AngularJS - HTML頁面在使用ngView時不顯示返回的數據

我有一個SQL數據庫PHP服務器,我有AngularJS一個HTML頁面和發送$ HTTP GET請求到服務器,返回數據的數組顯示在一個表上相同的按鈕頁。

每當我直接打開頁面websitename/myList.htm和我按下getList,數據顯示完美沒有任何問題,但一旦我通過路由,ngView打開頁面,頁面元素出現,但如果我按下按鈕,頁面不會從服務器獲取數據更新。

這兩個頁面之間是否需要額外的數據鏈接?

myList.htm

<!DOCTYPE html> 
<html> 
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script> 
<script src="https//ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-route.js"></script> 

<script> 
angular.module("crudApp", []) 
.controller("userController", function($scope,$http){ 
$scope.users = []; 
$scope.tempUserData = {}; 
// function to get records from the database 

$scope.getList = function(){ 
$http.get('action.php', { 
params:{ 
'type':'getList' 
     } 
    }).success(function(response){ 
     if(response.status == 'OK'){ 
      $scope.users = response.records; 
     } 
    }); 
}; 


}); 

</script> 


<body ng-app="crudApp"> 
<div class="container" ng-controller="userController"> 

<a href="javascript:void(0);" class="btn btn-success"  ng-click="getList()">getList</a> 


     <table class="table table-striped"> 
      <tr> 
       <th width="20%">Name</th> 
       <th width="30%">Email</th> 
       <th width="20%">Phone</th> 
      </tr> 
      <tr ng-repeat="user in users"> 
       <td>{{user.Name}}</td> 
       <td>{{user.Email}}</td> 
       <td>{{user.Phone}}</td> 
      </tr> 
     </table> 

<p>end of table</p> 
</body> 

</html> 

與路線頁:

<!DOCTYPE html> 
<html> 
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script> 
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-route.js"></script> 

<body ng-app="myApp"> 

<p><a href="#/">Main</a></p> 
<a href="#list">List</a> 



<div ng-view></div> 

<script> 
var app = angular.module("myApp", ["ngRoute"]); 
app.config(function($routeProvider) { 
$routeProvider 
.when("/", { 
    templateUrl : "main.htm" 
}) 
.when("/list", { 
    templateUrl : "myList.htm" 
}); 
}); 
</script> 

<p>Click on the links to navigate</p> 
</body> 
</html> 

謝謝。

+0

給我們看一些代碼 –

回答

0

您需要與控制器和app.js相同的.module名稱,例如;

var app = angular.module("myApp", ["ngRoute"]); 
angular.module("myApp", []).controller("userController" 

你沒有通過NG-路線工作的原因是因爲你裝「對myApp」的第一個實例,然後使用您的NG-視圖加載HTML網頁,其中會的工作,而是因爲你的模塊沒有作爲依賴添加到你的控制器上,它不會加載控制器,因爲它明確尋找使用「myApp」的控制器,它通過直接路由加載,因爲你從未告訴它明確使用「myApp」。

您還需要#/列表您的href標記。

您還只需要爲您的index.html引用一次角碼腳本,因爲它與整個應用程序有關,因爲當您加載「myList.htm」時,您將在ng中加載這些腳本的副本 - 查看標籤。如果「main.htm」首先被加載而不是默認的「index.html」,那麼這個方法可以工作,即使直接進入localhost:portnum /#/ list,你的路由也可以正常工作。

另外你應該在你的「main.htm」引用你的控制器腳本,這可以確保它們被加載在ng-view中使用,對於較大的頁面,你可以引用頁面底部的腳本,例如;

<script src="scripts/app.js"></script> 
<script src="scripts/controller"><script> 

由於文件路徑與當前項目目錄相關。

希望它有幫助!

相關問題