Google+

Saturday, December 26, 2015

#13 - Add CSS3 Style to AngularJS Application with Twitter Bootstrap

In this article we review how to Add CSS3 Style to an AngularJS Application with Twitter Bootstrap,  developing from scratch in 20 minutes a complete SPA (Single Page App) Angular Application that  shows the outstanding features of both the Twitter Bootstrap and the AngularJS javascript framework.
We'll build here a SPA app which shows an item list, and allows you to append more items to it.
You can learn this step-by-step tutorial as a standalone, or you can see the previous lessons of the series. This is the Lesson #13 in the "AngularJS: From 0 To 100" Series specially written for Beginners. This lessons begin at the Lesson #1   .

Also, this tutorial contains two parts:
1) creating an SPA AngularJS app
2) adding the Twitter Bootstrap to an existing AngularJS Application

Therefore, if you already have an SPA app, you can directly jump to the Step 2.


<<<<  PREVIOUS LESSON                      NEXT LESSON >>>>



This is the AngularJS App that we'll develop in 20 minutes in this Tutorial :

Add CSS3 Style to AngularJS Application with Twitter Bootstrap     1



Add CSS3 Style to an AngularJS Application with Twitter Bootstrap



Step #1 - Creating an SPA (Single Page Application) with AngularJS:


First, let's add the references to the AngularJS javascript framework using CDN, and defining the HTML5 file as an data-ng-app Angular App:

Add CSS3 Style to AngularJS Application with Twitter Bootstrap      2


(Get the source code):

<!doctype html>
<html data-ng-app="MusicApp">
<head>
<title>
    AngularJS Twitter Bootstrap
</title>
     
<link href="Style.css" rel="stylesheet" type="text/css"  />  
<script  src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.7/angular.min.js"></script>
<script src="Controllers.js" type="text/javascript"></script>

</head>



Here we're  using the "Brackets" open source web Editor , which supports AngularJS Apps. You can read more about it in this post.

Our first step is coding a list of items using the data-ng-repeat AngularJS Directive:

Add CSS3 Style to AngularJS Application with Twitter Bootstrap        3

We explained in detail this kind of AngularJS collections in this tutorial . Take a look if you have the time.

(Copy):

<body  data-ng-controller="MusicController">
<div>
     

    <div> 
        <h2>Fragile State Discography</h2>     
        <h3>Neil Cowley (Zero 7) and Ben Mynott</h3>  
    </div>
    
   
    <div>    
        <ul>                
            <li data-ng-repeat="album in albums">                        
                .{{$index + 1}}            
                <img src="{{album.img}}" alt="{{album.name}}"  >             
                <span >{{album.name}} - {{album.price | currency:"USD$" | uppercase}}</span>             
            </li>             
        </ul><br /> 
    </div> 
        
</div>
</body>
</html>


The Controller part of this MVC (Model View Controller) AngularJS SPA App consists in this code that we add to the javascript .js file:

Add CSS3 Style to AngularJS Application with Twitter Bootstrap        4


This code just initialize the item's list we're building.

(Copy):

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

oMusicApp.controller('MusicController', [ '$scope', function ($scope) {
           
            var albums = 
            [
                {id:111,img:"Nocturnal.jpg",name:"Nocturnal Beats",price:"12.50"},
                {id:112,img:"Facts.jpg",name:"The Facts And The Dreams",price:"11.20"},
                {id:113,img:"Voices.jpg",name:"Voices From The Dust Bowl",price:"13.70"},
                {id:114,img:"Pretz.jpg",name:"Soundcastles",price:"14.80"}
            ]
            $scope.albums = albums;

}]);

Run the App to see if everything's OK:

Add CSS3 Style to AngularJS Application with Twitter Bootstrap       5


Next, we build the web form that allows us to append a new Music Album item to the list. We mimic here a real-world submit form with input checking. But, instead of sending the data form to a web server, we handle the submit event and immediately add the item to the list:

Add CSS3 Style to AngularJS Application with Twitter Bootstrap        6

Take a close look: our form includes several HTML5 input elements, with the correspondent validation and error checking , using the Angular data-ng-disabled directive to disable the submit button in case that the input data do not comply with the legal input requirements.
We bind all the input data to a data-ng-model named "album", as its properties. For example, "album.name" , "album.price" , etc. At runtime, the Angular engine will take care of the entire "album" entity for us.
A deeper explanation of this validation features can be found in the following Tutorial on Forms Validation.

