AngularJS: Chaining multiple functions in one ng-click

Today I learned… a little trick for performing multiple functions in a single ng-click. Just separate them with a semicolon (;) like so:

<button ng-click="selectTab(); $parent.someVar = true">Button Text</button>

This comes with a noticeable caveat: it complicates your template code. Generally, it’s considered good practice to minimize the amount of logic that happens in an html template. If you need to do many things on a single ng-click, you should consider writing (or refactoring) a method in your controller to handle them with just one method call.

Nonetheless, this odd bit of Angular syntax can be useful, even if it never makes it to production. In my case, I needed to modify $parent.someVar on click, which was (at the time) outside of the button’s controller. Ultimately, this code was refactored so that someVar could be modified from within selectTab(), but when I needed a quick and dirty implementation to demo something, chaining functions on a single ng-click got the job done.

Wait, what does $parent.someVar do? What is $parent?

$parent allows code within a child controller to access something contained within the parent scope.

In my project I had multiple scopes.

<div ng-controller="PageCtrl">
   <div ng-controller="SectionCtrl">
      <button ng-click="selectTab()">Button Text</button>
   </div>
</div>

someVar was contained within PageCtrl (the parent scope), but I needed to manipulate it from a button inside SectionCtrl (the child scope). Using $parent, the SectionCtrl code could “look up” into the parent and find someVar. This Stack Overflow Q&A explains $parent with more examples.