【问题标题】:angular render model one by one角度渲染模型一一
【发布时间】:2015-05-19 12:36:02
【问题描述】:

假设我有一个带有汽车列表的 JSON:

{
  "company": "Mercedes",
  "cars": 
  [{
    "idCar": 1,
    "Name": car 1,
    "img":"..."
  },{
    "idCar": 2,
    "Name": car 2,
    "img":"..."
  },{
    "idCar": 3,
    "Name": car 3,
    "img":"..."
  },{
    "idCar": 4,
    "Name": car 4,
    "img":"..."
  },{
    "idCar": 5,
    "Name": car 5,
    "img":"..."
  }]
}

我正在做一个 Angular 应用程序,用户可以按一个按钮来显示这些汽车,但用户一次只能看到一辆车,当他看完这辆车的规格后,他可以点击 “next”按钮,应该显示下一辆车等等。

现在您可能会注意到,我是 Angular 的初学者,我想知道是否有办法做到这一点。

提前谢谢你。

【问题讨论】:

  • 您的 JSON 似乎有误。如果是字符串,则名称字段值应该用引号引起来

标签: angularjs views render


【解决方案1】:

这是一个非常基本的 Angular 问题。这应该会让你朝着正确的方向前进:

app.controller("MyCtrl", ["$scope", function ($scope) {

    $scope.company = {
        company: "Mercedes",
        cars: [
            { "idCar": 1, "Name": "car 1", "img": "http://lorempixel.com/200/200" },
            { "idCar": 2, "Name": "car 2", "img": "http://lorempixel.com/200/200" },
            { "idCar": 3, "Name": "car 3", "img": "http://lorempixel.com/200/200" },
            { "idCar": 4, "Name": "car 4", "img": "http://lorempixel.com/200/200" },
            { "idCar": 5, "Name": "car 5", "img": "http://lorempixel.com/200/200" }
        ]
    };

    $scope.currentIndex = 0;
    $scope.currentCar = $scope.company.cars[$scope.currentIndex];

    $scope.nextCar = function() {
        $scope.currentIndex++;

        if ($scope.currentIndex >= $scope.company.cars.length) {
            $scope.currentIndex = 0;   
        }

        $scope.currentCar = $scope.company.cars[$scope.currentIndex];
    }
}]);

查看:

<div>
    <h1>{{ currentCar.Name }}</h1>
    <img ng-src="{{ currentCar.img }}" />
</div>
<button ng-click="nextCar()">Next</button>

示例:jsfiddle

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-08-17
  • 1970-01-01
  • 2010-12-06
  • 2017-10-25
相关资源
最近更新 更多