Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filter in Angular.js by checking against a scope variable

I'm trying to get a certain object out of an array of objects, that meets a certain criteria.

The id of the object should equal the scope variable $scope.lobbyid. My current approach below does not pass the lobby object into the controller.

the selected lobby represents the data of the active tab on the site. so the container array is fetched only once on site load.

markup

<div ng-repeat="lobby in lobbies | filter:checkLobbyID(lobby)">
    [[lobby.name]]
</div>

controller

$scope.checkLobbyID = function($lobby) {
    return $lobby.lobbyid == $scope.lobbyid;
}

array

"lobbies": [
    {
        "isglobal": true,
        "lobbyid": 1,
        "name": "GLOBAL",
    },
    {
        "isglobal": false,
        "lobbyid": 2,
        "name": "stackoverflow rules",
    },
    {
        "isglobal": false,
        "lobbyid": 3,
        "name": "sdadadad",
    }
]

a temporary solution is to add the following code to the tab-switch event. but this needs a copy and another scope variable. how to achieve this with a filter?

angular.forEach($scope.lobbies, function(lobby) {
    if (lobby.lobbyid == $scope.lobbyid)
    $scope.currLobby = angular.copy(lobby);
});
like image 232
Dominik H Avatar asked Oct 19 '25 09:10

Dominik H


1 Answers

You dont need the lobby param in the markup. the filter will implicitly pass it to the scope-filter function

<div ng-repeat="lobby in lobbies | filter:checkLobbyID">

http://jsfiddle.net/vrwQG/

regards

like image 93
kfis Avatar answered Oct 21 '25 23:10

kfis



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!