Reputation: 1505
I have a custom directive and when a function is defined as an attribute I want to show the button that executes that function. So if the on-delete is defined show the delete button. if the on-delete is not defined don't show the button.
I am having trouble finding out if a function is defined as an attribute.
Here is what I am trying but it always has showAdd and showDelete set to true. I have a custom directive like this:
<my-custom-directive on-add="addItem();"></my-custom-directive>
javascript is something like
app.directive('myCustomDirective', function() {
var myCustomDirectiveCtrl = ['$scope', function ($scope) {
$scope.showAdd = (typeof($scope.onAdd) !== 'undefined');
$scope.showDelete = (typeof($scope.onDelete) !== 'undefined');
}];
return {
restrict: 'E',
scope: {
onAdd: '&',
onDelete: '&',
},
controller: myCustomDirectiveCtrl,
templateUrl: 'myCustomDirective.html'
};
});
and the directive template is something like
<button ng-show="showAdd">Add</button>
<button ng-show="showDelete">Delete</button>
What am I doing wrong? Is there a better way of doing this?
Upvotes: 1
Views: 650
Reputation: 19193
Since you declared onAdd
and onDelete
as expression bindings in your directive (&
), $scope.onAdd
and $scope.onDelete
will always exist as they are declared as parsing functions. When executed, they will parse and evaluate whatever expression is passed in the HTML. When it is empty, they will simply return nothing.
An easy way to solve this is to simply check if your directive contains the on-add
/ on-delete
attributes or not. You do that using the $attrs
dependency:
var myCustomDirectiveCtrl = ['$scope', '$attrs', function ($scope, $attrs) {
$scope.showAdd = $attrs.onAdd;
$scope.showDelete = $attrs.onDelete;
}];
Upvotes: 2