2016-05-23 92 views
2

我有一个接受数组的指令。它最初是未定义的,然后在某个时间点被异步定义。

该指令类似于

function XYZDirective() { 
    return { 
     restrict: 'EA', 
     replace: true, 
     scope: { 
      array: '=' 
     }, 
     controller: ['$scope', $scope => { 
      $scope.$watch(() => $scope.array, (newValue, oldValue) => { 
       $scope.firstElement = (newValue && newValue.length > 0) 
        ? newValue[0] 
        : null; 
      }); 

     }], 

     templateUrl: URL 
    }; 
} 

这工作得很好。我想然后摆脱$watch并使用简单的绑定。

function XYZDirective() { 
    return { 
     restrict: 'EA', 
     replace: true, 
     scope: { 
      array: '=' 
     }, 
     controller: ['$scope', $scope => { 

      $scope.getFirstElement = function() { 
       return ($scope.array && $scope.array.length > 0) ? $scope.array[0] : null; 
      } 

      $scope.firstElement = $scope.getFirstElement(); 
     }], 

     templateUrl: URL 
    }; 
} 

我希望$scope.firstElement得到重新评估每一次$scope.array变化。

然而,这是行不通的。如果我在$scope.array添加一个观察者,我可以看到它被更新,但变化不会传播到$scope.firstElement

回答

2

这是一个声明,这是执行一次

$scope.firstElement = $scope.getFirstElement(); 

然后再也(只如果指令/控制器被破坏的再次渲染)

所以,你应该观察方法

{{getFirstElement()}} 

而且真的会连连触发此检查......还有......再次..所以也许$watch是更好的方式去(例如观看直到首先阵列来了,然后删除表)

相关问题