Why the parent area breaks when nesting directives using controllerAs

There are several pages in my web application that have their own controller. Inside these pages I use directives that also have a controller. All controllers use the syntax of controllerAs, and they are all specified as vm. According to this article, this should work. However, I had problems with the fact that it works in conjunction with the directive. In this code, I reproduced a similar situation:

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

In this example, the parent area is also corrupted due to a nested directive. Can someone explain why this is happening or how it can be changed to make it work?

+4
source share
2 answers

You need to isolate your controller with the directory

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";
}

Check the code if you want: http://codepen.io/anon/pen/VeYxQg

Follow this link for more information.

+1
source

When you define var vm = this;inside nestedDirectiveController, the scope is vmlimited only nestedDirectiveController.

Since the directive has an isolated scope, and your template uses this function nestedDirectiveControllerto evaluate the expression, it gets the value title null, and we do not see the name.

, scope : true config . , .

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

. Codepen

0

Source: https://habr.com/ru/post/1619033/


All Articles