2016-05-23 7 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が良い方法です(例:最初に配列が来るまで見てから時計を外す)