Tag: Angularjs controller

3 Sep by vichu Tags: , ,

Controllers in AngularJS

We saw how to create modules, but what do we do with them? So far, they have just been empty modules. Let’s now take a look at controllers. Controllers in AngularJS are our workhorse, the JavaScript functions that perform or trigger the majority of our UI-oriented work. Some of the common responsibilities of a controller in an AngularJS application include:
  • Fetching the right data from the server for the current UI
  • Deciding which parts of that data to show to the user
  • Presentation logic, such as how to display elements, which parts of the UI to show, how to style them, etc.
  • User interactions, such as what happens when a user clicks something or how a text input should be validated
An AngularJS controller is almost always directly linked to a view or HTML. We will never have a controller that is not used in the UI (that kind of business logic goes into services). It acts as the gateway between our model, which is the data that drives our Application, and the view, which is what the user sees and interacts with. So let’s take a look at how we could go about creating a controller for our vishalsrini module: [codepen_embed height="265" theme_id="0" slug_hash="GjRZQZ" default_tab="html,result" user="vishal_srini"]See the Pen <a href='http://codepen.io/vishal_srini/pen/GjRZQZ/'>Creating a module in angularjs</a> by Vishal Srinivasan (<a href='http://codepen.io/vishal_srini'>@vishal_srini</a>) on <a href='http://codepen.io'>CodePen</a>.[/codepen_embed] We define a controller using the controller function that is exposed on an AngularJS module. The controller function takes the name of the controller as the first argument, which in the previous example is creatively named MainCtrl. The second argument is the actual controller definition, of what it does and how it does it. But there is a slight twist here, which is the array notation. Notice that we have defined our controller definition function inside an array (this part -> [function() { ... }]). That is, the first argument to the controller function on the module is the name of the controller (MainCtrl), and the second argument is an array. The array holds all the dependencies for the controller as string variables, and the last argument in the array is the actual controller function. In this case, because we have no dependencies, the function is the only argument in the array. The function then houses all the controller-specific code. We also introduce a new directive, ng-controller. This is used to tell AngularJS to go instantiate an instance of the controller with the given name, and attach it to the DOM element. In this case, it would load MainCtrl, which would end up printing the console.log() statement.