1

I have an AngularJS 1.5 component that takes an optional callback function as an attribute binding. I would like to determine whether that attribute is included.

<silly-button></silly-button> <!-- Don't Click Me! -->
<silly-button on-silly-click="handleClick()"></silly-button> <!-- Click Me! -->

Given the trivial example below, how can I implement the the onClickIsNotProvided() function?

angular
  .module('example')
  .component('sillyButton')
  .bindings({
    onSillyClick: '&'
  })
  .controller(['$scope', ($scope) => {
    $scope.onClickIsNotProvided = () => {
      // this.onSillyClick is always defined, so return value is always false :(
      return !this.onSillyClick;
    };
  }])
  .template(`
    <button ng-click="$ctrl.onSillyClick()">
      <span ng-if="onClickIsNotProvided()">Don't</span>
      Click Me!
    </button>
  `);
Patrick McElhaney
  • 57,901
  • 40
  • 134
  • 167
  • Simply by using a different attribute name than the standard https://www.w3schools.com/jsref/event_onclick.asp one ? – Ioan May 26 '17 at 19:19
  • I've changed the attribute name in my dumbed down example to `on-silly-click` to avoid confusion with standard attributes. – Patrick McElhaney May 26 '17 at 19:22
  • 1
    maybe something like this? https://stackoverflow.com/a/33935950/445600 – starcorn May 26 '17 at 19:25
  • 1
    @starcorn Good idea! Post that as an answer and I'll accept it. – Patrick McElhaney May 26 '17 at 19:28
  • 1
    @PatrickMcElhaney the optional parameter `?` is a standard for angular bindings. By the way I suggest you to provide also another check through `angular.isFunction` to be sure that the parameter that has been passed is really a function – quirimmo May 26 '17 at 21:27

2 Answers2

1

You could use &? same as =?, @? to mark whether that parameter is optional or not.

Some reference can be found in here. Although it does not specifically talk about optional function bindings.

starcorn
  • 8,261
  • 23
  • 83
  • 124
  • 1
    Thanks. I sent a PR to mention the feature in the place where I would expect to find it in the docs. https://github.com/angular/angular.js/pull/16017 – Patrick McElhaney May 26 '17 at 19:51
0

I think this is the function that you would have to add:

function onClickIsNotProvided(item) {

    var elementAttributeValue = item.attributes['on-silly-click'].value;
    if (!elementAttributeValue) {
        return true;
    }
    else {
        return false;
}

This would go into the same place as your other angular for the controller.

BRogers
  • 3,534
  • 4
  • 23
  • 32