AngularJS shows the value of the model if the model is not zero

advertisements

Simple question here. I have this watch:

// Watch our model
$scope.$watch(function () {

    // Watch our team name
    return self.model.team.data.name;
}, function (name) {

    console.log(name);

    // if we have a name
    if (name) {

        // Store our model in the session
        sessionStorage.designer = angular.toJson(self.model);
    }
});

The team model is pull in from the database as a promise (hence the data) so when the watch first fires self.model.team has not been set so it is null. How can I get my watch to either wait until it has been set or add a check into the return function of the watch?


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.