我可能遗漏了一些关于范围界定的基本内容。
有人可以解释一下发生了什么以及如何从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 :(
答案 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)
另请务必使用->
,而不是=>