AngularJS · Javascript · Jquery

First GitHubNg app – Beginner Part 1 – AngularJS

Welcome to my first AngularJS learning module, wherein, i have done some, not so perfect, beginner application which lists the Github users and their corresponding profile details with repositories owned, extended to list the contributors too.

Some of my salient learning points to note about AngularJS:

  • ng-app, ng-controller => directives are the most basic directives which angular monitors to work with in dealing with view.
  • For Images with loading delays, use ng-src than src attribute. Angular does not display image till source is loaded using ng-src directive.
  • Angular Philosophy => Throws error to console, than breaking page.
  • ng-repeat => directive to use for repeating items from collection.
  • Filters can be specified inside ng-repeat => ng-repeat=”item in collection | orderBy:<attributeName>” => + or – sign tells order.
  • ng-include => fill in an HTML template.
  • ng-show => show r hide elements in view
  • Service or controllers should not directly talk to View in MVW model. Directives should.
  • Try avoiding native JS functions over Angular viz. timers, etc. Helps in better binding and unit testable.
  • Routing => done via ngRoute dependency module. Goes along with ng-view a placeholder to insert views.

In this application, i have used Angular Routing mechanism to route the pages as per need. This routing information should be the first JS script the angular should look and understand the whole structure.

Please feel free to play with the application:  http://plnkr.co/edit/aZ86hP6BnrYGmD68PSfL

Below are the explanation about few code excerpts:

index.html:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
<html ng-app="myApp">
<head>
    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.css" rel="stylesheet" />
    src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js">
    src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.7/angular-route.js">
    src="app.js" type="application/javascript">
    src="mainControl.js" type="application/javascript">
    src="httpService.js" type="application/javascript">
    src="userInfoController.js" type="application/javascript">
    src="repositoryController.js" type="application/javascript">
</head>
<body>
 <h1>Github app...</h1>
  place holder with ng-view directive.. </body>
</html>

In the above code, the ng-app directive is very important, this informs the Angular framework to load itself and attach to this webpage. The script section should have angular js as the first item followed by the routing script. The rest scripts order does not matter belonging to within the application. Inside the body, i have added ng-view directive, this directive informs the angular to look up the routing configuration and insert the corresponding view/html file based on the URL of the browser.

app.js => Routing configuration

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
(function () {
    var myAppmodule = angular.module("myApp", ["ngRoute"]); //[] contains dependency on services

    myAppmodule.config(function ($routeProvider) {
        $routeProvider
            .when("/", {
                templateUrl: "listUser.html",
                controller: "MainController"
            })
            .when("/user/:username", {
                templateUrl: "userDetails.html",
                controller: "UserInfoController"
            })            
            .otherwise({
                redirectTo: "/"
            });
    });

}());

In the above code,at line 2, invoking angular.module API, configures the angular framework with the details required for this application to work. In this case, the first argument is the name of the application, can be anything, but should be same across the application. Second argument is the dependencies on which this application via angular dependent on.
On line 4, angular is instructed to configure the application with the routing options mentioned inside it. .when function describes the scenario and action (html and associated controller). .otherwise is the last fall back choice.

mainControl.js

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
(function () {
    var app = angular.module("myApp");

    var mainController = function ($scope, myhttp, $location) {
        var onSuccess = function (data) {
            $scope.users = data;
            $scope.sortColumn = "+login";
        };

        var onError = function (errorData) {
            console.log(errorData);
        };

        myhttp.Users().then(onSuccess, onError);

        $scope.profileLinkClicked = function (userName) {
            $location.path("/user/" + userName);
        };
    };
    app.controller("MainController", mainController);
}());

at line 2, i am getting the reference to the already loaded angular module for my application. The controller code goes inside a method with a name, here at line 4. Any data which needs to be transferred between view and controller is done via $scope service. The $location service (helper methods in .NET world) is used to get the URL parameters which browser is operating over.
At line 20, i am describing the controller information. The first argument is a string which has to match between the view and corresponding controller. Here, multiple views can point and communicate talk to a controller.

repos.html

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
<div ng-controller="RepositoryController">
    <h3 ng-hide="!repoDetails">Repository owned:</h3>

    <div ng-repeat="repo in repoDetails">    
        
        <img 
          ng-show="!repo.showContributors"
          src="http://cdn.shopify.com/s/files/1/0434/3957/t/32/assets/icon-arrow-right-small.png" 
          ng-click="listContributors(repo)" />
        <img 
          ng-show="repo.showContributors"
          src="http://cdn.shopify.com/s/files/1/0434/3957/t/26/assets/icon-arrow-down-small.png" 
          ng-click="repo.showContributors = false" />
        {{repo.name}}
        
        <div id={{repo.name}} style="padding-left: 55px">
          <ul ng-if="repo.showContributors">
            <li ng-repeat='contributor in repo.contributors'>{{contributor.login}}</li>
          </ul>
        </div>
    </div>
</div>

Above html file is a bit advanced and required for my requirement, got it resolved with help from Stackoverflow people. Wherein, upon user profile link is clicked, the web displays profile details along with repositories owned. On clicking over icon of the owned repository item, it expands to display the contributors list. The template to display for any repository is same, hence i wanted a static simple solution but only data change controlled from Model.

On line 4, the loop is iterated over the repository owned. Under each repository owned, a image is set based on the click action. This is decided by a bool state variable showContributors, its configured to be monitored under ng-Show directive. ng-Click is used to wire the eventing system. Hence these attributes decide to act upon the model data available.

Thanking you,
Zen 🙂

Advertisements

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s