如何在指令中混合和匹配局部变量和导入变量



在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" />

问题:我注意到,如果我使用隔离方法…我不能再使用我的指令定义的变量在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)来自外部作用域。你在link中定义的作用域属性是内部的,会应用到指令的模板中。所以很明显,外部作用域无法查看内部和隔离作用域的属性。

为你的指令创建一个模板,并在其中应用ng-class。

template: '<div ng-class="{active:directiveDefinedVar}">...</div>'

如果我使用

.directive('directiveName', [function () {
    return {
        restrict: 'EA',
        scope: {
            parentScopeVar: '='
        },
        template: '<div data-ng-class="{focused: hasFocus}">blabla</div>',
        controller: function($scope, $element, $attrs){
             $scope.hasFocus = false;
              $scope.onFocus = function () {
                 $scope.hasFocus = true;
              }
        .....
        }

最新更新