2016-07-05 81 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