概要
ブランドのリストと製品のリストがあります。私は ng-repeat を使用してブランドのリストを表示し、フィルター付きの ng-repeat を使用してそれぞれのブランド内の製品のリストを表示しています。各ブランドと各製品には、そのブランド/製品の詳細を表示するボタンが必要です。これらのボタンはすべて、コントローラーで同じ機能を使用する必要があります。
問題
ブランドの詳細を表示するボタンは、そのブランドの各製品の詳細も表示します (これは私にとって奇妙な部分です) 最初にそのブランド内の製品のボタンをクリックしない限り、正しく機能します。
コード
こちらのプランカーをご覧ください。ブランドの「タイプを表示」をクリックすると、そのブランド内の製品のすべてのタイプも表示されることに注意してください: http://plnkr.co/edit/gFnq3O3f0YYmBAB6dcwe?p=preview
HTML
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="style.css">
<script src="script.js"></script>
</head>
<body>
<div ng-app="myApp">
<div ng-controller="MyController as vm">
<div ng-repeat="brand in brands">
<h1>
{{brand.name}}
</h1>
<button ng-click="showType(brand)">
Show Brand Type
</button>
<div ng-show="show">
{{brand.type}}
</div>
<div ng-repeat="product in products
| filter:filterProducts(brand.name)">
<h2>
{{product.name}}
</h2>
<button ng-click="showType(product)">
Show Product Type
</button>
<div ng-show="show">
{{product.type}}
</div>
</div>
</div>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.3/angular.min.js"></script>
<script src="script.js"></script>
</body>
</html>
ジャバスクリプト
var app = angular.module('myApp', []);
app.controller('MyController', function($scope) {
$scope.brands = [{
name: 'Kewl',
type: 'Cereal'
}, {
name: 'Joku',
type: 'Toy'
}, {
name: 'Loko',
type: 'Couch'
}]
$scope.products = [{
name: 'Kewlio',
type: 'Sugar Cereal',
brand: 'Kewl'
}, {
name: 'Kewliano',
type: 'Healthy Cereal',
brand: 'Kewl'
}, {
name: 'Jokurino',
type: 'Rattle',
brand: 'Joku'
}, {
name: 'Lokonoko',
type: 'Recliner',
brand: 'Loko'
}, {
name: 'Lokoboko',
type: 'Love Seat',
brand: 'Loko'
}]
$scope.showType = function(item) {
this.show = !this.show;
}
$scope.filterProducts = function(brand) {
return function(value) {
if(brand) {
return value.brand === brand;
} else {
return true;
}
}
}
});
重要な注意: オブジェクト (brand.show) に属性を追加してオブジェクトを関数に渡し、その属性を true/false に変更できることはわかっていますが、実際のアプリケーションでは、ボタンには、ブランド/製品を編集して情報を Firebase に送信するフォームが表示されますが、オブジェクトに「表示」属性を持たせたくありません。Firebase で情報を編集するたびに「show」属性を削除する必要はありません。