私はAngularを初めて使用します。私がやりたいのは、ページ上のオブジェクトの配列からのデータを表示し、ユーザーが次/前の配列項目に移動するためのボタンを提供することです。
配列が次のようになっているとしましょう。
var destinations = [
{
name: "Rome",
weather: "sunny",
price: "$2999"
},
{
name: "Paris",
weather: "cloudy",
price: "$4500"
}
];
HTMLで表示したい場合は、書くことができ{{destinations[1].name}}
、機能しますが、これを動的にするにはどうすればよいですか?i
コントローラで変数を定義[i]
してHTMLディレクティブに挿入しようとしましたが、機能しません。
どうすればこれを機能させることができますか?
スコープのメンバーを使用して、現在のアイテムを表します。
<div data-ng-app="exampleModule" data-ng-controller="exampleController">
<div>
<button data-ng-click="changeDestination(1)">
Next
</button>
<button data-ng-click="changeDestination(-1)">
Prev
</button>
</div>
<div class="dest-container">
<div class="dest-field dest-price-field">
<div class="dest-title">Price:</div>
<div class="dest-content">{{ current.price }}</div>
</div>
<div class="dest-field dest-name-field">
<div class="dest-title">Name:</div>
<div class="dest-content">{{ current.name }}</div>
</div>
<div class="dest-field dest-weather-field">
<div class="dest-title">Weather:</div>
<div class="dest-content">{{ current.weather }}</div>
</div>
</div>
</div>
これにより、を表示する1つのディスプレイが作成されます$scope.current
。
宛先配列を使用して最小限の完全な例を作成しました。
(function(angular) {
"use strict";
var exampleModule = angular.module('exampleModule', []);
exampleModule.controller('exampleController', ['$scope', function($scope) {
$scope.destinations = [
{
name: "Rome",
weather: "sunny",
price: "$2999"
},
{
name: "Paris",
weather: "cloudy",
price: "$4500"
}
];
$scope.currentItem = 0;
$scope.current = $scope.destinations[$scope.currentItem];
$scope.changeDestination = function(diff) {
$scope.currentItem += diff;
if ($scope.destinations.length) {
while ($scope.currentItem >= $scope.destinations.length)
$scope.currentItem -= $scope.destinations.length;
while ($scope.currentItem < 0)
$scope.currentItem += $scope.destinations.length;
} else {
$scope.currentItem = 0;
}
$scope.current = $scope.destinations[$scope.currentItem];
};
}]);
}(angular));
このページは、JavaScriptコードを実行する前にAngularJS1.4.8をロードします。
同じことがアイテムの範囲にも使用できます。配列をスライスして配列を設定し、ページ付けを実装するためにアイテムを表示する$scope.current
ために使用できますng-repeat
。
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加