2016-04-21 14 views
1

我有通過控制器查詢數據庫的JSON響應,我想在view.ejs文件中打印此JSON對象值。當數據庫調用時,控制器響應返回JSON對象時無法在view.ejs中打印JSON對象值

view.ejs

<div ng-app="myApp" ng-controller="customersCtrl"> 

<table> 
<tr ng-repeat="x in names"> 
    <td>{{ x.username}}</td> 
    <td>{{ x.password}}</td> 
</tr> 
</table> 
</div> 

<script> 
    var app = angular.module('myApp', []); 
    app.controller('customersCtrl', function($scope, $http) { 
    $http.get("") 
.then(function (response) {$scope.names = response.users;}); 
}); 
</script> 

這是我的模型 user.js的

module.exports = { 
    autoCreatedAt: false, 
    autoUpdatedAt: false, 

    attributes: { 

    username:{ 
     type:'string', 
     required: true, 
     unique:true 
    }, 
    password:{ 
     type:'string', 
     required:true 
    }, 
    } 
}; 

這是我的控制器 UserController.js

module.exports = { 
    get:function(req,res){ 
     User.find().exec(function (err, users){ 
      if (err) { 
       return res.json(err); 
      } 

      return res.json(users); 
     }); 
    } 
    }; 

我配置在以下路線文件 routes.js

module.exports.routes = { 

    '/': { 
     view: 'view' 
    }, 

    '/user/get': 'UserController.get', 

}; 

當我點擊URL「http://localhost:1337/user/get」時,我在json響應下面得到了這個,我想把這個值推入到view.ejs文件中。

​​

我想知道,如果有人可以幫助我瞭解如何我可以得到這些values.Thank你的任何建議

+0

嘗試在您的視圖中添加{{names}}您是否在獲取 – santhosh

+0

中的用戶否我沒有獲取values.Please保留此建議 – user3534759

+0

$ scope.names = response.users - >添加$ scope。$ apply($ scope。名稱)並檢查您的視圖中的{{名稱} – santhosh

回答

1

的問題,從response數據分配names。即,

使用

$ scope.names =響應。 data .users; OR $ scope.names = response。 data;

代替

$ scope.names = response.users;

+0

返回所有此檢查之前,他正在返回整個用戶並且未使用數據對象 – santhosh

+0

是正確我正在返回整個用戶對象並且$ http.get(「」)方法是否需要URL? – user3534759

+0

如果您使用角度爲'http'的承諾,那麼一些元數據會自動添加到響應對象中。例如:Object {data = [3],status:「200」,statusText =「OK」,config = {}}' – vineet

0

作爲響應本身,您正在獲取對象數組,因此如果將其直接分配給$ scope.names,它將起作用。

如果它可以幫助你,請讓我知道。

$ http.get。( 「本地主機:1337 /用戶/獲取」),那麼(功能(響應){$ scope.names =響應; 的console.log(響應); })