I'm having some trouble with nested directives in angularjs. I want to call a controller method from a directive within another directive and am trying to pass arguments to it, however they are undefined.
I'm attempting to call remove() with three arguments from selected.html below. It was working before I introduced a parent directive (televisionFilter.js) Can anyone suggest what to do to pass these to the controller?
Thanks!
Code:
controller.js
$scope.remove = function(selectorToRemove, choicesArr, selectedArr){
console.log(selectorToRemove); //undefined
console.log(choicesArr); //undefined
console.log(selectedArr); //undefined
};
televisionFilter.js
angular.module('app.directives').directive('televisionFilter', function(){
return{
restrict: 'A',
templateUrl: 'js/templates/television-filter.html',
scope: {
search: '=',
selectedBrand: '=',
submit: '&',
remove: '&'
}
};
});
selected.js
angular.module('app.directives').directive('selected', function(){
return{
restrict: 'A',
templateUrl: 'js/templates/selected.html',
scope:{
choicesArr: '=',
selectedArr: '=',
remove: '&'
}
};
});
list.html
<div television-filter search='televisionSearch' submit="submit()" selected-brand='selectedBrand' remove='remove(selectorToRemove, choicesArr, selectedArr)'></div>
television-filter.html
<div selected selected-arr='search.selectedBrands' choices-arr='search.brands' remove='remove(selectorToRemove, choicesArr, selectedArr)'>
selected.html
<ul>
<li ng-repeat="selected in selectedArr" class="filter-autocomplete-list" ng-click="remove({selectorToRemove:selected, choicesArr:choicesArr,selectedArr:selectedArr})">
<span class="label label-default label-text">{{selected}}</span>
</li>
</ul>
The answers suggested in the comments by @charlietfl and @angular_james, although working, exhibit bad angular practice. Calling $parent violates the point of your isolated scope (&). To get it working, you just have to modify the of the middle directive (television-filter.html) as follows:
<div selected selected-arr='search.selectedBrands' choices-arr='search.brands' remove='remove({selectorToRemove: selectorToRemove, choicesArr: choicesArr, selectedArr: selectedArr})'>
Updated plunkr
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