我是Node.js和anguler.js的新手我想使用angular.js将JSON输出显示到网页。 我angular.js代码是在Node.js的文件从node.js文件运行angular.js
test.js
var pg = require('/data /node_modules/pg');
var serverAddress = localhost';
var serverPort = '1337';
var conString = "tcp://myuser:[email protected]/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视图页面的源代码看起来名单this--
保持简单....!{{目录}} 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”, “状态”: “科罗拉多”},{ “COUNTRY_NAME”: “USA”, “状态”: “佛罗里达”},{ “COUNTRY_NAME”: “USA”, “状态”:“伊利诺伊“},{”country_name“:”美国“,”州“,”路易斯安那州“},{”country_name“:”美国“,”州“,”北卡罗来纳州“},{”country_name“:”中国“状态 “:” 上海 “},{” COUNTRY_NAME “:” 中国 “ ”状态“: ”北京“},{ ”COUNTRY_NAME“: ”意大利“, ”状态“: ”翡冷翠“},{ ”COUNTRY_NAME“:”意大利”, “状态”: “PISA”},{ “COUNTRY_NAME”: “印”, “状态”: “ASSAM”}]});
我不知道为什么Controller没有打印$ scope的值。请让我知道我可以改正这一点。 感谢
工作你不应该使用字符串连接发送的HTML内容。尝试将您的HTML页面作为静态文件进行服务。使用JSON将数据公开为REST服务,然后使用'$ http'服务来加载数据。 –