AngularJS ngClick and ngRepeat

Second article about AngularJS and today we are going to see ngClick and ngRepeat directives. I’ve decided to write about these directives because they are very important and we use them all the time.

AngularJS ngClick and ngRepeat

Let’s assume the following code


  var myApp = angular.module('myApp', []);

  myApp.controller("myController", function($scope){



Wrapping your Javascript in a closure is a good habit!

<!DOCTYPE html>
<html ng-app="myApp">
    <title>AngularJS ngClick and ngRepeat</title>
  <body ng-controller="myController">

    <!-- ngClick example goes here -->

    <!-- ngRepeat example goes here -->

    <script src="angular.min.js"></script>
    <script src="app.js"></script>


The first thing we need to do is to create a button in our HTML code and through the ngClick directive call the click function. After that, we will define the click function inside the controller.

<button ng-click="click();">Click</button>

{{ message }}
myApp.controller("myController", function($scope){

  $ = function(){

    $scope.message = "It's working!";



Great. The button is working through the ngClick directive and the message expression we’ve created was replaced by “It’s working”.


When we work with AngularJS, objects and arrays are used daily. Let’s continue our example including an array of objects and store the data inside the controller

myApp.controller("myController", function($scope){
  $scope.message = "It's working!";
  $scope.users = json; // Storing data inside the controller


var json = [
  {name: "Guilherme", email: "", age: "22"},
  {name: "Milena", email: "", age: "26"}

Now we’ve got a user array, simulating a JSON in the real life ;) How do we print out this data inside our webpage? We need to use the ngRepeat directive.

  <li ng-repeat="user in users">{{ }}</li>

The page has been printed out with all the names. But we need to print out the email as well as the age. What do you think about changing the list to a table? It will be easy.

  <tr ng-repeat="user in users">
    <td>{{ }}</td>
    <td>{{ }}</td>
    <td>{{ user.age }}</td>

What if we want to keep our list and print out the name, email and age?

  <li ng-repeat-start="user in users">{{ }}</li>
  <li>{{ user.age }}</li>
  <li ng-repeat-end>{{ }}</li>


The ngClick and ngRepeat directives are extremely easy to work with. JSON works great with the ngRepeat directive and it’s very common to use. You can find these examples on GitHub

Written on February 26, 2015