两个指令共享同一个控制器

red*_*ead 9 angularjs angularjs-directive

有以下指令

function directive() {
    return {
        template: '{{foo.name}}',
        controller: ctrl,
        controllerAs: 'foo'
    }
}

function ctrl($attrs) {
    this.name = $attrs.name;
}
Run Code Online (Sandbox Code Playgroud)

这在模板中:

<directive name="1" />
<directive name="2" />
Run Code Online (Sandbox Code Playgroud)

为什么我看到以下输出:

2
2
Run Code Online (Sandbox Code Playgroud)

代替

1
2
Run Code Online (Sandbox Code Playgroud)

Joy*_*Joy 15

该选项controllerAs: 'foo'执行以下操作:

$scope.foo = new ctrl()
Run Code Online (Sandbox Code Playgroud)

您的指令未指定scope,这意味着您的指令使用其parent($parentScope)中的作用域.在您的情况下,两个指令实例使用相同的父作用域.所以这两个指令:

<directive name="1" />
<directive name="2" />
Run Code Online (Sandbox Code Playgroud)

工作如下:

  1. <directive name="1" />:$parentScope.foo = new ctrl().控制器内部:$parentScope.foo.name = 1.
  2. <directive name="2" />:$parentScope.foo = new ctrl().(将覆盖步骤1中的实例).控制器内部:$parentScope.foo.name = 2.

所以最后两个指令都引用name了第二个控制器实例上定义的相同指令.

解决方案:使用隔离范围作为@Michelem提及.

  • 很好地解释了为什么需要隔离范围,而不仅仅是需要隔离范围 (2认同)