Filter ng-repeat by a property in the current scope

49 views Asked by At

I have tried the following (in a template loaded by a directive):

<li ng-repeat="lang in languages | filter: { Culture: '!{{currentLanguage}}'}">

this is not working, all languages are rendered

<li ng-repeat="lang in languages | filter: { Culture: !currentLanguage}">

this is not working, no languages are rendered

languages has a property 'Culture'. The currentLanguage (in scope) resolves to 'en-CA' (I can see this bound when I view the element in Chrome dev tools). I would expect all languages except for 'en-CA' to be returned. Is this possible without creating a custom filter?

2

There are 2 answers

2
scniro On BEST ANSWER

AngularJS filters accept an expression, whereas you are supplying an interpolated value

In HTML Template Binding

{{ filter_expression | filter : expression : comparator}}

Try changing to the following...

<li ng-repeat="lang in languages | filter: { Culture: !currentLanguage }">

See the AngularJS filter docs for more information


If you need some custom code to resolve this, a more involved solution may include...

<li ng-repeat="lang in languages | filter: languageFilter">{{ lang.name }}</li>

$scope.languages = [{'name': 'en-US'}, {'name': 'en-CA'}]

$scope.currentLanguage = 'en-CA';

$scope.languageFilter = function(language) {
    return language.name != $scope.currentLanguage; // en-US
}

JSFiddle Link - working example

1
Sajeetharan On
<li  ng-repeat="lang in languages | filter:{ Culture: '!en-CA'}" >

or

<li  ng-repeat="lang in languages | filter:{ Culture: !currentLanguage}" >