Search code examples
javascriptangularjsangularjs-components

In AngularJS, how to determine if an attribute is provided to a component?


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>
  `);

Solution

  • 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.