1
votes

I am following this blog post in creating directives: http://joelhooks.com/blog/2014/02/11/lets-make-full-ass-angularjs-directives/

He seemed to recommend having the controller seperate from the directive. However trying to run a function from the external controller in the link function results in undefined is not a function.

Controller

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

Directive

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

Console.log controller output

function () {
      if (this.vote === false) {
        return this.vote = null;
      } else {
        this.vote = false;
        return this.hasVoted = true;
      }
    }
2
init function seems to be attached to scope not on the controller instance... Change $scope.init to this.init - PSL
If you want to initialize your controller, I would like to suggest you should call the init method in your controller code itself. - yazaki
the $scope.init was just from me tryin different stuff but I switched it back to this.init this has no effect on the outcome. - Weston Ganger
something seems odd with your controller; your console log output isn't showing the entire controller, rather it is showing the last function voteDown as if that is the entire object. - Claies
I'm no expert with CoffeeScript, but I would think this isn't an angular issue, rather a compile issue within the CoffeeScript. Try writing the controller as a traditional JavaScript element and verify it functions, then try to determine why your CoffeeScript version is coming out mangled. - Claies

2 Answers

6
votes

I think you can do (you try, am not sure) :)

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

Your example controller above, i think is for "require" (the required directive's controller).

0
votes

I tried with traditional javascript, there is no problem, so it is better to check the broswer console to see if any runtime error with you code.