简体   繁体   中英

angularjs best practices - communication between directives without $rootScope?

So I have a nested directive that I need to communicate with a separate directive on the page (same controller). I tried the isolate scope approach but given how nested the first directive is, I abandoned that approach. I'm writing this code keeping in mind that $scope might not be around in 2.0. Is there an alternative solution to my approach that would fit with Angular Best practices?

Inside nested directive (3 levels deep):

$scope.chooseCard = function (selectedId) {
  this.data = 'init value';
  $rootScope.$emit('row chosen', selectedId);
  this.data = selectedId;
};

Inside directive #2 that needs data from the nested directive:

$rootScope.$on('row chosen', function (e, data) {
  ctrl.id = data;
  console.log("this is the IDDDDDD", ctrl.id);
  Service.func(ctrl.id);
});

$scope might not be around, but bindings sure will. You have two main options:

  1. Use a service and set this piece of data on there, then watch it in the child directive. This will work, but I do feel like it harms composition and re-use since you can no longer have multiple instances of the directive (they would all depend on the singleton service).

  2. Use an isolate scope as you mentioned earlier and then watch the binding using an '&' expression. This will be the closest you're going to get to Angular2 without using something like ngForward since the flow of data from parent -> child is still the primary method of data-binding in Angular2. This is the preferred way to accomplish this imo even if it ends up being more verbose.

No matter what solution you choose, make sure that you don't leak memory; if you don't unbind that $rootScope.$on handler, then you will leak memory every time that an instance of the directive is created and subsequently destroyed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM