AngularJS &JSON - 从上一个 & 获取值下一个对象 [英] AngularJS & JSON - Obtain Value from Previous & Next Object

查看:24
本文介绍了AngularJS &JSON - 从上一个 & 获取值下一个对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

背景:我创建了一个 AngularJS 测试应用程序,它从一个 JSON 文件中获取数据,该文件被分成多个类别,每个类别中都有一张通过 ng-repeat 显示的员工卡.然后可以使用滑块(使用 bxSlider)查看这些类别.

目标:使用 bxSlider,您可以使用自定义下一个/上一个按钮,我想要实现的是在下一个/上一个按钮中动态显示相关类别名称(请参阅下面的注释链接 - 我的级别不允许我发布图像).

网站类别滑块线框

例如: 当前查看的类别是技术"部门,上一个按钮可能会显示汽车"部门,下一个按钮可能会显示显示法律"部门.

我了解下面的代码将允许我访问类别名称技术".然而,这需要以动态的方式完成.

{{employees[0].category}}

在此之下,我将包含所有我认为相关的代码.

JSON 文件:

<预><代码>[{"category": "技术","shortname": "技术","icon": "fa-desktop",卡片":[{"id": "card-1","name": "乔治·索弗罗尼欧","shortname": "G_Sof","年龄": "23","company": "Pirean Ltd.","role": "研究生 UI 开发人员"},{"id": "card-2","name": "史蒂夫·乔布斯","shortname": "S_Jobs","age": "56 (已故)","company": "苹果公司",角色":前任CEO"},{"id": "card-3","name": "马克·扎克伯格","shortname": "M_Zuck","年龄": "30","公司": "脸书",角色":CEO"},{"id": "card-4","name": "蒂姆·库克","shortname": "T_Cook","年龄": "54","company": "苹果公司",角色":CEO"},{"id": "card-5","name": "乔尼·艾夫","shortname": "J_Ive","年龄": "48","company": "苹果公司",角色":设计高级副总裁"},{"id": "card-6","name": "玛丽莎梅耶","shortname": "M_May","年龄": "39","company": "雅虎!",角色":CEO"},{"id": "card-7","name": "伊夫·比哈尔","shortname": "Y_Beh","年龄": "47","company": "Fuseproject",角色":创始人"}]},{"category": "电机","shortname": "mot","icon": "fa-car",卡片":[{"name": "埃隆·马斯克","shortname": "E_Musk","年龄": "43","company": "特斯拉汽车",角色":CEO"}]},{"category": "足球","shortname": "脚","icon": "fa-futbol-o",卡片":[{"id": "card-1","name": "亚历克斯·弗格森爵士","shortname": "A_Fer","年龄": "73","公司": "不适用",角色":退休"}]},{"类别": "法律","shortname": "法律","icon": "fa-gavel",卡片":[{"id": "card-1","name": "哈维幽灵","shortname": "H_Spec","年龄": "43","company": "Pearson Spectre Litt","role": "名称合作伙伴"}]}]

HTML 代码:

<div class="slider-container"><!-- 搜索内容--><!-- 控制:真--><div class="content-results bxslider"bx-slider="mode: 'horizo​​ntal', pager: true, nextSelector: '#next', prevSelector: '#prev', nextText: '<i class=\'fa fa-chevron-right\'><;/i>', prevText: '<i class=\'fa fa-chevron-left\'></i>', minSlides: 1, maxSlides:1, infiniteLoop: true,adaptiveHeight: true, hideControlOnEnd: 假"><!-- 员工--><div class="cards-container"ng-repeat="过滤后的项目 = (员工 | 过滤器: 查询 | orderBy:empOrder:direction )"通知重复完成><div class="category" ng-animate="'animate'" ><div class="category-title"><h1 class="title-cat"><i class="fa {{item.icon}}"></i>&nbsp;{{ item.category }}</h1>

<div class="category-cards-container"><div class="employee-card card" ng-repeat="employee in Filtered = (item.cards | filter: query | orderBy:empOrder:direction )" dom-manipulation><!-- 前卡--><div class="front"><div class="pic-container"><img ng-src="../static/images/placeholders/{{employee.shortname }}.jpg" class="emp-pic" alt="{{employee.name }}的照片"><h3 class="emp-name">{{employee.name }}</h3><div class="变暗"></div>

<ul class="emp-details"><li class="detail emp-age"><h5>年龄:<small>{{employee.age }}</small></h5><li class="detail emp-role"><h5>角色:<br><small>{{employee.role }}</small></h5><li class="detail emp-company"><h5>公司:<br><small>{{employee.company }}</small></h5>

