HTML Dog
Skip to navigation

Angular

AngularJS is an open-source client-side JavaScript framework that uses HTML as its templating language. It’s notable for it’s philosophy that declarative programming is better than imperative programming for wiring up user interfaces and creating modular components.

Angular is MVC but it works quite differently from Backbone.

Templates and views in Angular are analogous, and are just regular HTML with some added sugar. In fact, you can put together a (very) simple Angular app without a single line of JavaScript:


<input ng-model="name">

<h1>Hello {{ name }}</h1>

The ng-model attribute on the input element connects the value of the input to a model called “name”. Angular creates this model for us; it doesn’t need to be declared elsewhere. Then, in the h1, we bind to the value of the “name” model. When you update the input, the h1 will update too.

When you want to build something useful in Angular, you use a controller, which is just a JavaScript function:


var AppCtrl = function ($scope) {
    $scope.name = "Yoda";
};

A controller has a scope, which is an area of DOM it has access to. Giving a controller a scope looks like this:


<div ng-controller="AppCtrl">
    <input ng-model="name">
     <h1>Hello {{ name }}</h1>
</div>

A model exists within a controller’s scope, so in the above example the “name” model would be set to “Yoda” by default, but the input would update the model and the h1 as you typed.

You’ll notice the $scope variable that the controller takes as an argument, but that seems to come from nowhere. This is injected into the controller using a system called dependency injection. It’s a complex area, but is a useful tool for building modular apps.