2015-10-16 52 views
1

模板角指令DOM樹無法訪問控制器最多

<section id="content" ng-controller="ReservationController as resvnCtrl" >    
     <form role="form" name="resvnCtrl.form">  
      <div data-date-picker> 
      </div>  
     </form> 
    </section> 

指令

var eateryDirectives=angular.module('eateryDirectives',['eateryControllers']); 

    eateryDirectives 
      .directive('datePicker',function(){ 
       var directive={ 
        require:'^resvnCtrl', 
        link:function(scope,ele,attrs,cntrl){ 
         console.log(cntrl); 
        } 
       }; 
       return directive; 
      }); 

我控制器找不到錯誤。順便說一句,控制器和diretcive在不同的模塊。這很重要嗎?如何從指令訪問該控制器?

+0

ReservationController在eateryControllers模塊 –

+0

很難說你應該怎麼做,而不知道你的總體目標是什麼,但是你的問題是你試圖以一種無法使用的方式使用指令的'require'。 http://stackoverflow.com/questions/15672709/how-to-require-a-controller-in-an-angularjs-directive – m59

+0

我做了同樣的鏈接 –

回答

2

如果你想要控制器,那麼你應該要求ngController指令。是的,你可以做到這一點,這只是正常的指令畢竟:

require: '^ngController' 

然而,不這樣做,這是完全錯誤的做法。如果你想從這個控制器或方法的一些數據,你應該使用範圍的配置,並通過必要的字段轉換成隔離範圍:

eateryDirectives.directive('datePicker', function() { 
    var directive = { 
     scope: { 
      data: "=", 
      onSelect: "&" 
     }, 
     link: function (scope, ele, attrs, cntrl) { 
      console.log(cntrl); 
     } 
    }; 
    return directive; 
}); 

和HTML:

<section id="content" ng-controller="ReservationController as resvnCtrl" >    
    <form role="form" name="resvnCtrl.form">  
     <div data-date-picker data="resvnCtrl.dates" on-select="resvnCtrl.update()"></div>  
    </form> 
</section> 
+0

哈哈。這說得通!有點明顯,但也有些尷尬。 – m59