角度渲染模型一个接一个

时间:2015-05-19 12:36:02

标签: angularjs views render

假设我有一个带有汽车列表的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应用程序,用户可以按下按钮来显示这些车,但用户一次只能看到一辆车,当他看完这辆车的规格时,他可以点击“下一步”按钮,应显示下一辆车,依此类推。

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

提前谢谢。

1 个答案:

答案 0 :(得分:4)

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

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

相关问题