【问题标题】:Get Json into a web angular page让 Json 进入网页 Angular 页面
【发布时间】:2014-10-03 03:27:13
【问题描述】:

我正在为我的项目使用 Total.js 框架。我正在关注这个示例https://github.com/totaljs/examples/tree/master/angularjs-mongodb-rest-resources 我想做的是获取一个 json 列表并在 angularjs 网页中打印出来。我从数据库中正确获得了 json 列表。我得到的是浏览器上原始格式的 json 列表打印。我会在 html 文件中打印出来。这是控制器:

exports.install = function(framework) {
    framework.route('/', view_app);
};

function view_app() {

    var self = this;
    var Car = MODEL('car').Schema;

    Car.find({}, {_id:0, brand:1}, function(err, docs){

        if(err)
            self.view500(err);

        self.json(docs)
    }); 
}

我不知道如何将 json 文件绑定到 angularjs 网页。我已经按照示例进行了操作,但没有成功

【问题讨论】:

  • 你能给我们看一个你的AngularJS视图和控制器的例子吗?加载后,可以像 JS 对象一样操作 JSON。

标签: javascript json angularjs mongoose total.js


【解决方案1】:

您必须使用controller.view('my-view-name', docs) 而不是controller.json(docs),因为 json 将序列化对象返回到 JSON 中,而视图返回 HTML。谢谢。

exports.install = function(framework) {
    framework.route('/', view_app);
};

function view_app() {

    var self = this;
    var Car = MODEL('car').Schema;

    Car.find({}, {_id:0, brand:1}, function(err, docs){

        if(err)
            self.throw500(err);
        else
            self.view('my-view-name', docs)
    }); 
}

【讨论】:

    【解决方案2】:

    我不确定您究竟想如何执行此操作,但本质上您只想获取您的JSON 值,将其分配给$scope 变量并使用标准绑定将其附加到您的页面。

    您需要在 angularjs 控制器中获取您的文档数据,这意味着您可以访问$scope。然后只需执行以下操作:$scope.docs = docs(假设这是您要显示的数据)。希望您已经像这样(或类似)定义了您的控制器:

    angular.module('myapp', [])
    .controller('MyController', ['$scope', function($scope) {
    //get your data...
    
    //bind your data:
    $scope.docs = docs;
    

    从那里,您将它绑定到您的 html,如下所示:

    <body ng-app="myapp" ng-controller="MyController">
    <span>{{docs}}</span>
    ....
    

    让我知道这是/不是你想要做的。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-07-07
      • 1970-01-01
      • 1970-01-01
      • 2018-02-08
      • 2020-07-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多