无范围指令 - 如何获取数据?

时间:2015-02-06 15:01:55

标签: angularjs

我正在使用无范围指令(https://github.com/johnpapa/angularjs-styleguide#directives-and-controlleras)。

<directive1>
    <directive2></directive2>
</directive2>

directive1外{我} controllerAS: 'vm'内有var vm=this; vm.test="test from directive1"

内部directive2scope: false, controllerAs: 'vm2', bindToController:true 如何从directive2获取directive1 vm.test数据?我想在控制器中使用它 - 而不是HTML视图

1 个答案:

答案 0 :(得分:0)

你想用

做什么
var vm = this

是指令1的JS范围的局部变量(不是角度范围的$ scope对象)。 Directive2永远无法访问它。要提供访问权限,您必须将vm附加到指令范围。然后,嵌套指令2的$ scope。

可以访问它

在指令一中就像这样

$scope.vm = this; // This will work
$scope.vm.test = 'test from directive1 scope';

在指令二中就像这样

controller: function ($scope) {
  console.log($scope.vm.test) // this will work for you

这是一个有效的jsFiddle示例。

working jsFiddle example