2

I have a custom angular directive that accepts two function parameters, addElement and removeElement:

.directive('myDirective', ['$window', function () {
        return {
            restrict: 'E',
            replace: true,
            scope: {
                addElement: '&',
                removeElement: '&'
            },
            templateUrl: window.root + 'myDirectiveHtml.html'
        };
    }])

I cannot figure out how to set these two attributes conditionally outside the directive and how to conditionally use these two function parameters inside the directive. I would like to be able to pass either a function or 'null' into the directive and based on that, code proper logic inside.

Currently I have two more parameters (not listed in above code) in my directive, enableAdd and enableRemove. I would like to remove these two attributes and determine them based on the logic explained above.

From the outside, currently, the directive is instantiated like this:

<myDirective add-element="addElementFunc()"
             remove-element="removeElement()"
             enable-remove="{{ 1===1 ? 'true' : 'false' }}"
             enable-add="{{ 1===1 ? 'true' : 'false' }}" />

Inside my directive, currently, I use the the enable/disable properties like this:

<div ng-show="enableAdd" ng-click="addElement()">Add</div>
<div ng-show="enableRemove" ng-click="removeElement()">Add</div>

So basically my question is how to remove enableAdd/enableRemove attributes and just code that logic based on whether addElement/removeElement is null or function.

2
  • You can just do: ng-show="addEelment", and that will work, since if nothing is passed in the addElement function is undefined and the ng-show evaluates to false.... Commented Sep 19, 2014 at 14:52
  • @MohammadSepahvand: That is one part. What about declaring that condition to set the add-element attribute on the directive? Commented Sep 19, 2014 at 14:55

1 Answer 1

0

you can do something like this, create two boolean values in parent controller and then condition pass of function into directive by them. for example:

parent controller:

$scope.triggerAdd = false;
$scope.triggerRmove = true;

parent html:

  <myDirective add-element="triggerAdd ? addElementFunc() : false"
                 remove-element="triggerRmove ? removeElement(): false"
                 enable-remove="{{ 1===1 ? 'true' : 'false' }}"
                 enable-add="{{ 1===1 ? 'true' : 'false' }}" >
    </myDirective>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.