How can I get data from the controller to the directive when I click

I am trying to send data of a directive link function from a controller when I used ng-clicked , but I was unable to send data to a directive, the directive calls when the page first loads

here is my html code

  <h2 ng-click="clickMe(somedata)"> click </h2> <my-directive my-key="myVal"> </my-directive> 

here is my controller

 .controller('myController',function($scope){ $scope.clickMe=function(somedata){ $scope.myVal=somedata; }; }); 

my directive

 .directive('myDirective',function(){ return{ restrict:'E', scope:{ myKey:'=' }, templateUrl:'exampleTempl.html', controller:'myController', link:function(scope,elem,attr){ console.log(scope.myKey); // getting undefined console.log(scope.myVal); //here i want the data from controller when i clicked on ng-click } } }); 
+5
source share
3 answers

You can transfer data through services or use $rootScope for this, but using the root area is bad practice. So, use the services. There should be more ways to do this, but the services are very good.

Here is a clear example for transferring data through services: AngularJS service Transferring data between controllers

And one more for $ rootScope: How to pass an object using $ rootScope?

Updated:

You can also pass data through parent-child controllers via $scope.$emit and $scope.$broadcast , but remember that this is true only for parent-child controllers.

But you can do the same with $rootScope like $rootScope.$emit and $rootScope.$broadcast . If you use it, it does not matter how the controllers are connected to each other (this is also true for the "brothers").

This article should help you: https://toddmotto.com/all-about-angulars-emit-broadcast-on-publish-subscribing/

+3
source

I hope this works for you;

 .directive('myDirective',function(){ return{ restrict:'E', scope:{ myKey:'=bindingmyVal' }, templateUrl:'exampleTempl.html', controller:'myController', link:function(scope,elem,attr){ console.log(scope.myKey); //here i want the data from controller when i clicked on ng-click } } }); 
+2
source

Since the controller is located inside the directive in the selection area, its functions are not available for the parent area. Set the variable directly:

 <!-- REPLACE <h2 ng-click="clickMe(somedata)"> click </h2> --> <!-- WITH --> <h2 ng-click="myVal = somedata"> click </h2> <my-directive my-key="myVal"> </my-directive> 

In the directive controller use the $onChanges Hook 1

 directiveApp.controller('myController',function(){ this.$onChanges = function(changesObj) { if (changesObj.myKey) { var val = changesObj.myKey.currentValue; console.log(val); }; }; }); 

For more information, see AngularJS Wide-Interface API - Lifecycle Hooks

+1
source

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


All Articles