(Get the source code):

 <div class="jumbotron">            
        <div class="container" >
            <h3>Add a New Music Album</h3>
                     
          <form data-ng-submit="submitForm()" name="NewAlbumForm">
                
            Album Name 
            <span data-ng-show="NewAlbumForm.Name.$error.required" class="errorMessage">*</span><br />
            <input  class="form-control" name="Name" data-ng-model="album.name" 
                   required data-ng-minlength="3" /> <br />
            <span class="alert alert-danger"  data-ng-show="NewAlbumForm.Name.$error.minlength" class="errorMessage">Minimum length 3</span><br />
              
            <br />Album Price
            <span data-ng-show="NewAlbumForm.Price.$error.required" class="errorMessage">*</span><br />
            <input  class="form-control" type="number" name="Price" min="1" 
                   data-ng-model="album.price"  required><br /><br /><br />
            
            Select a Picture<br />
            <select  class="form-control"  data-ng-model="album.img"  
                data-ng-options="picture + '.jpg' as picture for picture in pictures" required>
            </select><br />

            <input class="btn btn-primary  btn-lg" type="submit" value="Add New Music Album" 
                   data-ng-disabled="NewAlbumForm.$invalid">
                
          </form>
        </div>
    </div> 

And at the Controller we add the following code to handle the submit event:

Add CSS3 Style to AngularJS Application with Twitter Bootstrap      7

This code just loads the data for the select element, and appends a new "album" item to the list. Then, it cleans the "album" object, to allow adding more items . As you can see, Angular takes care of all the Album's properties. 

(Copy):

$scope.pictures = ["Nocturnal","Facts","Voices","Pretz"];
             
            $scope.submitForm = function() {
                $scope.albums.push($scope.album);
                $scope.album = {};
                
            };








Step #2 - Adding the Twitter Bootstrap to an AngularJS SPA Application:


#First step: adding the Bootstrap references:


Add CSS3 Style to AngularJS Application with Twitter Bootstrap    8

You can get the style using CDN (Content Delivery Network) just copying this links:

(Copy):

<link rel="stylesheet" href="http://netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css"  />
<link rel="stylesheet" href="http://netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap-theme.min.css"  />

Or you can download the latest versions from the Bootstrap web site:

Add CSS3 Style to AngularJS Application with Twitter Bootstrap        9


#Second Step: adding the Bootstrap Navbar to the App:


Browse to the Bootstrap web site , and find the Navbar at the "Components" tab:

Add CSS3 Style to AngularJS Application with Twitter Bootstrap       10

Copy-paste the HTML5 markup to a new HTML file in your directory:

Add CSS3 Style to AngularJS Application with Twitter Bootstrap    11

Then, use the data-ng-include and src AngularJS directives to insert the Navbar inside the App:

Add CSS3 Style to AngularJS Application with Twitter Bootstrap       12

<div data-ng-include src="'Navbar.html'"></div>

Notice the double quotes we used here: "' '" : it's very important!



#Third Step: add the Bootstrap classes to the <div>s elements :


Now we just decorate all divs and elements with the Bootstrap classes:

Add CSS3 Style to AngularJS Application with Twitter Bootstrap        13


For instance, we use the "Jumbotron" component to give style to the title, as explained at the Bootstrap web site:

Add CSS3 Style to AngularJS Application with Twitter Bootstrap       14

After you added the style, browse to your app and refresh it:

Add CSS3 Style to AngularJS Application with Twitter Bootstrap      15

We can already see the Navbar and the Jumbotron.

Now we add the Bootstrap classes to the web form as follows:

Add CSS3 Style to AngularJS Application with Twitter Bootstrap

We can choose another kind of button from the Bootstrap web site:

Add CSS3 Style to AngularJS Application with Twitter Bootstrap       16

Also there you'll find all kinds of Alerts to choose:

Add CSS3 Style to AngularJS Application with Twitter Bootstrap       17


Refresh the SPA:


Add CSS3 Style to AngularJS Application with Twitter Bootstrap   18


Now for the items list, add the Bootstrap Style classes as follows:



Add CSS3 Style to AngularJS Application with Twitter Bootstrap      19


Refresh:

Add CSS3 Style to AngularJS Application with Twitter Bootstrap        20

We have all the Bootstrap Style we need.

Now let's see how it works. Let's add a new "Fragile State" Music Album to the Collection:


Add CSS3 Style to AngularJS Application with Twitter Bootstrap      21


Notice the Bootstrap Alert informing the user that the length requisites have not been provided.
Select a Price:

Add CSS3 Style to AngularJS Application with Twitter Bootstrap     22



And select a Picture from the Drop Down List:

Add CSS3 Style to AngularJS Application with Twitter Bootstrap     23



Click the button :

Add CSS3 Style to AngularJS Application with Twitter Bootstrap      24


A new item has been appended to the list.

Finally, the only CSS3 style that we need is the following: (copy-paste the following CSS3 style to your style.css file) :


ul
{
list-style:none;    
}
div.centered
{
 text-align:center   
}
.errorMessage
{
 color:red;   
}
}


That's All!!! You have Added CSS3 Style to an AngularJS Application using the Twitter Bootstrap . In the next article we will continue to learn Step by Step about Making GET Requests with pagination to OData Web API RESTful service using $http AngularJS 
Enjoy AngularJS.....

      by Carmel Schvartzman


<<<<  PREVIOUS LESSON            NEXT LESSON >>>>



כתב: כרמל שוורצמן

Monday, October 26, 2015

#12 - Learn AngularJS CSS3 and HTML5 DOM manipulation with Directives

In this article we learn AngularJS CSS3 and HTML5 DOM manipulation with Directives,  and develop from scratch an Angular Application which includes CSS3 style and HTML5 DOM changing upon user's interaction. Our Angular App will allow us to manipulate both CSS3 style and DOM elements.
We'll perform the following, by handling a <button> click event :

1) change an <img> element source
2) change the style class of an element
3) change the inline style of an element
4) hide/show a <div> element
5) create a new HTML DOM custom element named "<copyright>"

This is the Lesson #12 in the "AngularJS: From 0 To 100" articles written for Beginners. This lessons start at Lesson #1  , and you're invited to follow them.

<<<<  PREVIOUS LESSON                     NEXT LESSON >>>>


You can read more about the "Brackets" open source web Editor , which supports AngularJS Apps,  in this post.

The AngularJS App that we'll develop here will be shown this way :

Learn AngularJS CSS3 and HTML5 DOM manipulation with Directives




Learn AngularJS CSS3 and HTML5 DOM manipulation with Directives



The DOM (Document Object Model) is a W3C standard for manipulating an HTML5 page, by performing all CRUD (Create, Read,Update, Delete) operations on the HTML5 elements, meaning creating new HTML5 elements, getting existing HTML elements, changing elements, and deleting them. Because changing an HTML5 element includes changing its Attributes, DOM manipulation applies also on its CSS3 style, in that we can change style as well. For example, a DOM can show like the following elements tree:
Learn AngularJS CSS3 and HTML5 DOM manipulation with Directives     1

AngularJS includes built-in functionality to change the HTML5 DOM and the CSS3 style of a web page, through Angular "Directives".
AngularJS Directives are expressions which tell the Angular $compiler to transform a DOM element or its properties.  By the end of this lesson, we'll create a new HTML DOM custom element named "<copyright>" , using an AngularJS Directive.

First , we create from scratch an AngularJS web page as follows:

Learn AngularJS CSS3 and HTML5 DOM manipulation with Directives       2



 (copy-paste):

<!doctype html>
<html data-ng-app="MusicApp">
<head>
<title>
    AngularJS CSS3 & DOM Manipulation
</title>     
<link href="style.css" rel="stylesheet" type="text/css"  />
<script  src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.7/angular.min.js"></script>
<script src="Controller.js" type="text/javascript"></script>
</head>

Next, we create an Angular View bound to a Controller, to show a list of Music Albums , as learned at the Lesson  #1 :

Learn AngularJS CSS3 and HTML5 DOM manipulation with Directives      3



 (copy-paste):

<body >    
<div   data-ng-controller="MusicController">
    <div class="centered">         
        <img data-ng-src="{{angularImgSrc}}">
    </div>
    
    <div id="controls"> 
        <div class="centered"  > 
            <h1>Fragile State Discography</h1>     
            <h2>Neil Cowley (Zero 7) and Ben Mynott</h2>  
        
        </div>
       
        <ul >                
            <li data-ng-repeat="album in albums"> 
                 <div  >        
                    <img src="{{album.img}}" alt="{{album.name}}"  >             
                    <span >{{album.name}} - {{album.price | currency:"USD$" | uppercase}}</span>                        
                </div>
            </li>             
        </ul><br />        
            
    </div>  
   </div>  
</body>
</html>

Open the Controller javascript file, and copy-paste the following code:

angular.module('MusicApp', [])

.controller('MusicController', [ '$scope', '$log', function ($scope, $log) {
           
            var albums = 
            [
                {id:111,img:"Nocturnal.jpg",name:"Nocturnal Beats",price:"10.50"},
                {id:112,img:"Facts.jpg",name:"The Facts And The Dreams",price:"10.20"},
                {id:113,img:"Voices.jpg",name:"Voices From The Dust Bowl",price:"11.70"},
                {id:114,img:"Pretz.jpg",name:"Soundcastles",price:"10.80"}
            ]
            $scope.albums = albums;
            $scope.angularImgSrc = "IMG_2.jpg";
                
                                 
            
}])





Now, because we'll be changing the CSS3 style, here you have the code to copy:

div[id^=controls] 
{
padding:5px 5px 5px 25px;
margin:10px 15px 15px 25px;
font:900 12px Comic Sans MS;
opacity:0.9;
background:#fed;    
border:10px solid #ddd;    
border-radius: 10px;
box-shadow:10px 10px 2px #c0c0c0;
}
button
{
padding:5px 5px 5px 5px;
margin:10px 15px 15px 15px;
width:220px;
text-align: center;
background:#ddd; 
font:900 14px Comic Sans MS;
opacity:0.9;
border:1px solid #c0c0c0;    
border-radius: 10px;
box-shadow:10px 10px 2px #c0c0c0;
}
ul
{
list-style:none;    
}
div.centered
{
 text-align:center;   
}
.angular
{
padding:5px 5px 5px 5px;
margin:25px 15px 15px 25px;
width:350px;
text-align:center;
background:#fee; 
font:900 14px Comic Sans MS;
opacity:0.9;
border:1px solid #c0c0c0;    
border-radius: 10px;
box-shadow:10px 10px 2px #faf;
}


Run the App to check if everything's OK :



Learn AngularJS CSS3 and HTML5 DOM manipulation with Directives    4

Provided it's OK, add a button to perform the style changes:


Learn AngularJS CSS3 and HTML5 DOM manipulation with Directives       5



 (copy-paste):

<div  class="centered"> 
              <button data-ng-click="applyStyle()">Change CSS3 Style</button>
 </div>

Append this code to the Controller:

Learn AngularJS CSS3 and HTML5 DOM manipulation with Directives         6

Here we just code a toggle mechanism to enable/disable the changes. The $log.info() is to help you to debug this Controller, as you will see the log info inside the Developer's Tools (F 12) Console.

 (copy-paste):

 var bIsCustomStyle = false; 
            $scope.applyStyle = function() {
                
                
                $log.info("InsideCtl") 
                bIsCustomStyle = !bIsCustomStyle;
  };

Refresh the App and open the Developer's Tools (F 12) Console to see the message:

Learn AngularJS CSS3 and HTML5 DOM manipulation with Directives        7


1 - Change an <img> element source:

How to change an image <img> source dynamically using AngularJS?
Remember that we used previously an data-ng-src Directive inside the <img> image element. That data-ng-src is bound in our example to a Model called "angularImgSrc", therefore we just change its value at the method.
By adding the following code to the method that handles the OnClick event, you change the image at the Angular View:

Learn AngularJS CSS3 and HTML5 DOM manipulation with Directives       8




 (copy-paste):

$scope.angularImgSrc = "IMG_2.jpg";
$scope.angularImgSrc = "IMG_1.jpg";

Refresh the web page and see how it works:

Learn AngularJS CSS3 and HTML5 DOM manipulation with Directives       9


Click the button to change the picture:

Learn AngularJS CSS3 and HTML5 DOM manipulation with Directives     10



2 - Change the style class of an element:

This second exercise shows how to change the style Class of an HTML5 element using AngularJS. 
Add the data-ng-class AngularJS Directive to the div element inside the list :

Learn AngularJS CSS3 and HTML5 DOM manipulation with Directives     11


Next, add this code to the method, to toggle the style class:

Learn AngularJS CSS3 and HTML5 DOM manipulation with Directives    12



  (copy-paste):

$scope.angularClass = "";
$scope.angularClass = "angular";

Refresh the web page and click the button, to see the style changing:

Learn AngularJS CSS3 and HTML5 DOM manipulation with Directives      13


3 - Change the inline style of an element :

Now we'll see how to change part of an element's CSS3 style using AngularJS. Add the data-ng-style AngularJS Directive to the div :


Learn AngularJS CSS3 and HTML5 DOM manipulation with Directives     14


Next, add this javascript code to the Controller's method:

Learn AngularJS CSS3 and HTML5 DOM manipulation with Directives     15

We just toggle CSS style for an element , dynamically changing its font, color, background , corners and opacity.

  (copy-paste):

$scope.angularStyle = "";
$scope.angularStyle = { "opacity":"0.3",
                                           "borderRadius":"10px",
                                           "background":"#00F",
                                           "font":"900 Tahoma 14px",
                                           "color":"#F00"
   };

Refresh the web page and click the button:

Learn AngularJS CSS3 and HTML5 DOM manipulation with Directives       16


Compare the style's changes:

Learn AngularJS CSS3 and HTML5 DOM manipulation with Directives       17



4 - Hide/show a <div> element :

Now we'll see how to display and hide a DOM element using AngularJS. 
Add a new <div> to the page, and use the data-ng-show AngularJS Directive:

Learn AngularJS CSS3 and HTML5 DOM manipulation with Directives     18


Because "IsVisible" is boolean (true/false) , it receives the "false" value for default. Now, inside the Controller's method, just toggle the boolean value of the Model, as follows:


Learn AngularJS CSS3 and HTML5 DOM manipulation with Directives        19



 (copy-paste):

$scope.IsVisible = !$scope.IsVisible;

Refresh the web page:

Learn AngularJS CSS3 and HTML5 DOM manipulation with Directives   20


Click the button to see the div displayed and hidden:

Learn AngularJS CSS3 and HTML5 DOM manipulation with Directives      21



5 - Create a new HTML DOM custom element :

Now we'll see how to create a new DOM element by using AngularJS Directives.
We'll create a custom HTML DOM element called "Copyright", using Directives.
First, you must know that Directives can apply on HTML Elements ("E") , element's Attributes ("A") , element's Classes ("C") and also on an element's Comments ("M"), as can be learned from the official AngularJS documentation :


Learn AngularJS CSS3 and HTML5 DOM manipulation with Directives   22


We'll create an AngularJS Directive, that will receive three parameters : $scope (the Model scope), $element (the specific HTML DOM element) and $attrs (the HTML attributes of the element):

Learn AngularJS CSS3 and HTML5 DOM manipulation with Directives       23

You can read more about AngularJS Directives on the AngularJS Official web site .
Append the Directive as follows:


Learn AngularJS CSS3 and HTML5 DOM manipulation with Directives       24



  (copy-paste):

.directive('copyright', function(){
    return {
        restrict:'E',
        template:'<div class="{{style}}">(c) Copyright 2015 by {{owner}} - The AngularJS Club</div>',
        controller: function($scope, $element, $attrs){
            $scope.owner = $attrs.ownerAttr;
            $scope.style = $attrs.classAttr;
        }      
        
    }
})

As you can see, we "restrict" this Directive only to elements, and create the "template" to be embedded to the DOM by the Angular engine. This template is bound to an "anonymous" Controller which gets the element's attributes and injects them inside the $scope Model, instantiating the two properties "owner" and "style":


Learn AngularJS CSS3 and HTML5 DOM manipulation with Directives      25

Notice that the attribute named "owner-attr" is cited inside the method as "ownerAttr", using camel notation. You can use the names you want, but respecting that rule.
Now you can use your custom <copyright> HTML tag at the web page, provided it's inside the tag with the data-ng-app declaration, that means, inside the AngularJS Module. In our example, this Module is the following: <html data-ng-app="MusicApp"> :


Learn AngularJS CSS3 and HTML5 DOM manipulation with Directives     26



  (copy-paste):

<copyright class-attr="angular" owner-attr="Your_Name"></copyright>

Refresh the web page and see your brand new HTML element:

Learn AngularJS CSS3 and HTML5 DOM manipulation with Directives        27




That's All!!! You have begun learning AngularJS CSS3 and HTML5 DOM manipulation with Directives . In the next article we will continue to learn Step by Step about sending HTTP GET requests to an OData RESTful web service using the $http AngualrJS Service 
Enjoy AngularJS.....

      by Carmel Schvartzman




<<<<  PREVIOUS LESSON                NEXT LESSON >>>>





כתב: כרמל שוורצמן