带外部控制器的角度指令

时间:2014-08-27 00:30:30

标签: angularjs angularjs-directive

我正在关注创建指令的博文:http://joelhooks.com/blog/2014/02/11/lets-make-full-ass-angularjs-directives/

他似乎建议将控制器与指令分开。但是,试图在链接函数中从外部控制器运行函数导致undefined不是函数。

控制器

wrmcControllers.controller 'voteCtrl', ($scope,$attrs) ->
   this.hasVoted = false
   this.init = ->
     if this.hasVoted
       #scope.vote = Vote.get(scope.vote)
     else
       this.vote = null

   this.voteUp = ->
     if this.vote == true
       this.vote = null
     else
       this.vote = true
       this.hasVoted = true

   this.voteDown = ->
     if this.vote == false
       this.vote = null
     else
       this.vote = false
       this.hasVoted = true

指令

 wrmcDirectives.directive 'voteSet', ->
   restrict: 'AE'
   scope: {}
   controller: 'voteCtrl'
   templateUrl: 'vote.html'
   link: (scope,element,attrs,controller) ->
     console.log controller
     controller.init()

Console.log控制器输出

function () {
      if (this.vote === false) {
        return this.vote = null;
      } else {
        this.vote = false;
        return this.hasVoted = true;
      }
    }

2 个答案:

答案 0 :(得分:6)

我认为你可以做(​​你试试,我不确定):)

{
   controller:....,
   controllerAs: "myctrl",
   link : function($scope) {
        $scope.myctrl.init()
   }
}

上面的示例控制器,我认为是"要求" (所需指令的控制者)。

答案 1 :(得分:0)

我尝试使用传统的javascript,没有问题,所以最好检查一下broswer控制台,看看你的代码是否有任何运行时错误。