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

喜欢而已 提交于 2019-12-09 06:04:35

问题


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>

回答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



来源:https://stackoverflow.com/questions/19667275/nested-directives-cannot-pass-args-to-controller-method-from-child-directive-i

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!