Hello World With AngularJs

To understand the basic architecture of creating a simple app lets make a Hello World with AngularJs. In the process, we will look at how to declare a new Angular app, create a controller, and create a Hello World directive.

Creating a new Angular module is pretty simple (The name can be whatever you choose):

var app = angular.module('adamsAngularApp', []);

As we have seen before, this will be used to let Angular know this is the app to look for our directives we have declared for upon DOM compilation. For this example we will just throw it up at the top of the page in the tag.

<html ng-app="adamsAngularApp">

Now to make a controller. The nice part about having controllers is to be able to manipulate the parents $scope that Angular provides in each controller or create a child $scope that can be manipulated per controller. Controllers also tend to help keep things readable and separated into nice and abstracted thoughts. Lets look at the declaration statement for a controller.

app.controller('MainController', function ($scope) {
    $scope.name = 'World'; //This is using the parent scope.
});

Angular is pretty neat with its $scope. As you can see above, we just added a name element to the scope that we can now use in our directive. Implementing the controller in part of our app is pretty simple. We could implement it solely on a div surrounding what we are using it for or if you need your whole page to use the controller, we can just throw it on the tag.

<body ng-controller="MainController">
</body>

Now lets put together a simple directive to go in the middle. Let’s take a look at the declaration of the directive we will use.

app.directive('helloWorld', function () {
    return {
        //We Will Fill this soon.
    };
});

Pretty simple. Now lets add some simple arguments in the return statement.

app.directive('helloWorld', function () {
    return {
        replace: true, //replaces new HTML element with template below
        restrict: 'AE', // directive can be used as a new HTML element or an attribute
        template: '<h3>Hello World. {{ name }}</h3>' //Template that will replace
    };
});

All comments are inline in the example. Basically, when this directive gets executed it’s going to replace the html element we created with the template in the directive. Also, take a look at how the $scope.name was used in the template. Upon execution this will be rendered as the value of name which is ‘Welcome.’ Now lets finish it off with the full html front.

<html ng-app="adamsAngularApp">
	<head>
		//Include reference to AngularJs
	</head>
	<body ng-controller="MainController">
		<hello-world />
	</body>
</html>

One thought on “Hello World With AngularJs

  1. Pingback: JavaScript Regex To Get Parts Of URL - Adam Things

Leave a Reply

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