Skip to content

Instantly share code, notes, and snippets.

@boxmein
Created February 20, 2019 08:05
Show Gist options
  • Save boxmein/6a3f732ca42fa8ed54e49fd32e2ce986 to your computer and use it in GitHub Desktop.
Save boxmein/6a3f732ca42fa8ed54e49fd32e2ce986 to your computer and use it in GitHub Desktop.
AngularJS 1.5 code to get an "optional callback argument" in components
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.10/angular.min.js"></script>
<script src="script.js"></script>
</head>
<body ng-app="app">
<app-x></app-x>
</body>
</html>
/*
This code makes an AngularJS component callback argument optional.
If you bind to '&?' instead of '&', then the callback function will be undefined
if it's not set by the parent. However, just '&' will just shim it with a function
even if there's no actual function specified.
*/
angular.module('app', [])
.component('appX', {
bindings: {
func: '&?',
},
template: `<div>
<p>Hello from appX!</p>
<ul>
<li>func is: {{ $ctrl.func }}</li>
</ul>
</div>`,
controller: class {
constructor() {
console.log('[constructor] function is', this.func);
}
$onInit() {
console.log('[$onInit] function is', this.func);
}
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment