Get Json into a web angular page

148 Views Asked by At

I'm using Total.js framework for my project. I'm following this example https://github.com/totaljs/examples/tree/master/angularjs-mongodb-rest-resources What I'd like to do is to take a json list and print out in angularjs web page. I get correctly the json list from the db. What I get is the json list print in the raw format on the browser. I would print out it in the html file. This is the controller:

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)
    }); 
}

I don't know how to bind the json file to the the angularjs web page. I have followed the example but It didn't worked

2

There are 2 best solutions below

0
On

I'm not sure exactly how you want to do this, but essentially you want to simply take your JSON value, assign it to a $scope variable and use standard binding to attach it to your page.

You will need to obtain your docs data inside an angularjs controller, which means you'll have access to $scope. Then just do something like this: $scope.docs = docs (assuming this is the data you want to show). Hopefully you have already defined your controller like this(or similar):

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

//bind your data:
$scope.docs = docs;

From there, you bind it to your html like this:

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

Let me know if this is/is not what you were trying to do.

0
On

you must use controller.view('my-view-name', docs) instead of controller.json(docs) because json returns a serialized object into the JSON and view returns HTML. Thanks.

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)
    }); 
}