Angular Basics

Posted on

in

,

To start using Angular, attach it either locally or via CDN.

 
There are 4 main elements in Angular: Directives, Modules, Controllers and Expressions.

Directives

There are HTML attributes (or elements) that call the module code. An example of this is:

<html ng-app="moduleName">

This is an attribute directive. You can also right your own element directive and call it whatever you want eg:

<project-description></project-description>

Modules

The js “class” so to speak. They contain variables and Controllers (as well as custom directives).

(function() {
  //declare module
  var app = angular.module('moduleName', []);
  //controller example
app.controller('StoreController', function(){
    this.products = gems;
    this.functionName = function(){
          //do something;
      }
  });

//var example
  var gems = [
    { name: 'Azurite', price: 2.95, canPurchase: true },
    { name: 'Bloodstone', price: 5.95, canPurchase: true },
    { name: 'Zircon', price: 3.95, canPurchase: false }
  ];
})();

‘app’ is a variable that’s just used to reference the module. The [ ] at the end of that line is an area where you can insert other module names that this module depends on.

Controllers

Kind of like the functions in the module, you can write functions inside them as well. Controllers usually start with capital letters.

app.controller('StoreController', function(){
    this.products = gems;
  });

“products” is a made up property that can be used by the HTML to output values. In this example, it’s reference the variable “gems” which is an array that has a string, number and boolean.

Expressions

These are HTML that tell which values get displayed on the page. These have to be inside a directive. An simple example of an expression is:

<body ng-controller="StoreController as store">
    <div ng-repeat="product in store.products">
      <h3>
        {{product.name}}
        <em class="pull-right">${{product.price}}</em>
      </h3>
<button ng-show="product.canPurchase">Add to Cart</button>
    </div>
  </body>

As “ng-app” specifies when a module starts, “ng-controller” is a directive that specifics when a Controller starts. Using “ng-repeat”, we are looping through the array and then duplicating the html and updating it’s values in the array. “store” and “product” are only used in the HTML. The button uses the attribute “ng-show” to only appear if a value in the js is true. “ng-hide” is the reverse of this.

View Demo

Download Demo

Leave a Reply

Your email address will not be published. Required fields are marked *

About me

Mark Wong is a front end developer with 10+ years experience. Most of his knowledge of HTML5, CSS and Js is self taught.

Calendar

May 2024
M T W T F S S
 12345
6789101112
13141516171819
20212223242526
2728293031