Search code examples
javascriptangularjsangularjs-filter

AngularJS - check condition on ng-if


I need to show/hide multiple elements if they check a condition like this:

<div id="LineSingleDate" ng-if="VM.PageFeatures.AvailableFields.SafeAny(function(e) { return e.Id == VM.Constants.SingleDate; })"></div>
<div id="LineSpotlight" ng-if="VM.PageFeatures.AvailableFields.SafeAny(function(e) { return e.Id == VM.Constants.InSpotlight; })"></div>
<div id="LineSubtitle" ng-if="VM.PageFeatures.AvailableFields.SafeAny(function(e) { return e.Id == VM.Constants.Subtitle; })"></div>
<div id="LineResumeDescription" ng-if="VM.PageFeatures.AvailableFields.SafeAny(function(e) { return e.Id == VM.Constants.ResumeDescription; })"></div>
<div id="LineLocation" ng-if="VM.PageFeatures.AvailableFields.SafeAny(function(e) { return e.Id == VM.Constants.Location; })"></div>
<div id="LineCoordinatesGPS" ng-if="VM.PageFeatures.AvailableFields.SafeAny(function(e) { return e.Id == VM.Constants.CoordinatesGPS; })"></div>
<!--and 20 more others-->

But it gives me this error for all of those ng-ifs:

angular.js:13920 Error: [$parse:syntax] Syntax Error: Token '{' is unexpected, expecting [)] at column 53 of the expression [VM.PageFeatures.AvailableFields.SafeAny(function(e) { return e.Id == VM.Constants.SingleDate; })] starting at [{ return e.Id == VM.Constants.SingleDate; })].

I already tried to use {} and {{}} bracing the conditions but it always gives me a different error like this previous.

How can I solve this?

NOTE 1: Every variable and function exists and works.

NOTE 2: I don't want to have a variable for each div on my controller.


Solution

  • Maybe refactoring will help:

    HTML

    <div id="LineSingleDate" ng-if="VM.checkAvailability('SingleDate')"></div>
    <div id="LineSpotlight" ng-if="VM.checkAvailability('InSpotlight')"></div>
    

    Controller

    VM.checkAvailability(fieldName) {
        return VM.PageFeatures.AvailableFields.SafeAny(function(e) { return e.Id == VM.Constants[fieldName]; })
    }