-3

I'm trying to figure out the best way to take a json object which I'm storing as a scope, and filter/query it to display specific data from within it.

For example:

$scope.myBook = {"bookName": "Whatever",
    "pages": [
        {"pageid": 1, "pageBody": "html content for the page", "pageTitle": "Page 1"},
        {"pageid": 2, "pageBody": "html content for the page", "pageTitle": "Page 2"},
        {"pageid": 3, "pageBody": "html content for the page", "pageTitle": "Page 3"},
    ]
}

How would I go about grabbing the object for pageid:2 ?

||||||
  • You mean grabbing the pageBody for pageid: 2 ? – ForgetfulFellow Jul 21 '14 at 0:25
  • Use for() to find the necessary page, then use foundPage.pageBody – zerkms Jul 21 '14 at 0:29
0

I ended up asking the AngularJS IRC - And one of the guys put this plunker together with exactly what I was looking for.

Plnkr Example

Props to https://github.com/robwormald for the answer.

/* See PLNKR Link Above for the answer */
||||||
0
function getPage (id) {
    angular.forEach($scope.myBook.pages, function (page, pageIndex) {
        if (page.pageId == id) {
            console.log("Do something here.");
            return page;
        }
    });
}

Otherwise . . .

$scope.myBook.pages[1];
||||||
1

You can use this approach:

template:

<div ng-repeat="page in myBook.pages | filter:pageMatch(pageid)">
    {{ page.pageBody }}
</div>

scope:

$scope.pageMatch = function(pageid) {
    return function(page) {
        return page.pageid === pageid;
    };
};

Set pageid to needed value in filter:pageMatch(pageid) to display necessary page content.

||||||

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.