【问题标题】:Unable to access scope using fat arrow无法使用粗箭头访问范围
【发布时间】:2016-04-20 14:47:05
【问题描述】:

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

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

这是一个例子:

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 :(

【问题讨论】:

    标签: angularjs angularjs-directive scope coffeescript


    【解决方案1】:

    将postlink函数直接返回给compile函数:

    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)
    

    还要确保使用->,而不是=>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-10-19
      • 1970-01-01
      • 2019-03-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-02-16
      相关资源
      最近更新 更多