erichardson30 erichardson30 - 4 years ago 113
AngularJS Question

Pass data back to controller from directive

The structure of my code is I have a parent "component" with a list component inside of that. I want to click edit on an item inside the list component and have that item be passed back to a function in the parent component. The parameter inside the editMember function is being passed back as null

let ParentDirective = () => {
"use strict";
return {
restrict: 'A',
scope: {
visible: '<',
members: '='
},
template: (() => {
return `
<div>
<div list-directive
members="members"
edit="methods.editMember(member)">
</div>
</div>
`;
})(),
controller: ($scope) => {
$scope.methods = {
editMember: (member) => {
console.log(member) //member is null
}
};
}
}
};

export default {directive: ParentDirective, name: 'parent'};



let ListDirective = () => {
"use strict";
return {
restrict: 'A',
scope: {
members: '<',
editMember: '&edit'
},
template: (() => {
return `
<div>

<div ng-repeat="member in members">
{{member.name}}
<button type="button"
ng-click="editMember(member)">
<i class="ion-edit"></i>
</button>
</div>
</div>

</div>
`;
})(),
controller: ($scope) => {
}
}
};

export default {directive: ListDirective, name: 'list'};

Answer Source

Your best bet is to use EventEmitter to interact between child and parent components in case you are using Angular 2.

Have a look at here for more info on how to do it.

If you are using Angular 1 you're on the write track, just change ng-click="editMember(member)" to ng-click="editMember({member: member})" since you need to pass it as a hash:

<button type="button"
    ng-click="editMember({member: member})">
    <i class="ion-edit"></i>
</button>

Note that you need to call it whatever you named your argument in the parent, e.g. if you defined your parent like this:

edit="methods.editMember(temp)"

Then you should pass it like:

<button type="button"
    ng-click="editMember({temp: member})">
    <i class="ion-edit"></i>
</button>
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download