深入研究Angular中的JSON对象

Drill Down into JSON Object in Angular

本文关键字:对象 JSON 中的 Angular 深入研究      更新时间:2023-09-26

我正在努力找出将我存储的json对象作为作用域的最佳方法,并对其进行过滤/查询以显示其中的特定数据。

例如:

$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"},
    ]
}

如何获取pageid:2的对象?

您可以使用这种方法:

模板:

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

范围:

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

filter:pageMatch(pageid)中将pageid设置为所需值,以显示所需的页面内容。

function getPage (id) {
    angular.forEach($scope.myBook.pages, function (page, pageIndex) {
        if (page.pageId == id) {
            console.log("Do something here.");
            return page;
        }
    });
}

否则。

$scope.myBook.pages[1];

我最终询问了AngularJS IRC,其中一个人把这个plunker和我想要的东西放在了一起。

Plnkr 示例

道具到https://github.com/robwormald寻找答案。

/* See PLNKR Link Above for the answer */