Intro to Angularjs – Turing



Intro to Angularjs – Turing

0 0


class-angular-intro

Introduction to Angularjs

On Github itechdom / class-angular-intro

Intro to Angularjs

Turing

Osama Alghanmi / @itechdom

What you'll need to know

  • HTML
  • CSS
  • JavaScript
  • DOM

What is AngularJS

“AngularJS is not a library.”

“AngularJS is a JavaScript framework that embraces extending HTML into a more expressive and readable format.”

“AngularJS fits the definition of a framework the best, even though it's much more lightweight than a typical framework and that's why many confuse it with a library”

Why use AngularJS?

Organization

Fast (responsive) websites

Easy to test

Getting Started

  • Download AngularJS
  • Or use the CDN
  • Link it in your html
<html>
<head>
<!-- <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script> -->
</head>
<body>
</body>
</html>
- adding the script tag and style tags

Module

Containers for different parts of your application.

Except those containers can use other containers.

Places where we will write pieces of our application and define dependencies

Mention modular design and a graphic would be helpful here

Our first module

Create a new file, app.js, and add:

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

And in our HTML file

<!DOCTYPE HTML>
<html ng-app="turing">
    <head>
    <!--
<!-- <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
    <script type="text/javascript" src="app.js"></script>
    -->
    </head>
    <body>
    </body>
</html>

You've made a module!

- Create your app.js file, add main app module code - angular is a call to angular.js - 'turing' will be the name of your application, make sure to add it! - [ ] will be where dependencies go - Side note about ng-app - It's telling angular that everything inside of html belongs to the app 'turing' - It could even be empty

{{ Exercise }}

  • Create a module and call it 'whateverYouWant'
  • Remember to create: app.js, load it in your HTML
  • Add the module name to your html with ng-app

Controllers

Controllers are (from the name) what controls our html file and our data.

Controllers

First we need to add a controller to our app

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

    app.controller('UserController', function($scope){

    });

Controllers

Let's populate a list of turings here in our controller. then assign the data to the scope variable

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

    app.controller('UserController', function($scope){

    $scope.cohort =

        {
            "name":"1410",
            "students": [
                "jane",
                "john",
                "jimmy",
                "jones"
            ],
            "color":"blue"
        }

        });

Attaching the Controller

<section class="center" ng-controller="UserController">

        <h1 style="color:{{cohort.color}};"> Hi, {{cohort.name}}</h1>

</section>

Understanding Scope

The "scope" of the controller only works inside of the container

<section class="center" ng-controller="UserController">

        <h1 style="color:{{cohort.color}};"> Hi, {{cohort.name}}</h1>

</section>
{{cohort.name}} <!-- doesnt't work! -->

expressions and binding

Angular expressions are JavaScript-like code snippets that are usually placed in bindings such as {{ expression }}. This allows you to insert values into the HTML

For example:

I have {{ 1+2 }} apples ⇨ I have 3 apples

expressions and binding

Some other valid expressions:

{{ a+b }}
{{ user.name }}
{{ items[index] }}
- no loops, conditionals, if/else - You don't really want to do logic in your view! - Binding is best for displaying data

expressions and binding

Let's add an input into our view and add an ng-model attribute:

<input type="text" ng-model="myName" />

Then add a binding somewhere on the page

<h1>Hi, {{myName}}</h1>

expressions and binding

Binding can be used for more than just printing text

<input type="text" ng-model="myName" />
<h2 class="text-{{myName}}">Your name is: {{myName}}</h2>

{{ Exercise }}

Color your list
  • Create a text box
  • write the name of one of your favorite things to do
  • Display that name in your html
  • create another text box to type in the color of that item
  • change the color of that item! Hint(use binding and css style 'color')

Directives: The spices of Angularjs

Angularjs provides a lot of directives that add functionality to our html Let's add more data to our application

app.controller('UserController', function($scope){

    $scope.cohorts =[

    {
        "name":"1410",
        "students": [
            "jane",
            "john",
            "jimmy",
            "jones"
        ],
        "color":"blue",
        "graduated":false
    },
    {
        "name":"1412",
        "students": [
            "a",
            "b",
            "c",
            "d"
        ],
        "color":"red",
        "graduated":false
    }
]

});

ngshow directive

ngShow: show the html element if the value provided is true

<section class="center" ng-controller="UserController">
        <div ng-show="!cohort.graduated">
        <h1 style="color:{{students.color}};"> Hi, {{students.cohort}}</h1>
        </div>
</section>

ngHide Directive

<section class="center" ng-controller="UserController">
        <div ng-hide="cohort.graduated">
        <h1 style="color:{{students.color}};"> Hi, {{students.cohort}}</h1>
        </div>
</section>

NgRepeat

very important directive. iterates through an array and repeats the html element it's attached to.

<div>
    <h2>
    List of cohorts
    </h2>

    <ul>

    <li ng-repeat="cohort in cohorts" >

    {cohort.name}}

        <h2>
        List of Students
        </h2>

        <ul>

        <li ng-repeat="student in cohort.students">

        {{student}}

        </li>

        </ul>

    </li>

    </ul>

</div>
show good way

Filters

Returns a subset of our data

{{ cohorts | filter:{"name":"1410"} }}

More Built-in Filters https://docs.angularjs.org/api/ng/filter

jQuery Way, The old Way

