2

这里简单的问题。我有这只手表:

// 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);
    }
});

团队模型是作为一个承诺从数据库中提取的(因此是数据),因此当手表第一次触发时self.model.team尚未设置,因此它为空。我怎样才能让我的手表要么等到它被设置好,要么在手表的返回功能中添加一个检查?

4

2 回答 2

2

使用监视表达式而不是函数。这将捕获丢失对象的任何错误并返回undefined

// Watch our model
$scope.$watch('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);
    }
});
于 2015-04-19T21:55:23.430 回答
1

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.

于 2015-04-20T05:02:18.907 回答