javascript – 为什么在使用controllerAs嵌套指令时,父作用域会中断

我的Web应用程序有几个页面,他们有自己的控制器.在这些页面中,我使用了也有控制器的指令.所有控制器都使用controllerAs语法,它们都设置为vm.根据 this文章,这应该工作.但是,我无法将其与指令结合使用.在这个codepen中,我重现了类似的情况:

http://codepen.io/csteur/pen/LGEdLy

在此示例中,由于嵌套指令,父作用域也被破坏.任何人都可以解释为什么会发生这种情况或者如何更改它以使其工作?

最佳答案 您需要使用目录隔离控制器

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

有关更多信息,请参阅此link

点赞