AngularJs — First Steps

Hi it’s been a while since i don’t share anything about what I've learn recently.

So, i’ve been working on the last month or bit more on a new technology for me, it’s as the tittle name AngularJs.

What’s AngularJs?

AngularJs it’s a Javascript Framework develop by Google, that lets you extend the HTML in the application.

There are some important characteristics of AngularJs that makes it such a powerful framework that i’ll cover on my next entries:

  • Two Way Data Biding
  • Dependency Injection
  • Templates

How do i import AngularJs into my application?

Angular it’s simply a script that we can reference in our HTML file and it will start working. You can import AngularJs with the following line:

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

In this case it will import the minified version of the script.

What’s $scope?

Scope it’s an Angular object that is associated for every controller that you create. It let’s you access data from the views of your controllers.

Example

Here I've defined a simple html:

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<script type="text/javascript" src="index.controller.js"></script>
<title>My HTML File</title>
</head>
<body ng-app="myApp">
<div ng-controller="IndexController">
<p>Message from IndexController {{greeting}}</p>
</div>
</body>
</html>

Important points:

  1. We reference the AngularJs script in the head of the HTML.
  2. Also we have another reference to another script that is in the same folder in which we’ve defined our controller.
  3. In the body tag, with the ng-app we are setting the Angular name application, that will match with the one on the controller.
  4. The value ‘greeting’ inside the curly brackets in the <p> tag, it’s going to be bind from the controller.
  5. And finally we set the controller on the div with ng-controller.

And then i created the controller file (index.controller.js), that is referenced in the HTML file.

var myApp = angular.module('myApp',[]);
myApp.controller('IndexController', ['$scope', function($scope) {
$scope.greeting = 'Hola!';
}]);

Here it’s an variable named ‘myApp’ which will hold the angular module that is created named ‘myApp’ and it’s also referenced in the HTML file on the body tag.

Also to create the controller just with the ‘myApp.controller’ and then we specify the parameters:

  • ‘IndexController’ the name of the controller.
  • Within the squared brackets we inject the $scope the object that we mentioned before.
  • And then the definition on the controller by a function.

Result

The message is as we expect, in the controller $scope.greeting that we setted before to ‘Hola!’, it’s being bind to the view.

index.html