【发布时间】:2014-08-27 14:50:39
【问题描述】:
我正在关注这篇博文来创建指令:http://joelhooks.com/blog/2014/02/11/lets-make-full-ass-angularjs-directives/
他似乎建议将控制器与指令分开。但是,尝试在链接函数中从外部控制器运行函数会导致 undefined is not a function。
控制器
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;
}
}
【问题讨论】:
-
init 函数似乎附加到不在控制器实例上的范围...将
$scope.init更改为this.init -
如果你想初始化你的控制器,我建议你应该在你的控制器代码中调用init方法。
-
$scope.init 只是我尝试不同的东西,但我将它切换回 this.init 这对结果没有影响。
-
你的控制器有点奇怪;您的控制台日志输出没有显示整个控制器,而是显示最后一个函数
voteDown,就好像那是整个对象一样。 -
我不是 CoffeeScript 专家,但我认为这不是角度问题,而是 CoffeeScript 中的编译问题。尝试将控制器编写为传统的 JavaScript 元素并验证其功能,然后尝试确定您的 CoffeeScript 版本出现错误的原因。
标签: angularjs angularjs-directive