pandaseal pandaseal - 5 months ago 17
AngularJS Question

How to return AND and OR logical operators JavaScript

I have a really long one line if-statement in an ng-if in my html. It got too long so I want to make a function evaluate it instead.

My problem is that I cant get my head around how to "convert" an && or an || to nested if-statements that i could have in an function. Could someone, a bit wiser than me, help me out?

Here is the logic i want to convert to nested if-statements (I indented it to get what I was doing):

ng-if="(
(
(filter === 'critical')
||
(
!(
(filter === 'status')
||
(filter === 'events')
)
&&
(
(
!(door.status_error_array.length >= 1)
&&
(door.event_array.length >= 1)
)
||
(
!(door.status_error_array.length >= 1)
&&
!(door.event_array.length >= 1)
)
)
)
)
&&
(door.critical_error_array.length >= 1)
)"

Answer

Move this logic to a controller. Only very simple expressions should go into the view.

EDIT

The first step would be a simple copy-paste, if you are using the $scope rather than controllerAs syntax you will need to prepend this.$scope that in the expression otherwise just this:

YourController.$inject = ['$scope'];
function YourController($scope) {
    this.$scope = $scope;
}

YourController.prototype.testExpresstion = function() {
    return (
  (
    (this.$scope.filter === 'critical') 
||
(
  !(
    (this.$scope.filter === 'status')
    ||
    (this.$scope.filter === 'events')
  )
  &&
  (
    (
      !(this.$scope.door.status_error_array.length >= 1)
      &&
      (this.$scope.door.event_array.length >= 1)
    )
    ||
    (
      !(this.$scope.door.status_error_array.length >= 1)
      &&
      !(this.$scope.door.event_array.length >= 1)
    )
  )
    )
      )
      &&
      (this.$scope.door.critical_error_array.length >= 1)
    )

}

Your view would just simply be something like:

<div ng-if="testExpression()"> 

Of course don't call it testExpression. Give it a contextual name based on what it does.

Once you have that working, write a unit test for this method. Then refactor this method and move each condition into its own method until it becomes clear to any developer what this is supposed to do.

Comments