在 angular.js 中,指令可以像这样使用在其父范围内定义的所有变量:
.directive('directiveName', ()->
scope: true
类似地,一个指令可以简单地忽略它的父作用域并像这样定义它自己的作用域
.directive('directiveName', ()->
scope: false
此外,指令可以选择将它希望使用的特定变量从其父作用域中“隔离”出来,如下所示:
.directive('directiveName', ()->
scope:
parentScopeVar1: '='
localVarAliasOfParentVar2: '=parentVar2'
这里的问题是这些独立的变量必须像这样在指令的 html 语法中声明:
<directiveName parent-scope-var-1="parentScopeVar1" parent-var-2="parentVar2" />
问题: 我注意到如果我使用 isolate 方法..我不能再在 html 中使用我的指令定义的变量,例如假设我有
.directive('directiveName', ()->
scope:
parentScopeVar1: '='
..
link: (scope, elem, attrs) ->
scope.directiveDefinedVar = true
在 html 中:
<directiveName ng-class="{active:directiveDefinedVar}" /> <!-- This doesn't work! it used to work when I had scope: false -->
知道为什么会这样吗?
我能解决这个问题的唯一方法是将 parentScopeVar1 的值持久化到服务中......然后在我的指令主体中设置一个观察者,如下所示:
.directive('directiveName', 'parentScopeVar1Cache',(parentScopeVar1Cache)->
..
link: (scope, elem, attrs) ->
scope.parentScopeVar1Cache = parentScopeVar1Cache
scope.$watch 'parentScopeVar1Cache', (newValue)->
# do stuff with newValue
但我发现该解决方案太脏了..我想像我的前三个示例一样简单地从范围定义中做到这一点..
最佳答案
应用于元素的属性(通过 ng-class
)来自外部作用域。您在链接中定义的范围属性是内部的,并应用于指令的模板。所以显然外部作用域无法查看内部和隔离作用域的属性。
不要这样做,而是为您的指令创建一个模板并在那里应用 ng-class。
template: '<div ng-class="{active:directiveDefinedVar}">...</div>'
关于javascript - 如何在指令中混合和匹配局部变量和导入变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24680012/