<!-- 结束前卡--><!-- 背卡--><div class="back"><div id="地图加载"><i class="fa fa-map-marker"></i>

<div id="maps-container"><div id="googleMap"></div>

<i class="fa fa-times"></i>

<!-- END Back Card -->

<!-- 没有匹配项--><div class="no-match" ng-show="filtered.length == 0"><h3 class="no-matchText">您的搜索未提供匹配项!</h3>

<!-- END 没有匹配项-->

<!-- 结束员工-->

<!-- 结束搜索内容--><!-- 下一个 &上一个按钮 --><div class="btn-nextprev"><div class="next-container"><a href="" class="btn btn-next" id="next"></a>

<div class="prev-container"><a href="" class="btn btn-prev" id="prev"></a>

<!-- END Next &上一个按钮 -->

<!-- END 滑块容器 -->

AngularJS:

控制器

var personControllers = angular.module('personControllers', ['ngAnimate']);//人员搜索控制器personControllers.controller('PersonList', ['$scope', '$http',函数($scope,$http){$http.get('../static/scripts/data2.json').成功(功能(数据){console.log("加载了 JSON 文件");控制台日志(数据);$scope.employees = 数据;//$scope.empOrder = 'name';}).错误(功能(){console.log("JSON 文件未加载");});}]);

编辑更新的控制器

var personControllers = angular.module('personControllers', ['ngAnimate']);//人员搜索控制器personControllers.controller('PersonList', ['$scope', '$http',函数($scope,$http){$http.get('../static/scripts/data2.json').成功(功能(数据){console.log("加载了 JSON 文件");控制台日志(数据);$scope.employees = 数据;//$scope.empOrder = 'name';//下一个&上一个按钮类别标签$scope.getNextCategoryIndex = function(currentIndex){var nextIndex = currentIndex+1;if( nextIndex >= $scope.employees.length ){//如果在列表末尾则移动到开始下一个索引 = 0;}返回下一个索引;}$scope.getPrevCategoryIndex = function(currentIndex){var prevIndex = currentIndex+1;如果(上一个索引 <0 ){//移动到最后一个索引,如果已经在开始prevIndex = $scope.employees.length - 1;}返回上一个索引;}}).错误(功能(){console.log("JSON 文件未加载");});}]);

更新下一个/上一个按钮

<div class="btn-nextprev"><div class="next-container"><a href="" class="btn btn-next" id="next">{{员工[getNextCategoryIndex($index)].category }}</a>

<div class="prev-container"><a href="" class="btn btn-prev" id="prev">{{ 员工[getPrevCategoryIndex($index)].category }}</a>

<!-- END Next &上一个按钮 -->

解决方案

我可能会这样做:为控制器创建函数以获取上一个和下一个索引(以处理索引溢出):

