2016-07-05 83 views
1

我對angularjs有點新。我正在寫一個指令,但我不明白bindToController如何運行。我閱讀這篇有用的文章http://blog.thoughtram.io/angularjs/2015/01/02/exploring-angular-1.3-bindToController.html,但我不明白爲什麼在下面的例子中我沒有定義。指令綁定undefined

.directive('firstDirective', function(){ 
    return { 
     restrict: 'E', 
     replace: true, 
     scope: true, 
     bindToController: { 
      directiveInput:'=' 
     }, 
     templateUrl: 'components/directive-tree/directive-tree.html', 
     controllerAs: 'directiveTreeCtrl', 
     controller: function($scope, $uibModal){ 
      var self = this; 
      self.selected = null; 
      console.log(self.directiveInput); //HERE IS THE UNDEFINED 
      $scope.modalOptions = { 
       windowClass: 'semi-modal', 
      } 

      this.openDirectiveModal = function(object, index) { 
       //Other irrelevant code 
      } 
     } 
    } 
}); 

之後,我可以使用沒有任何問題的HTML模板的輸入。

<ul> 
    <li ng-repeat="object in directiveTreeCtrl.directiveInput"> 
     {{object.Id}}&emsp;{{object.Name}} 
    </li> 
</ul> 

爲什麼在HTML模板我可以使用directiveInput和它的實例用正確的價值觀和我的console.log告訴我「未定義」?

也許這是一個愚蠢的問題。謝謝

+1

您需要使用您的指令,像這樣的「<第一指令>'在你的HTML。 [官方角度指令文檔](https://docs.angularjs.org/guide/directive)更完整 –

+0

@TomShen我正確使用它。唯一的疑問就是爲什麼我在console.log()中得到一個未定義的對象,並且我可以在我的html中使用該對象,當我呈現它時 – acostela

回答

1

通常的代碼我寫來實現這看起來像這樣:

.directive('firstDirective', function(){ 
    return { 
     restrict: 'E', 
     replace: true, 
     scope: { 
      directiveInput:'=' 
     }, 
     bindToController: true, 
     templateUrl: 'components/directive-tree/directive-tree.html', 
     controllerAs: 'directiveTreeCtrl', 
     controller: function($scope, $uibModal){ 
      var self = this; 
      self.selected = null; 
      console.log(self.directiveInput); //HERE IS THE UNDEFINED 
      $scope.modalOptions = { 
       windowClass: 'semi-modal', 
      } 

      this.openDirectiveModal = function(object, index) { 
       //Other irrelevant code 
      } 
     } 
    } 
}); 

現在HTML

<first-directive directive-input="inputObject"></first-directive> 
+0

我對如何使用它沒有任何疑問。我的問題是另一個。爲什麼console.log正在打印UNDEFINED,之後HTML正在正確渲染對象。 – acostela