How to: AngularJS

(by AXDS)

Example: http://jsfiddle.net/jc5au247/

Angular is a JavaScript Framework that extends HTML with directives and attributes. When an Angular app is set up on an element it sets up a ‘scope’. The JavaScript deals with what happens to the values inside this scope. This is very useful for forms, inputs, or displaying data.

The AngularJS script can be referenced using:

<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>

Once the script has been added the functionality should be all there.

There are many ‘ng-directives’ that can be used inside HTML elements. All these are online.

The main directive is ‘ng-app’ which sets up an AngularJS section. This can be set to be for the whole page by including it in the <html> as <html ng-app=”myApp”> or inside any element.

For my example I’ll set it up in a <div>:

<div ng-app="myApp">

The next directive I’ll use is ‘ng-controller’. This defines a controller inside of the ‘ng-app’. This controller, once referenced, handles all the ‘ng-model’ elements included. The ‘ng-model’ elements just bind a name to the element so it can be used.

<div ng-app="myApp">
<div ng-controller="myCtrl">
<input ng-model="fullName">
<h1>My name is {{fullName}}</h1>
<div ng-controller="myCtrl">
</div>
</div>

Inside the ‘ng-controller’, a scoped variable name can be called using double brackets:

{{variable}}

The AngularJS app is finished off by including script and calling a function to build a module. In this same script we can manipulate the controller scope.

<script>

//Sets up the App
var app = angular.module('myApp', []);

//Sets up the Controller
app.controller('myCtrl', function($scope) {
//Looks for the model 'fullName' in the controller and sets it.
$scope.fullName= "John Smith";
});

</script>

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s