Daniele Martini Daniele Martini - 2 months ago 9
AngularJS Question

Angular JS, importing some specifics data from a JSON file

I’m trying to make an angular JS app that displays notes.
All the notes are stored in a note.json file and the main page of the app shows just fews fields of all the notes.
I would like to add the feature that open a new page if I click on a particular note.
The new page should displays all the data referred to the clicked note.

I have a show.html file which is the template of the note selected, and a notes-show-controller.js which, when I click a note on the main page, should import just some specific data from the note.json file.
Here the code of the two file:

show.html

<div class="col-sm-12">
<p>{{note.title}}</p>
<p>Created By: {{note.user}}</p>

<p>Description:</p>
<p>{{note.description}}</p>

<p>Contents:</p>
<p>{{note.content}}</p>
</div>


notes-show-controller.js

angular.module('NotesApp').controller('NotesShowController', function($http, $routeParams) {
var controller = this;
controller.notes = [];


$http.get('notes/'+ $routeParams.id).success(function(data){
controller.notes = data;
})
});


My question is: is it possible to import from the json file, which is an array of object, just few fields of a particular object? and if not, how can I solve my problem?
Here is the notes.json file

[
{
"id": 1,
"users":"Fabio",
"title":"questa è la prima nota",
"description": "blablablablablablablabla",
"content":"èoisèdoifjèosijdfèosjdfèoijsèdofij"
},
{
"id": 2,
"users":"Francesco",
"title":"questa è la seconda nota",
"description": "huhuhuuhuhuhuhuuhuuhuhuh",
"content":"èoisèdoifjèosijdfèosjdfèoijsèdofij"
},
{
"id": 3,
"users":"Fernando",
"title":"questa è la terza nota",
"description": "cicicicicicicicicicicici",
"content":"èoisèdoifjèosijdfèosjdfèoijsèdofij"
}
]


If it help to solve my problem, I've also made a Plunker file that shows all the app, here is the link:

Plunker File

Thanks in advance to anyone who can help me.

Answer

All your data is in the JSON file.. Based on that I have updated the NotesShowController to find() the $http.get() response and show the information on the Show view.

Working Plunker:

NotesShowController:

angular
    .module('NotesApp')
    .controller('NotesShowController', ['$http', '$routeParams', function ($http, $routeParams) {
        var controller = this;
        controller.note = {};

        $http.get('notes.json').success(function (data) {
            controller.note = data.find(function (n) {
                return n.id == $routeParams.id;
            });
        });
    }]);

Show view:

<div class="col-sm-12">
    <p>{{showController.note.title}}</p>
    <p>Created By: {{showController.note.users}}</p>

    <p>Description:</p>
    <p>{{showController.note.description}}</p>

    <p>Contents:</p>
    <p>{{showController.note.content}}</p>
</div>
Comments