0
if( angular.isDefined( $scope.user.id ) ){ var data = ({ id : $scope.user.id }) ; }

Produces Error:

TypeError: Cannot read property 'id' of undefined

$scope.user is going to be undefined sometimes - it will only have a value if the user is logged in. I have tried typeOf, === 'undefined' and angular.isDefined / Undefined throughout my code and cannot find a solution that always works when checking a angular property that may be undefined or null.

Thanks for the help I am sure will follow.

Jordan Reddick
  • 456
  • 1
  • 7
  • 16
  • How are you determining what is working and what isn't? What are the values of `$scope.user` that "work" and "don't work" using the methods above? – jraede Jun 06 '14 at 00:18
  • The above code generates an error and stops the rest of my code from executing whenever the value returned by the database is null. the actual use case is an hours of operation object which is nested as settings->hours->day->open->time. I don't want to have to check angular.isDefined(hours) then (days) then (open) to see if a time has been set without stopping my code. My reading of angular.isDefined makes me think it is the function I need - but it is not implementing as I expected at all. – Jordan Reddick Jun 06 '14 at 00:26

1 Answers1

3

Your $scope.user is undefined. check both.

if (angular.isDefined( $scope.user ) && angular.isDefined( $scope.user.id )) { ... }
oori
  • 5,533
  • 1
  • 30
  • 37
  • 1
    So to check something very nested like my hours of operation object at $scope.settings.hours.day.open.time I need to check every item in between ?! Ouch but Thanks. – Jordan Reddick Jun 06 '14 at 00:45
  • 1
    yes, that's nothing to do with Angular, but with Javascript. To stay DRY, you can add a helper `function isDefined(obj,'some.deep.nested.node') { return true/false }` – oori Jun 09 '14 at 00:34
  • 1
    See examples: https://www.google.com/search?q=javascript+function+nested+object+check+if+defined http://stackoverflow.com/questions/2631001/javascript-test-for-existence-of-nested-object-key http://stackoverflow.com/questions/4676223/check-if-object-member-exists-in-nested-object – oori Jun 09 '14 at 00:35