无法使用胖箭头访问范围

时间:2016-01-15 03:09:00

标签: angularjs angularjs-directive scope coffeescript

我可能遗漏了一些关于范围界定的基本内容。

有人可以解释一下发生了什么以及如何从ngModelController内的外部范围正确访问对象scope.$watch吗?

以下是一个例子:

myDirModule = angular.module("myDir", []) 
.directive "myDir", ($compile) -> 
restrict: "A"
require: "ngModel" 
scope:  
  myParam: "=ngModel" 
compile: (element, attrs) -> 

  // ... more code here ...

  post: (scope, element, attrs, ngModelController) -> 

    // ... more code here ...

    // ngModelController defined here :D

    scope.$watch 'myParam', (newValue, oldValue) =>
      // ngModelController NOT defined here :(

1 个答案:

答案 0 :(得分:0)

将postlink函数直接返回到编译函数:

myDirModule = angular.module("myDir", []) 
.directive "myDir", ($compile) -> 
restrict: "A"
require: "ngModel" 
scope:  
  myParam: "=ngModel" 
compile: (element, attrs) -> 
  # more code here
  # return postlink function directly
  (scope, element, attrs, ngModelController) ->
    console.log(ngModelContoller)

或者将pre和post函数作为哈希值返回

myDirModule = angular.module("myDir", []) 
.directive "myDir", ($compile) -> 
restrict: "A"
require: "ngModel" 
scope:  
  myParam: "=ngModel" 
compile: (element, attrs) -> 
  # more code goes here
  # return pre and post as a hash
  pre: (scope, element, attrs, ngModelController) ->
    console.log(ngModelController)
  post: (scope, element, attrs, ngModelController) ->
    console.log(ngModelContoller)

另请务必使用->,而不是=>