Silvio Troia
Silvio Troia

Reputation: 1459

annidate variable undefined - angular

I have a annidate variable like that.

  $scope.a = { b: {c : 1} };
  var test = $scope.a.b.c;
      // test == 1
  $scope.a = {}
  var test = $scope.a.b.c;
      // ERROR

I want test variable will be null or undefined.

How can I fill test variable without error?

some advice?

I'm looking for a smart way

not only

if(angular.isDefinied($scope.a) && angular.isDefinied($scope.a.b) && angular.isDefinied($scope.a.b.c))

Upvotes: 1

Views: 40

Answers (2)

Ram_T
Ram_T

Reputation: 8484

If you are not defined the value before using it, then definitely, it will throw an error. You must define or you must check whether it is defined or not. Otherwise you can't resolve the error. var test will get a value only if there is no error. Now, its up to you to decide and use a smart way

var test = $scope.a?((typeof($scope.a.b)=="object" && $scope.a.b.c)?$scope.a.b.c:(typeof($scope.a)=="object" && $scope.a.b)?$scope.a.b:null):null

Upvotes: 0

codeepic
codeepic

Reputation: 4112

You probably want to do something like that:

var test = ($scope.a && $scope.a.b && $scope.a.b.c) ? $scope.a.b.c : undefined;

Upvotes: 1

Related Questions