Nested directives – cannot pass args to controller method from child directive in Angularjs

All we need is an easy explanation of the problem, so here it is.

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>

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

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

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply