Method of passing from parent to child directive
I want to pass a method from controller directive -> parent directive -> child. I am calling this method from a child controller passing in arguments. It works in the parent directive, but I cannot pass parameters from the child directive. Below is the code:
http://jsfiddle.net/gurukashyap/e14ff06p/6/
From the parent directive, I get the following response in the console: 'Method Ctrl 123'
From child directive: Ctrl method is undefined.
Any help was appreciated.
<div ng-app="MyApp">
<div ng-controller="MyController">
<container data-method="foo(value)"/>
</div>
</div>
var myApp = angular.module('MyApp', []);
myApp.directive('container', function () {
return {
restrict: 'E',
replace: 'true',
scope: {
methodToCall: '&method'
},
template: "<div>" +
"<button ng-click='finish()'>Parent directive</button><child data-method=\"methodToCall(val) \"></child>" +
"</div>",
link: function (scope, element, attrs) {
scope.paragraphs = [];
scope.pushText = function () {
scope.paragraphs.push(scope.textToPush);
scope.textToPush = "";
}
scope.finish = function () {
scope.methodToCall({value: '123'});
}
}
}
});
myApp.directive('child', function () {
return {
restrict: 'E',
scope : {
methodToCall : '&method'
},
template : '<button ng-click = "newMethod()">Child directive </button>',
controller : function($scope) {
$scope.newMethod = function () {
console.log('Test child '+$scope);
//debugger;
$scope.methodToCall({val : 'Testchild'});
}
}
}
});
myApp.controller('MyController', function ($scope, $window) {
$scope.foo = function (textArray) {
console.log('Ctrl method '+textArray)
};
});
source to share
In your template, container
you are calling the function methodToCall(val)
in scope correctly , but you are only passing it a local variable val
(which, again, you will get from the directive child
). You need to pass the hash, however, just like in the directive child
.
So, change the part of the template container
that includes <child>
:
<child data-method="methodToCall({value: val})"></child>
Perhaps it would be more readable if you called the inner function and from there call the "&"
-bound function :
scope: {
methodToCall: '&method'
},
template: '<child data-method="innerMethodToCall(val)"></child>',
link: function(scope){
scope.innerMethodToCall = function(val){
scope.methodToCall({value: val});
}
}
Your forked jsfiddle
source to share
You have 2 questions:
You had a typo in the child directive where you were submitting val
instead value
. Another problem is that you have created a marquee for the child directive. This broke the whole chain of inheritance. Instead, you need to either not use scoping in the child directive or use scope: true
.
jsfiddle - http://jsfiddle.net/2tw5mxf6/1/
discussion scope: {}
vs. scope:true
- https://groups.google.com/forum/#!topic/angular/7Rnd5RjdlCc
source to share