There is no magic here - if one of the variables you are accessing could be null
/undefined
, then you cannot get its property if it's null
/undefined
. So, you have to guard against that:
$scope.$watch(
function(){
return (self.model.team && self.model.team.data.name) || undefined;
},
function(v){
// ...
});
The only "magic" is when you "$watch" for expressions, but the expressions need to be exposed on the scope. So, you could do:
$scope.model = self.model;
$scope.$watch("model.team.data.name", function(v){
// ...
});
But, really, you have to ask yourself why you need a $watch
here to begin with. It seems to me that you are getting the team
asynchronously once - it does not look like it will change except by maybe another async call. So, just handle that when you receive the data without the $watch
:
someSvc.getTeam() // I made an assumption about a service that pulls the data from db
.then(function(team){
var name = team.data.name;
// if we have a name
if (name) {
// Store our model in the session
sessionStorage.designer = angular.toJson(self.model);
}
});
An unnecessary $watch
is expensive - it is evaluated on every digest cycle, so, it's best to reduce the number of $watchers.