【问题标题】:Angular Directives with External Controller带有外部控制器的 Angular 指令
【发布时间】: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


【解决方案1】:

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

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

您上面的示例控制器,我认为是用于“require”(所需指令的控制器)。

【讨论】:

  • 你能不能给我看个plunker什么的。我知道它应该。
【解决方案2】:

我用传统的javascript试过了,没有问题,所以最好检查一下浏览器控制台,看看你的代码是否有运行时错误。

【讨论】:

  • 我当然一直在检查控制台,如果是这样的话,我会包括任何相关的错误
猜你喜欢
  • 2017-07-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-02-06
  • 2018-04-22
  • 2016-06-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多