0

我是 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 的值。请让我知道如何纠正这个问题。谢谢

4

1 回答 1

0

这是我看到的几件事:

  • 您缺少ng-app实际引导 Angular 应用程序的属性
  • angular.controller()不是 API 的一部分。我认为您正在尝试使用Module.controller(),但您必须首先引用可能创建的模块angular.module()
  • 在您尝试定义控制器的内联<script/>块中,您应该使用字符串文字作为控制器名称,例如“countryController”。您现在拥有的是一个未定义的变量......所以它会评估为undefined.
  • 此外,您需要在<table ng-controller="countryController">标签中添加一些引号(它们不在上面)。

Soo...在你让这个小样本工作之前你还有一些工作要做:-)

于 2013-08-16T19:41:08.550 回答