我在我的範圍中有以下數據模型。使用ng-repeat對象數組中的另一個對象的id屬性通過id查找對象
$scope.staff = [
{"id": "1","name": "Alex"},
{"id": "2","name": "Brad"},
{"id": "3","name": "Cam"}
];
$scope.closedShop =[
{"day": "monday","staffID": "1"},
{"day": "wednesday","staffID": "2"},
{"day": "thursday","staffID": "3"},
{"day": "friday","staffID": "1"}
];
我想要做的是輸出哪個員工每天關閉店鋪,所以基於上面我的理想輸出會是。
亞歷週一收盤
店布拉德關閉了店鋪週三
凸輪關閉了商店在週四
亞歷關閉了店上週五
我遇到的問題是closedShop數據只包含staffID,我怎麼能根據staff.id數據來查看這個人的姓名?
但是,我有一個下面的工作示例,這不是一個可擴展的解決方案,對於少數員工?
'use strict';
var app = angular.module('app', []);
app.controller('MainCtrl', ['$scope', function ($scope) {
$scope.staff = [
{"id": "1","name": "Alex"},
{"id": "2","name": "Brad"},
{"id": "3","name": "Cam"}
];
$scope.closedShop =[
{"day": "monday","staffID": "1"},
{"day": "wednesday","staffID": "2"},
{"day": "thursday","staffID": "3"},
{"day": "friday","staffID": "1"}
];
}]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app">
<div ng-controller="MainCtrl">
<div ng-repeat="closed in closedShop">
<span ng-if="staff[0].id==closed.staffID">{{staff[0].name}}</span>
<span ng-if="staff[1].id==closed.staffID">{{staff[1].name}}</span>
<span ng-if="staff[2].id==closed.staffID">{{staff[2].name}}</span>
closed the shop on {{closed.day}}
</div>
</div>
</div>
什麼是得到這個工作的最佳方式?
一種可能的解決辦法是改變你的員工的模型是一個對象的關鍵是工作人員的ID。這將成爲$ scope.staff = {1:{name:「Alex」}等),然後在你的循環中,你可以簡單地通過執行員工[closed.staffId] .name來檢索員工。這也消除了額外的循環來查找數組內正確的工作人員的必要性,因爲您可以在地圖中進行直接查找。 – 2015-02-24 07:31:30