【问题标题】:AngularJS : Interpolating attributesAngularJS:插值属性
【发布时间】:2014-05-13 08:05:08
【问题描述】:

假设我有以下两个指令:

angular.module('foo').directive('outer', [function(){
  return {
    restrict: 'E',
    scope: {
      inner: '@',
      innneParams: '@'
    },
    template: "<div {{inner}}{{innerParams}}></div>",
    link: function(scope, elem, attrs){
      console.debug("I AM IN YOUR OUTER DIRECTIVE PASSING YOUR D00DZ!")
    }
  }

}]);
angular.module('foo').directive('innerDir', [function(){
  return {
    restrict: 'EA',
    scope: {
      innerParam: '='
    },
    template: "<div>{{massagedInner}}</div>",
    link: function(scope, elem, attrs){
      console.debug('I AM IN YOUR INNER DIRECTIVE MASSAGING YOUR D00DS!')
      scope.massagedInner = scope.innerParam + "FROM YOUR DOGE!"
    }
  }
}]);

还有以下 HTML:

<outer inner="inner-dir" my-awesome-scope-value="myAwesomeScopeValue" inner-params="inner-param='myAwesomeScopeValue'"></outer>

外部指令控制台调试触发,内部没有。我有什么好的方法来实现这种行为吗?

Plunk:http://plnkr.co/edit/jXbtWvYvtFXCTWiIZUDW?p=preview

【问题讨论】:

  • 您尝试将指令用作属性(内部属性),但您将其限制为 E(仅限元素)。您还需要将内部指令限制为属性:EA,比方说。您在这里还有一个结尾的单引号拼写错误:my-awesome-scope-value="myAwesomeScopeValue'
  • 这些都是问题,但是内部参数仍然没有绑定....更新了 plunk/question 以解决您的问题
  • 我认为你不能在同一个元素上定义一个模板两次。你有外部和内部都在竞争这样做。您还两次请求隔离范围。内部看起来应该是一个元素指令,但我不清楚你的目标是什么。
  • 除了充满拼写错误(有时参数名称是inneParams 有时是innerParam 有时是innerParams)我认为您正在解决兄弟作用域的问题;也就是说,内部和外部实际上在范围层次结构中是并排的,而不是像这里假设的那样嵌套......我会验证这一点。
  • 我为这些错误道歉。我已经把它们清理干净了

标签: javascript angularjs angularjs-directive angularjs-compile


【解决方案1】:

你做错了很多事情。我已经做出了我认为接近您想要的更改,您可以从这里更改代码。

Here's a working version

这就是script.js 现在的样子;

angular.module('foo', []);
angular.module('foo').controller('fooController', ['$scope', function(scope){
  scope.myAwesomeScopeValue = 'O HAI THERE'  
}]);
angular.module('foo').directive('outer', [function(){
  return {
    restrict: 'E',
    scope: {
      // inner: '@',
      // innnerParams: '@'
      innerParam: '@'
    },
    template: "<div inner {{inner}} {{inner-param}}></div>",
    link: function (scope) {
      console.log('OUTER', scope.innerParam);
    }
  }

}]);
angular.module('foo').directive('inner', [function(){
  return {
    restrict: 'A',
    // scope: {
    //   innerParam: '='
    // },
    replace: false,
    template: "<div>{{massagedInner}}</div>",
    link: function(scope, elem, attrs){
      scope.massagedInner = scope.innerParam + "FROM YOUR DOGE!"
      console.log('INNER');
    }
  }
}]);

为简洁起见,我已将您的一些行注释掉。我希望这会有所帮助。

【讨论】:

  • 这并没有真正做到我想要的,因为内部指令是无条件应用的,而不是从父作用域传递的
  • AFAIK,还没有办法有条件地应用指令。条件必须高于指令; ngIf 可能会有所帮助,但当然,它必须在指令中而不是在指令中。这里的想法是表明您不需要隔离所有指令的范围 - 特别是当您有两个或多个指令在同一个元素上工作时。子指令很有可能使用父作用域——在这种情况下,inner 指令使用outer 的作用域,如果replace: false 则反过来可以使用父作用域。 docs.angularjs.org/api/ng/directive/ngIf
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-11-28
  • 1970-01-01
  • 2015-10-25
  • 2014-08-31
  • 2013-09-03
  • 1970-01-01
  • 2021-11-24
相关资源
最近更新 更多