我是 Node.js 和 anguler.js 的新手,我想使用 angular.js 将 JSON 输出显示到网页。我的 angular.js 代码在 node.js 文件中
测试.js
var pg = require('/data /node_modules/pg');
var serverAddress = localhost';
var serverPort = '1337';
var conString = "tcp://myuser:myuser@localhost/mydb";
var client = new pg.Client(conString);
http = require('http');
fs = require('fs');
url = require('url');
path = require("path");
http.createServer(function (req, res) {
console.log("request is--- "+ req.url);;
res.writeHead(200,{"Content-type":"text/html"});
getData(res);
}).listen(serverPort, serverAddress);
function getData(res)
{
client.connect(function(err)
{
if(err){
return console.error('could not connect to postgres', err);}
client.query('select * from countrydata;', function(err, result){
if(err){
return console.error('error running query', err);}
res.write("<html ng-app>");
res.write("<body> Keep it simple....!");
res.write("<script>");
res.write("alert('it work!');");
res.write("</script>");
res.write("<table ng-controller= countryController>");
res.write("<td>{{directory}}</td>");
res.write("</tr>");
res.write("</table>");
res.write("<script
src=\'https://ajax.googleapis.com/ajax/libs/angularjs/1.0.1/angular.min.js\'>");
res.write("</script>");
for (var i in result)
{
var records =result[i];
if (i=='rows')
{
var json = JSON.stringify(result[i]);
}
}
res.write("<script>");
res.write("angular.controller(countryController, function($scope) {");
res.write("$scope.directory =" + json);
res.write("});");
res.write("</script>");
res.write("</body>");
client.end();
});
所以当我运行这个 test.js 时,我在网页上的输出看起来像这样:保持简单......!{{$目录}}
Html查看页面源代码看起来列表这个--
保持简单......!{{directory}}https://ajax.googleapis.com/ajax/libs/angularjs/1.0.1/angular.min.js>angular.controller(countryController, function($scope) {$scope.directory =[{"country_name":"USA","state":"Alaska"},{"country_name":"USA","state":"Colorado"},{"country_name":"USA ","state":"佛罗里达"},{"country_name":"USA","state":"Illinois"},{"country_name":"USA","state":"Louisiana"},{"country_name ":"USA","state":"North Carolina"},{"country_name":"CHINA","state":"SHANGHAI"},{"country_name":"CHINA","state":"BEIJING" },{"country_name":"ITALY","state":"FLORENCE"},{"country_name":"ITALY","state":"PISA"},{"country_name":"INDIA","state":"ASSAM" }]});
我不确定为什么 Controller 不打印 $scope 的值。请让我知道如何纠正这个问题。谢谢