Skip to content

Instantly share code, notes, and snippets.

@nimitmaru
Created May 15, 2015 15:46
Show Gist options
  • Save nimitmaru/d6c12b9ab536ea8d5631 to your computer and use it in GitHub Desktop.
Save nimitmaru/d6c12b9ab536ea8d5631 to your computer and use it in GitHub Desktop.

#Angular part 2

Part 1 Recap

In the last workshop we covered the basics of building an Angular app. As a recap the steps included:

  1. Start with a default file to serve, typically index.html
  2. Include the Angular Library source file like any other javascript file
  3. Create a main file, app.js, that defines and initiates the angular app 'Education'
  4. Inside app.js should be a controller named 'SchoolController', that defines a school property on the $scope object, containing details about Fullstack Academy
  5. On index.html, set ng-app to encompass the html body
  6. In another div, declare the controller responsible for the scope of class schools

Objectives

We were able to display a single object with multiple properties on the last workshop. The objective today is to display an array of multiple objects with similar properties.

Setup

To start, we need to fork the repository.

  1. Fork the repository to your account.
  2. Go to your own repositories on GitHub and clone the fellowshipt repository link.
  3. Use the link in the git clone then follow the rest of the commands.
$ git clone https://github.com/alwang85/fellowship.git

Display an array of 3 schools

Leveraging the existing template, try displaying the contents of the following array:

    schools = [{
          students: 28,
          name: "Fullstack Academy",
          history: "2 years",
          fellows: ["Seema", "Ivan", "Linda", "Sarah"],
          motto: "code for life"
        },{
          students: 50,
          name: "General Assembly",
          history: "2 years",
          fellows: ["Sam", "John", "George"],
          motto: "all you can join"
        },{
          students: 17,
          name: "Joescript Academy",
          history: "Joe years",
          fellows: ["Joe", "Joe", "Joe", "Joe"],
          motto: "got Joe?"
     }];

Bonus: When you are done, try out what happens when you delete a school from the schools array without modifying index.html!

Perhaps a DRYer way: ng-repeat

