Reputation: 345
I currently have two lists which are being compared. One displays a list of colors and the other is a list of names that have chosen a specific color. This is simple to display. An example fiddle can be found here: https://jsfiddle.net/37dq96tj/
<div ng-repeat="eachColor in colors">
{{eachColor.name}} Selected By: ->
<span ng-repeat="eachName in names" ng-if="eachName.catid == eachColor.id">
{{eachName.name}}
</span>
</div>
The problem I am facing which I thought would be easy to do, would be to display the word "none" if no name is listed for that color. I thought I could do it this way which works if only one name is in the 2nd list. See: https://jsfiddle.net/37dq96tj/2
{{eachColor.name}} Selected By: ->
<span ng-repeat="eachName in names">
<span ng-if="eachName.catid == eachColor.id">{{eachName.name}}</span>
<span ng-if="eachName.catid != eachColor.id">NONE</span>
</span>
But if I add another name, this will not work. I'll end up getting duplicates "NONE" values. See: https://jsfiddle.net/37dq96tj/4
This seems simple, but I haven't figured it out. Hoping someone can point me in the right direction.
Also, another question I'd definitely like to know is using nested ng-repeats this way is the ideal way to display this type of data?
Thanks! T
Upvotes: 0
Views: 666
Reputation: 171669
Instead of using ng-if
can use a filter on the array that will match the id's.
The filter lets you create an alias for this filtered array which you can then check for length to show "none"
<span ng-repeat="eachName in names | filter: {'catid': eachColor.id} as filteredNames">
{{eachName.name}}
</span>
<span ng-if="!filteredNames.length">None</span>
Upvotes: 1
Reputation: 1152
Try it like this
<div ng-app="appX" ng-controller="appCtrl">
<h5>COLORS</h5>
<div ng-repeat="eachColor in colors">
{{eachColor.name}} Selected By: ->
<span ng-repeat="name in colorSelectedByUsers(eachColor)">{{ name }}</span>
</div>
</div>
I have created a function colorSelectedByUsers(color)
that returns array of users or array with single string of "None"
var app = angular.module("appX", []);
app.controller("appCtrl", function($scope) {
$scope.colors = [{
"id": 0,
"name": "Red"
}, {
"id": 1,
"name": "Blue"
}, {
"id": 2,
"name": "Green"
}];
$scope.names = [{
"id": 0,
"catid": 2,
"name": "Jim"
},
{ "id": 1,
"catid": 1,
"name": "Frank"
}]
$scope.colorSelectedByUsers = function(color){
var users = [];
for(var u in $scope.names){
if($scope.names[u].catid == color.id){
users.push($scope.names[u].name);
}
}
if(users.length == 0){
users.push("None");
}
return users;
}
});
Upvotes: 0