为什么使用controllerAs嵌套指令时父级作用域会被破坏?

4
我的Web应用程序有几个页面,它们各自拥有自己的控制器。在这些页面中,我使用指令,这些指令也有一个控制器。所有控制器都使用controllerAs语法,并且它们都设置为vm。根据这篇文章,这应该是可以实现的。然而,我在与指令结合使用时遇到了问题。在这个CodePen中,我重现了一个类似的情况: http://codepen.io/csteur/pen/LGEdLy 在这个例子中,由于嵌套指令,父作用域也被破坏了。有人能解释一下为什么会发生这种情况,或者如何更改才能使其正常工作吗?

它运行良好。问题出在哪里? - Vivek
@VVK 主控制器的vm.title未显示。 - Chantal
2个回答

1
你需要将控制器与目录隔离。
angular.module('app', []);

angular.module('app').controller("MainController", function(){
    var vm = this;
    vm.title = 'AngularJS Nested Controller Example';
});

angular
  .module('app')
  .directive('nestedDirective', function() {
  return {
    restrict: 'E',
    scope: {}, 
    controller: 'nestedDirectiveController',
    controllerAs: 'vm',
    template:'<div> {{vm.message}} </div>'
  };
});

angular
  .module('app')
  .controller('nestedDirectiveController', nestedDirectiveController);

function nestedDirectiveController() {
  var vm = this;
  this.message = "hoi";
}

如果您想查看代码,请访问codepen: http://codepen.io/anon/pen/VeYxQg

请通过此链接获取更多信息


我通过添加 scope: {} 行使其工作。我不太确定你所说的“与目录共享”的意思,但我猜测你提供的链接会解释这个问题。感谢 @Arvaan 的快速回复。 - Chantal

0

当你在nestedDirectiveController内定义var vm = this;时,vm的作用域仅限于nestedDirectiveController

由于您的指令具有隔离作用域,并且您的模板使用此nestedDirectiveController函数来评估表达式,因此它获取标题值null,我们看不到标题。

如果您想要共享作用域,则可以在指令中提供scope:true配置。这样,指令将获得其自己的作用域,该作用域从父作用域原型继承。

angular
  .module('app')
  .directive('nestedDirective', function() {
  return {
    restrict: 'E',
    scope: true, 
    controller: 'nestedDirectiveController',
    controllerAs: 'vm',
    template:'<div> {{vm.message}} </div>'
  };
});

查看 Codepen


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接