Reputation: 1449
my response is like this :
$scope.users = [{
name: 'joseph',
queue:[
{number:'111',status:'Paused'},
{number:'345',status:'Not In Use'},
{number:'342',status:'Not In Use'}],
}];
In my view I set the class as paused if the queue array in reponse contains status = Paused at any index. I think the way I'm doing it below is not the proper way as just in case the queue array contains more than 3 objects then my code won't assign the class properly. Here is my code :
<div ng-repeat="user in users>
<span class="badges badges-lg" ng-class="{'paused': user.queue[0].status === 'Paused' || user.queue[1].status === 'Paused' || user.queue[2].status === 'Paused'}">111</span>
</div>
I want a solution such that apply the class paused only if the status corresponding to the "number":"111"
in queue array is Paused.
I mean instead of user.queue[0].status === 'Paused' || user.queue[1].status === 'Paused' || user.queue[2].status === 'Paused'
I just want a single line of code to check status corresponding to the "number":"111" in queue array is Paused.
How do I do it?
Upvotes: 0
Views: 36
Reputation: 30739
You can call a controller function in ng-class
to dynamically check the condition and return the class you need:
var app = angular.module('myApp', []);
app.controller('MainCtrl', ['$scope', function($scope) {
$scope.users = [{
name: 'joseph',
queue: [{
number: '111',
status: 'Paused'
},
{
number: '345',
status: 'Not In Use'
},
{
number: '342',
status: 'Not In Use'
}
],
}];
$scope.checkPaused = function(user) {
var isPaused = user.queue.find(({
number
}) => number === '111');
if(isPaused){
return 'paused'
}
}
}]);
.paused{
color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="MainCtrl">
<div ng-repeat="user in users">
<span class="badges badges-lg" ng-class="checkPaused(user)">111</span>
</div>
</div>
Upvotes: 1