Issue
I've got a simple contactList component, which has 2 bindings: contacts and onRemove.
contactsis just an array of contacts to displayonRemoveis a callback function
app
.component('contactList', {
template:
`<div ng-repeat="c in $ctrl.contacts">
{{c.name}}
<div ng-click="$ctrl.onRemove({contact: c})">Remove</div>
</div>`,
bindings: {
contacts: '<',
onRemove: '&'
},
controller: function() {}
})
I use this component multiple times within my app. And the onRemove callback can behave differently, depending on where the contactList component is getting used. Example:
contactMainView(= component) displays a search bar and the resulting list of contacts using thecontactListcomponent.onRemovewill delete the contact from the database.groupMembersViewdisplays all contacts belonging to the given group using thecontactListcomponent. Here it shouldn't be possible to remove a contact, thoughonRemovewill not be set.
Ideas:
First I thought, that I could use an ng-if="$ctrl.onRemove" but that doesn't work, because onRemove is never undefined within contactList component. console.log(this.onRemove) always prints: function(locals) { return parentGet(scope, locals); }
Of course I could use another showRemove: '@' binding, but that doesn't look DRY to me.
Do you have any idea or some better solution to get things done?
Solution
The simplest way would to check if the attribute is defined. In your controller inject $attrs and then you can do:
if( $attrs.onRemove ) { //Do something }
Using the & binding angular will wrap the function in order to keep references to the original $scope of the passed method, even if is not defined.
Answered By - Sebastian Sebald
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.