Let's write a simple TODO application and Do it in good ol' Javascript and jQuerys ... This is how we would write a simple todo list app

The HTML:

<input id="list-input" placeholder="task"></input>
<button id="submit">Add</button>

<ul id="list">
</ul>

jQuery - Part1

We initialize some variables (inside document read)

    $(document).ready(function() {

    listArray = [];
    input = $('#list-input');
    submitButton = $('#submit');
    list = $('#list');

    )

jQuery - Part 2

General methods to delete and add to the list array

    addToList = function(item){

        listArray.push(item)
        updateDisplay()

    }

    deleteFromList = function(item){

        index = listArray.indexOf(item)
        if(index > -1){
            listArray.splice(index,1);
        }
        updateDisplay()

    }

jQuery - Part 3

We usually update the list everytime we make changes

    updateDisplay = function(){

        list.empty()
        deleteButton = '<button class="delete">Delete</button></div>'
        for(i=0;i<listArray.length;i++){
            item = listArray[i];
            listItem = $('<div class=".container"><li id='+item+'>' + item +'</li>'+ deleteButton);
            list.append(listItem)
        }

    }

jQuery - Part 4

We shouldn't forget to bind the buttons so we can add to and delete from list

    $(document).on('click','#submit',function(el){
        value = input.val();
        addToList(value)

    })

    $(document).on('click','.delete', function(el) {
        todo = el.currentTarget;

        sibling = $(todo).siblings('li')

        item = sibling[0].innerHTML;

        deleteFromList(item);

    })

Angular way

What we had to do in the previous example:

  • create list element in code and insert them
  • update display everytime we make a change
  • We are not focusing on the data in our application (task list)

Angular Way

  • We can re-write our previous application in a couple of lines in Angualrjs.
  • We will review all the steps that we take into converting the TODO list app into an Angularjs app.

Todo App

Let's go back to our first example and rewrite it completely in Angularjs.

Start with your Data

  • define what data your want to have and bind it to the scope.
  • design your html and add directives around it
  • let Angular handle the rest

Step1: our Data

    app.controller('TodoController', function($scope){

        $scope.todos = []

    });

Step2: Design your html

Write your html and spice it with some Directives to connect to your data.

<div class="todos center" ng-controller="TodoController">

    <input ng-model="currentTodo" id="list-input" placeholder="task"></input>
    <button class="button" ng-click='addTodo(currentTodo)' id="submit">Add</button>

    <ul id="list">

        <li ng-repeat="todo in todos" class="todo">
            <button ng-click="deleteTodo(todo)">Delete</button>
            {{todo.name}}
        </li>

    </ul>

</div>

Step3: Add missing functions

Add the missing functions to your controller

    $scope.currentTodo = ""

    $scope.addTodo = function(todo){
        todoObject = {
            name:todo
        }
        $scope.todos.push(todoObject);
    }
    $scope.deleteTodo = function(todo){
        index = $scope.todos.indexOf(todo)
        $scope.todos.splice(index,1)
    }

{{ Exercise }}

Extend the todo app to:
  • have a button next to each todo task
  • When the user clicks the button: Toggle the text in the button to "finished", "no finished"
  • hint: add a piece of data to your todo items that determines whether a task is done or not

Let's make our own directive

In our HTML

<todo-item></todo-item>

In our app

app.directive('todoItem', function(){
    return{
        restrict: 'E',
        templateUrl: 'todoItem.html'
    };
});

Let's move the todo items

to the directive template

<div  class="todo" ng-class="{done:todo.done}">
<img height="20" width="30" ng-show="todo.done" src="../../img/check.png">{{todo.name}}
<button ng-click="deleteTodo(todo)">Delete</button>
<button class="done" ng-click="todo.done = !todo.done">
    <span ng-show="todo.done">Not Finished</span>
    <span ng-show="!todo.done" >Finished</span>
</button>
</div>

Restrict

app.directive('todoItem', function(){
    return{
        restrict: 'E',
        templateUrl: 'todoItem.html'
    };
});

restrict is the type of directive this code will match

A: attribute

<div todo-item></div>

E: element

<todo-item></todo-item>

C: class

<div class="todo-item"></div>
You'd use element more for UI widgets Attributes for mixins (decorating existing stuff), like turning a block of text into a tool tip. You can even do multiple so that they all work.

Directives with Controllers

Let's move our whole todo list into it's own directives

The benefits: Can be reused in other parts of our application. Example: if we wanted to add multiple todo list of different types

In our HTML

<todo-list>
</todo-list>

In our app

app.directive('todoList', function(){
    return{
        restrict: 'E',
        templateUrl: 'todoList.html'
    };
});

In our template

<input ng-model="currentTodo" id="list-input" placeholder="task"></input>
<button class="button" ng-click='addTodo(currentTodo)' id="submit">Add</button>
<ul id="list">
<todo-item ng-repeat="todo in todos"></todo-item>
</ul>

Let's move the controller into our directive

app.directive('todoList', function(){
    return{

        restrict: 'E',

        templateUrl: 'todoList.html',

        scope:{},

        controller:function($scope){
        $scope.todoList = [
        $scope.addToList = function(){
            todoObject = {
            name:$scope.currentTodo,
            done:true
        };
        $scope.todoList.push(todoObject);
        }
       }
    };
});