I am trying to send the data to directive link function from controller when i used ng-clicked
, but I failed to send the data to directive, the directive is calling when the page was loading at first time
<h2 ng-click="clickMe(somedata)"> click </h2>
<my-directive my-key="myVal"> </my-directive>
.controller('myController',function($scope){
$scope.clickMe=function(somedata){
$scope.myVal=somedata;
};
});
.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
}
}
});
You can pass data through services or you can use $rootScope
for that, but using root scope is bad practice. So, use services. There should be more ways to do that, but services are pretty good.
Here is the clear example for passing data via services: AngularJS Service Passing Data Between Controllers
And another one 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, it's true only for parent-child controllers.
But you can do the same things with $rootScope
like $rootScope.$emit
and $rootScope.$broadcast
. If you will use it, it doesn't matter anymore, how controllers relate to each other (this is true for "brothers" controllers too).
This article should help you: https://toddmotto.com/all-about-angulars-emit-broadcast-on-publish-subscribing/
I hope it 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
}
}
});
Since the controller is inside the directive on an isolate scope, its functions are not available to the parent scope. 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
Life-Cycle Hook1
directiveApp.controller('myController',function(){
this.$onChanges = function(changesObj) {
if (changesObj.myKey) {
var val = changesObj.myKey.currentValue;
console.log(val);
};
};
});
For more information, see AngularJS Comprehensive Directive API - Life-Cycle Hooks
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With