Chances are on index.html you did something such as {{schools[0].name}} for all 3 schools. That certainly goes against the coding mantra of DRY (Don't Repeat Yourself)!

Fortunately, Angular has a built in directive called ng-repeat. Check out the following resources and then refactor your code using ng-repeat!

https://docs.angularjs.org/api/ng/directive/ngRepeat

http://randomjavascript.blogspot.com/2014/09/building-angular-list-using-ng-repeat.html

Once you got ng-repeat to work, try copying the same objects inside the schools array and add a duplicate copy into the array!

Hints / Syntax

ng-repeat takes the form of <div ng-repeat="(key, value) in myObj"> ... </div> for Objects, and <div ng-repeat="element in elements"> ... </div> for an Array.

{{element.name}} gives you access to the name property of this element in an Array. You may have noticed that every repetition has different values, even though they are referenced with the same "element.name". Every element in ng-repeat has its own scope!

Also, Angular by default does not allow duplicate elements to be shown in ng-repeat, since it would be much harder to manipulate the DOM with multiple objects having the same data;

Recap

When we displayed the array of 3 schools by manually adding <div>'s, it was very tedious to manage all of the elements of the array. Worse, when the manually added elements had a different length of what's available in the array, the code broke.

In many applications, you may not be able to know beforehand the elements of what you wish to display. ng-repeat is one of the BEST directives in Angular that helps front-end development become more DRY.

ng-repeat keeps track of the different elements created, and also maintains a separate scope for each element. This allows the same function on the scope to be passed the different values of each event! Find out more about the benefits of separate scope in the last Bonus step!

Next Steps / Bonus

  • Instead of displaying the fellows as an array, try nesting ng-repeat!

  • You can add a class to an element by adding ng-class="classname" to an element

    • Check the docs for ng-class-odd and ng-class-even to see how they work together with ng-repeat!
  • Check the documentation for ng-click , define a function in the controller, and experiment with ng-click! A good sample function would be:

      $scope.tellMe = function(element){
          console.log(element)
      };
    

#Pokedéx Upgrade

Introduction

Ash Ketchum, after a long and fulfilling career as a Pokémon trainer, has decided to make the switch to web development. Oak Industries, the manufacturer of the Pokédex, has employed Ash, and has assigned him his first project: upgrade the Pokedéx to a web-based single page application. You will assume the role of Ash, and begin the process of making a new Pokedéx. Today we will be working on one feature: listing all of the Pokemon on the Pokedex onto a single page!

Getting Started

  1. Fetch and clone the workshop from the GitHub Repo
  2. Run npm install after retrieving the repository. This repository will include the index.html, app.js, and style.css files.
  3. Run npm start after installing the files, and we're ready to start!

Puting it into HTML

Inside of our index.html file, let's place our Pokedéx onto the page statically.

Here is the current HTML snippet for the Pokedex:

<div class="pokemonster"> 
    <h1>Name</h1>
    Name of Pokemon 
    <h3>Type</h3>
    Type: Grass, Water, Fire
    <img src='pokemon.com'></img>
</div> 

Place the snippet inside the <div> with the ng-controller="PokedexController" attribute that was included in the index.html file.

Professor Oak's Conundrum

Professor Oak, CEO of Oak Industries, is using a highly manual and inefficient process to update all of the Pokemon in the Pokedex. He is replacing the fields Name of Pokemon, Type: Grass, Water, Fire, and img src of each Pokemon's attributes one by one! Can you think of a better way to update the Pokemon in a way that not only saves time but also allows for greater control of your application? If you do not, have no fear, because I would like to introduce you to an Angular directive called ng-repeat!

This directive let's you iterate over a collection (ex. array or object) and repeat a snippet of code for each of the items in the collection. Angular creates a new $scope instance for each repeated snippet of HTML. This allows you to input properties of all of the Pokemon in the $scope.pokeList array in app.js by including ng-repeat in your .pokemonster div!

Gotta Catch Em' All!

Inside our app.js file, let's take a look at what's inside of our PokedexController :

app.controller('PokedexController', function($scope){
	$scope.pokeDex = [
		{
		name: 'Charmander',
		type: 'Fire',
		img: 'http://img.pokemondb.net/artwork/charmander.jpg'
		},
		{
		name: 'Squirtle',
		type: 'Water',
		img: 'http://img.pokemondb.net/artwork/squirtle.jpg'
		},
		{
		name: 'Bulbasaur',
		type: 'Grass',
		img: 'http://img.pokemondb.net/artwork/squirtle.jpg'
		},
		{
		name: 'Pikachu',
		type: 'Electric',
		img: 'http://img.pokemondb.net/artwork/pikachu.jpg'
		}
	];
});

As you can see, there are four Pokemonster objects in our $scope.pokeDex array that contain the properties we would like to include in our Pokedex. Let's take a look at how we can modify our .pokemonster div to populate all of our Pokemon and their properties into the Pokedex page.

  • Let's include ng-repeat into our div

      <div class="pokemonster" ng-repeat='pokemonster in pokeDex'> 
          <h1>Name</h1>
          Name of Pokemon 
          <h3>Type</h3>
          Type: Grass, Water, Fire
          <img src='pokemon.com'></img>
      </div>
    

The ng-repeat will iterate through the array of pokemon objects located on the $scope.pokeDex array in our PokedexController and create a new .pokemonster div for the length of the array. Every instance of each pokemon object will be referred to in each div as pokemonster.

  • Now, let's format our template to display the properties of each pokemon

      <div class="pokemonster" ng-repeat='pokemonster in pokeDex'> 
          <h1>Name</h1>
          {{pokemonster.name}}
          <h3>Type</h3>
          {{pokemonster.type}}
          <img ng-src="{{pokemonster.img}}"></img>
      </div> 
    

Since pokemonster in each of our divs' is a reference to each pokemon object, we have access to each pokemon's properties! Our Pokedex page should now be populated with the name, type, and image of each Pokemon! Take a look at the page in your Chrome browser, and use the Chrome element inspector to see how the properties for each pokemon have been inputted in each div!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment