Google+

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 >>>>





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