Basic AngularJS (1.3.13) SPA

Being on the saga to master AngularJS I decided to post about a basic application with a  module and controller that returns static data to the view. The view and controller are married by routing. This post will not go in detail on how things work.

index.html

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" data-ng-app="app">
<head>
    <meta charset="utf-8" />
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.13/angular.min.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.13/angular-route.min.js"></script>
    <script src="app.module.js"></script>
    <script src="app.config.js"></script>
    <script src="posts.module.js"></script>
    <script src="postsController.js"></script>
<body>
    <div>
      <div data-ng-view></div>
    </div>
</body>
</html>

line 2 defines data-ng-app=”app” which is an attribute Every angular application should have  (could live in other elements)

Line 8-11 are the JavaScript inclusion for the application (in a real website one would minify and merge the files together for faster loading)

Line 14 is where the view will be loaded     <div data-ng-view></div>

AngularJS is modular in such a way that one could separate functionality but one or more modules can be injected into another module for richer functionality.

app.module.js

(function () {
    'use strict';
    
    angular.module("app", [
        'ngRoute',
        'app.posts'
    ]);
   
})();

The main module’s name should match the data-ng-app=”app” as above

ngRoute and app.posts are injected modules that the app module will make use of.

ngRoute is a standard module that takes care of routing

app.posts is a custom module that is built for this application

app.config,js

(function(){
  'use strict';
  
    angular.module("app").config(['$routeProvider',
      function ($routeProvider) {
        $routeProvider
            .when('/', {
		  controller: 'postsController',
		  controllerAs: 'vm',
                  templateUrl: 'posts.html'
            })
            .otherwise({
                redirectTo:"/"
            });
     }
    ]);
});

Every module may have a configuration and this is the first thing that will execute from that module for initialization.  In this case the main module has routing initialized.

$routeProvider is where routing is setup.

in a nut shell the above is configuring that when visiting root ‘/’ use controller postsController with vm alias and use posts.html as a view template else redirect to root.

posts.module.js

(function () {
    'use strict';

    angular.module('app.posts', []);
    
})();

This is just the definition of posts module which has no dependencies. As one may notice it is almost the same as app.module.js

postsController.js

(function () {
    'use strict';

  // Register
  angular
        .module('app.posts')
        .controller('postsController',postsController);
        
 // Inject
 postsController.$inject = [];        

  // Function
 function postsController() {
    var vm = this;
    vm.persons = [
                   {
                      "Name":"Alfreds Futterkiste",
                      "City":"Berlin",
                      "Country":"Germany"
                   },
                   {
                      "Name":"Berglunds snabbkkp",
                      "City":"Luleb",
                      "Country":"Sweden"
                   }
                 ];
  }

})();

Controllers can be written in different ways but the most elegant (opinionated) is Register/Inject/Function

Register the controller with a function name

Inject parameters

Function is the controller’s logic. The variable vm stands for ViewModel because that’s exactly what it represents. and Some JSON data is set to a property in that view model.

posts.html

<ol>
    <li data-ng-repeat="person in vm.persons">
      {{ person.Name + ', ' + person.Country }} <br/>
    </li>
</ol>

This is the view template that will be loaded instead of <div data-ng-view></div>

data-ng-repeat means repeat this element for as much items in the list

The vm here is the alias that was defined in the routing and has nothing to do with the controller vm variable ( but for logical sense it is the same )

{{}} mean execute the expression in between which in this case are the Name and Country

 

here is the code

Same example but using $http request here

Best Practices learned so far

Always encapsulate your code as a module to avoid polluting the global namespace

Always use ‘use strict’;

Use employ single responsibility principle

Separate every thing in files and make sure you organize files by feature if the application is large

Code neatly and use indentation

Love the community: When posting on the internet about code always include a version number

Experts worth following

John Papa

Tod Motto 

Resources

Very good introduction by Dan Wahlin : https://www.youtube.com/watch?v=i9MHigUZKEM

www.angular-tips.com

www.scotch.io

www.egghead.io

https://angularjs.org/

https://www.ng-book.com/

Please like & share:

Leave a Reply