$scope.getNextCategoryIndex = function(currentIndex) {var nextIndex = currentIndex+1;if (nextIndex >= $scope.employees.length) {//如果我们已经在列表的末尾,则移到开始下一个索引 = 0;}返回下一个索引;}$scope.getPrevCategoryIndex = function(currentIndex) {var prevIndex = currentIndex+1;如果(上一个索引<0){//移动到最后一个索引,如果我们已经在开始prevIndex = $scope.employees.length - 1;}返回上一个索引;}

然后在 HTML 中使用 $index(ng-repeat 的当前索引,参见 ngRepeat 的 AngularJS 文档 以获取更多详细信息)作为参数:

 <!-- Next &上一个按钮 --><div class="btn-nextprev"><div class="next-container"><a href="" class="btn btn-next" id="next">{{员工[getNextCategoryIndex($index)].category}}</a>

<div class="prev-container"><a href="" class="btn btn-prev" id="prev">{{员工[getPrevCategoryIndex($index)].category}}</a>

<!-- END Next &上一个按钮 -->

Background: I have created an AngularJS test app which, obtains data from a JSON file, which is separated into categories and within each category is an employee card which is displayed through ng-repeat. These categories can then be viewed utilising a slider (using bxSlider).

Aim: With bxSlider you can use custom Next/Previous buttons, what I wanted to achieve was to dynamically display the relevant category names in the Next/Previous buttons (please see annotation link below - my level does not allow me to post images).

Website Category Slider Wireframe

For example: the current category on view is the 'Technology' department, the previous button may then show 'Motors' department and the next button may show 'Law' department.

I understand that the code below would allow me to access the Category name 'Technology'. However this needs to be done in a dynamic nature.

{{employees[0].category}}

Below this I will include all what I believe to be relevant code.

JSON file:

[
  {
    "category": "Technology",
    "shortname": "tech",
    "icon": "fa-desktop",
    "cards": [
      {
        "id": "card-1",
        "name": "George Sofroniou",
        "shortname": "G_Sof",
        "age": "23",
        "company": "Pirean Ltd.",
        "role": "Graduate UI Developer"
      },
      {
        "id": "card-2",
        "name": "Steve Jobs",
        "shortname": "S_Jobs",
        "age": "56 (Died)",
        "company": "Apple Inc.",
        "role": "Former CEO"
      },
      {
        "id": "card-3",
        "name": "Mark Zuckerberg",
        "shortname": "M_Zuck",
        "age": "30",
        "company": "Facebook",
        "role": "CEO"
      },
      {
        "id": "card-4",
        "name": "Tim Cook",
        "shortname": "T_Cook",
        "age": "54",
        "company": "Apple Inc.",
        "role": "CEO"
      },
      {
        "id": "card-5",
        "name": "Jony Ive",
        "shortname": "J_Ive",
        "age": "48",
        "company": "Apple Inc.",
        "role": "Senior Vice President of Design"
      },
      {
        "id": "card-6",
        "name": "Marissa Mayer",
        "shortname": "M_May",
        "age": "39",
        "company": "Yahoo!",
        "role": "CEO"
      },
      {
        "id": "card-7",
        "name": "Yves Behar",
        "shortname": "Y_Beh",
        "age": "47",
        "company": "Fuseproject",
        "role": "Founder"
      }
    ]
  },
  {
    "category": "Motors",
    "shortname": "mot",
    "icon": "fa-car",
    "cards": [
      {
        "name": "Elon Musk",
        "shortname": "E_Musk",
        "age": "43",
        "company": "Tesla Motors",
        "role": "CEO"
      }
    ]
  },
  {
    "category": "Football",
    "shortname": "foot",
    "icon": "fa-futbol-o",
    "cards": [
      {
        "id": "card-1",
        "name": "Sir Alex Ferguson",
        "shortname": "A_Fer",
        "age": "73",
        "company": "N/A",
        "role": "Retired"
      }
    ]
  },
  {
    "category": "Law",
    "shortname": "law",
    "icon": "fa-gavel",
    "cards": [
      {
        "id": "card-1",
        "name": "Harvey Specter",
        "shortname": "H_Spec",
        "age": "43",
        "company": "Pearson Specter Litt",
        "role": "Name Partner"
      }
    ]
  }
]

HTML Code:

<!-- Slider Container -->
    <div class="slider-container">
        <!-- Search Content  -->
        <!-- controls: true -->
        <div class="content-results bxslider" 
        bx-slider="mode: 'horizontal', pager: true, nextSelector: '#next', prevSelector: '#prev', nextText: '<i class=\'fa fa-chevron-right\'></i>', prevText: '<i class=\'fa fa-chevron-left\'></i>', minSlides: 1, maxSlides:1, infiniteLoop: true, adaptiveHeight: true, hideControlOnEnd: false">
            <!-- Employee -->
            <div class="cards-container" 
            ng-repeat="item in filtered = ( employees | filter: query | orderBy:empOrder:direction )"
            notify-repeat-finished>
                <div class="category" ng-animate="'animate'" >
                    <div class="category-title">
                        <h1 class="title-cat"><i class="fa {{item.icon}}"></i>&nbsp;{{ item.category }}</h1>
                    </div>
                    <div class="category-cards-container">
                        <div class="employee-card card" ng-repeat="employee in filtered = (item.cards | filter: query | orderBy:empOrder:direction )" dom-manipulation>
                            <!-- Front Card -->
                            <div class="front">
                                <div class="pic-container">
                                    <img ng-src="../static/images/placeholders/{{ employee.shortname }}.jpg" class="emp-pic" alt="Photo of {{ employee.name }}">
                                    <h3 class="emp-name">{{ employee.name }}</h3>
                                <div class="darken"></div>
                                </div>
                                <ul class="emp-details">
                                    <li class="detail emp-age">
                                        <h5>Age: <small>{{ employee.age }}</small></h5>
                                    </li>
                                    <li class="detail emp-role">
                                        <h5>Role: <br><small>{{ employee.role }}</small></h5>
                                    </li>
                                    <li class="detail emp-company">
                                        <h5>Company: <br><small>{{ employee.company }}</small></h5>
                                    </li>
                                </ul>
                            </div>
                            <!-- END Front Card -->
                            <!-- Back Card -->
                            <div class="back">
                                <div id="map-load">
                                    <i class="fa fa-map-marker"></i>
                                </div>
                                <div id="maps-container">
                                    <div id="googleMap"></div>
                                </div>
                                <i class="fa fa-times"></i>
                            </div>
                            <!-- END Back Card -->
                        </div>
                    </div>
                </div>
                <!-- No Matches -->
                <div class="no-match" ng-show="filtered.length == 0">
                    <h3 class="no-matchText">Your search provides no matches!</h3>
                </div>
                <!-- END No Matches -->
            </div>
            <!-- END Employee -->
        </div>
        <!-- END Search Content  -->
        <!-- Next & Previous Buttons -->
        <div class="btn-nextprev">
            <div class="next-container">
                <a href="" class="btn btn-next" id="next">
                </a>
            </div>
            <div class="prev-container">
                <a href="" class="btn btn-prev" id="prev">
                </a>
            </div>
        </div>
        <!-- END Next & Previous Buttons -->
    </div>
    <!-- END Slider Container -->

AngularJS:

Controller

var personControllers = angular.module('personControllers', ['ngAnimate']);

//PersonSearch Controller
personControllers.controller('PersonList', ['$scope', '$http', 
function($scope, $http) {

    $http.get('../static/scripts/data2.json').
    success(function(data) {
        console.log("JSON file loaded");
        console.log(data);
        $scope.employees = data;
        //$scope.empOrder = 'name';
    }).
    error(function(){
        console.log("JSON file NOT loaded");
    });

}]);

EDIT Updated Controller

var personControllers = angular.module('personControllers', ['ngAnimate']);

//PersonSearch Controller
personControllers.controller('PersonList', ['$scope', '$http', 
function($scope, $http) {

    $http.get('../static/scripts/data2.json').
    success(function(data) {
        console.log("JSON file loaded");
        console.log(data);
        $scope.employees = data;
        //$scope.empOrder = 'name';

        //Next & Previous Button Category Label
        $scope.getNextCategoryIndex = function(currentIndex){
            var nextIndex = currentIndex+1;
            if( nextIndex >= $scope.employees.length ){
                //move to start if at list end
                nextIndex = 0;
            }
            return nextIndex;
        }

        $scope.getPrevCategoryIndex = function(currentIndex){
            var prevIndex = currentIndex+1;
            if( prevIndex < 0 ){
                //move to the last index, if already at the start
                prevIndex = $scope.employees.length - 1;
            }
            return prevIndex;
        }

    }).
    error(function(){
        console.log("JSON file NOT loaded");
    });

}]);

Updated Next/Previous Buttons

<!-- Next & Previous Buttons -->
        <div class="btn-nextprev">
            <div class="next-container">
                <a href="" class="btn btn-next" id="next"> 
                    {{ employees[getNextCategoryIndex($index)].category }}
                </a>
            </div>
            <div class="prev-container">
                <a href="" class="btn btn-prev" id="prev">
                    {{ employees[getPrevCategoryIndex($index)].category }}
                </a>
            </div>
        </div>
        <!-- END Next & Previous Buttons -->

解决方案

I would probably do something like this: create functions to your controller to get the previous and next indexes (to handle the index overflows):

$scope.getNextCategoryIndex = function(currentIndex) {
  var nextIndex = currentIndex+1;
  if (nextIndex >= $scope.employees.length) {
    // move over to start if we already were at the end of the list
    nextIndex = 0;
  }
  return nextIndex;
}

$scope.getPrevCategoryIndex = function(currentIndex) {
  var prevIndex = currentIndex+1;
  if (prevIndex < 0) {
    // move over to the last index, if we already are at the start
    prevIndex = $scope.employees.length - 1;
  }
  return prevIndex;
}

And then in the HTML call those functions using $index (the current index of ng-repeat, see AngularJS documentation for ngRepeat for more details) as parameter:

    <!-- Next & Previous Buttons -->
    <div class="btn-nextprev">
        <div class="next-container">
            <a href="" class="btn btn-next" id="next">
                {{employees[getNextCategoryIndex($index)].category}}
            </a>
        </div>
        <div class="prev-container">
            <a href="" class="btn btn-prev" id="prev">
                {{employees[getPrevCategoryIndex($index)].category}}
            </a>
        </div>
    </div>
    <!-- END Next & Previous Buttons -->

这篇关于AngularJS &amp;JSON - 从上一个 &amp; 获取值下一个对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
前端开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