1

I have an object that looks like this

$scope.object = {
  Title: 'A title',
  Status: 'Open',
  Responsible: 'John Doe',
  Author: 'Jane Doe',
  Description: 'lorem ipsum dolor sit'
}

Now I want to see if the current user has permission to edit this item, for the user to be able to edit, the item has to

  • Exist (is not null, undefiend etc)
  • Responsible is equal $scope.currentUser
  • Status is equal 'Open'

if all these are true, our function should return true, I am doing it like this

$scope.isTrue = function(){

  if($scope.object && $scope.object.Status == 'Open' && $scope.object.Responsible == $scope.currentUser){
    return true;
  }else { return false; }

}

Pretty straight forward, but are there a better way to do these kind of checks?

sch
  • 1,368
  • 3
  • 19
  • 35
  • 4
    You don't have to return `true/false`, you can just return everything in the if statement, this itself will already be true or false. so: `return $scope.object && $scope.object.Status == 'Open' && $scope.object.Responsible == $scope.currentUser` – Martijn Welker Mar 31 '16 at 06:59
  • @MartijnWelker that got a whole lot cleaner, thanks! – sch Mar 31 '16 at 07:07

2 Answers2

2

The condition in the if statement is already true or false, you can just return that.

return ($scope.object && $scope.object.Status == 'Open' && $scope.object.Responsible == $scope.currentUser);
KWeiss
  • 2,954
  • 3
  • 21
  • 37
2
  1. Converting the result to Boolean (So, if $scope.object is undefined result is false instead of undefined)
  2. Making comparisons using ===
  3. Just declaring function and assigning it to scope(personal preference)

$scope.isTrue = isTrue;

function isTrue() {
  return Boolean($scope.object && $scope.object.Status === 'Open' && $scope.object.Responsible === $scope.currentUser);
}
Community
  • 1
  • 1
sabithpocker
  • 15,274
  • 1
  • 42
  • 75