Rainbow Coding

Introducing Simple Angular.js tutorial

Angular.js is popular technology for organizing code for client-side JavaScript apps. Here's a simple way to get started.

Angular.js is really popular technology for client-side JavaScript apps.

To get started with angular.js, all you need to do is to include it into your page and it just works. No need for dependencies such as jQuery etc. Below is about the simplest possible app you can write with angular.js.

app.js

angular.module('myApp')
.controller('MyAppCtrl', function($scope) {
  $scope.variable = 1;
  $scope.increment = function() {
    $scope.variable += 1;
  }
});

index.html

<html>
<head>
  <title></title>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0/angular.min.js"></script>
</head>
<body ng-app="myApp">
<div ng-controller="MyAppCtrl">
  {{variable}}
  <button ng-click="increment()">increment</button>
</div>
<script type="text/javascript" src="app.js"></script>
</body>
</html>

Code should be pretty much self-explanatory, but here are some important points.

  • ng-app directive must be used somewhere in the application. It takes module name as parameter. Above example uses it for body, so anything outside body won't be affected.
  • ng-controller directive defines controller for element. It takes module as parameter. Above example uses it for div, so anything outside the div won't be affected.
  • {{}} notation will allow referencing variables from controllers $scope. We use it to show the value of "variable"
  • ng-click directive works pretty much same as onClick, just that it also works inside $scope, not globally.

Of course, there is much more to know about angular.

Angular has lots of patterns to learn, such as directives, controllers, modules, services, interceptors, transformers, digest loops and dependency injections. There will be more tutorials in future that explain these concepts in more detail.

© RainbowCoding 2010-2024