Sunday, April 3, 2016

Important Note for Angular

http://www.tutorialspoint.com/angularjs/angularjs_interview_questions.htm

What is AngularJS?
AngularJS is a framework to build large scale and high performance web application while keeping them as easy-to-maintain. Following are the features of AngularJS framework.
  • AngularJS is a powerful JavaScript based development framework to create RICH Internet Application (RIA).
  • AngularJS provides developers options to write client side application (using JavaScript) in a clean MVC (Model View Controller) way.
  • Application written in AngularJS is cross-browser compliant. AngularJS automatically handles JavaScript code suitable for each browser.
  • AngularJS is open source, completely free, and used by thousands of developers around the world. It is licensed under the Apache License version 2.0.
  • AngularJS provides capability to create Single Page Application in a very clean and maintainable way.
  • AngularJS provides data binding capability to HTML thus giving user a rich and responsive experience.
  • AngularJS code is unit testable.
  • AngularJS uses dependency injection and make use of separation of concerns.
  • AngularJS provides reusable components.
  • With AngularJS, developer writes less code and gets more functionality.
  • In AngularJS, views are pure html pages, and controllers written in JavaScript do the business processing.
  • AngularJS applications can run on all major browsers and smart phones including Android and iOS based phones/tablets.

Creating Angular Frame work

Step1:

download :
https://github.com/btford/angular-express-seed
for lib only.

Step2: replace Package Json. otherwise get body-parser error:

"dependencies": {
  "anchor": "~0.10.5",
  "async": "1.5.0",
  "captains-log": "~0.11.11",
  "colors": "1.1.2",
  "commander": "2.9.0",
  "compression": "1.5.2",
  "connect": "2.30.0",
  "connect-flash": "0.1.1",
  "consolidate": "0.12.1",
  "cookie": "0.1.2",
  "cookie-parser": "1.3.5",
  "cookie-signature": "1.0.6",
  "ejs": "2.3.4",
  "ejs-locals": "1.0.2",
  "express": "3.21.2",
  "express-handlebars": "3.0.0",
  "express-session": "1.12.1",
  "fs-extra": "0.18.4",
  "glob": "5.0.15",
  "grunt": "0.4.5",
  "grunt-cli": "0.1.13",
  "grunt-contrib-clean": "0.6.0",
  "grunt-contrib-coffee": "0.13.0",
  "grunt-contrib-concat": "0.5.1",
  "grunt-contrib-copy": "0.5.0",
  "grunt-contrib-cssmin": "0.9.0",
  "grunt-contrib-jst": "0.6.0",
  "grunt-contrib-less": "1.1.0",
  "grunt-contrib-uglify": "0.7.0",
  "grunt-contrib-watch": "0.5.3",
  "grunt-sails-linker": "~0.10.1",
  "grunt-sync": "0.2.4",
  "i18n": "0.8.1",
  "include-all": "~0.1.6",
  "lodash": "3.10.1",
  "lodash.isarray": "3.0.4",
  "lodash.iserror": "3.1.1",
  "lodash.isfunction": "3.0.8",
  "lodash.isnull": "3.0.0",
  "lodash.isobject": "3.0.2",
  "lodash.isregexp": "3.0.5",
  "lodash.isstring": "3.0.1",
  "lodash.isundefined": "3.0.1",
  "merge-defaults": "~0.2.1",
  "method-override": "2.3.5",
  "mock-req": "0.2.0",
  "mock-res": "0.3.0",
  "parseurl": "1.3.1",
  "pluralize": "1.2.1",
  "prompt": "0.2.14",
  "rc": "1.0.1",
  "reportback": "~0.1.9",
  "rttc": "9.3.3",
  "sails-build-dictionary": "~0.10.1",
  "sails-disk": "~0.10.9",
  "sails-generate": "~0.13.0",
  "sails-hook-orm": "~1.0.6",
  "sails-hook-sockets": "~0.13.0",
  "sails-stringfile": "~0.3.2",
  "sails-util": "~0.11.0",
  "semver": "5.1.0",
  "serve-favicon": "2.3.0",
  "serve-static": "1.10.2",
  "skipper": "~0.5.8",
  "uid-safe": "1.1.0",
  "walk": "2.3.9",
  "waterline": "~0.11.0"}


Step 3:
run below command:
npm install body-parser
npm install express
npm install error-handler
npm install morgan
npm install method-override

npm install
node app.js



Step 4: now you can add your Jade . 
like partail3; for gui- grid

p This is the partial for view 1.
div(ng-controller='MyCtrl3')
    h2 Hello {{name}}     h2 Stock prices for: {{symbol}}        label(for='symbol') Stock symbol:        input(name='symbol', type='text', ng-model='symbol', ng-change='getData()')
        label(for='start') Start date:        input(name='start', type='text', ng-model='startDate', ng-change='getData()')
        label(for='end') End date:        input(name='end', type='text', ng-model='endDate', ng-change='getData()')
        label(for='method') Lookup method        select(ng-model='method', ng-options='o.value for o in options')
        p        .grid(ui-grid='gridOptions')
        p        p        h2 price wise {{symbol}}        .grid(ui-grid='gridOptionsprice')


Step 4: Add new controller into controller.js
'use strict';

/* Controllers */
angular.module('myApp.controllers', []).
  controller('AppCtrl', function ($scope, $http) {

    $http({
      method: 'GET',
      url: '/api/name'    }).
    success(function (data, status, headers, config) {
      $scope.name = data.name;
    }).
    error(function (data, status, headers, config) {
      $scope.name = 'Error!';
    });

  }).
  controller('MyCtrl1', function ($scope) {
    // write Ctrl here  $scope.name ="ashok";

  }).

controller('MyCtrl3', function ($scope,service) {
  // write Ctrl here  $scope.name ="Testing by Ashok";
  $scope.gridOptions =[];
  $scope.gridOptionsprice =[];

  $scope.symbol = "^VIX";
  $scope.items = [];
  $scope.startDate = '2015-03-01';
  var date = new Date();
  var month = new Date(date);
  month.setMonth(date.getMonth()+1);
  var monthnum  = null;
  monthnum = month.getMonth();
  if(month.getMonth().toString().length <2 ) monthnum ="0"+ month.getMonth()

  $scope.endDate = '2016-12-06';
  $scope.options = [{
    value: '$q'},
    {
      value: 'callback'},
    {
      value: 'watch'}];
  $scope.method = $scope.options[0];

  $scope.$watch(function combinedWatch() {
    return {
      symbol: $scope.symbol,
      startDate: $scope.startDate,
      endDate: $scope.endDate,
      method: $scope.method
    };
  }, function(value) {
    if (value.symbol && value.startDate && value.endDate && value.method) {
      console.log('Start updating ' + JSON.stringify(value));
      $scope.items = [];
      if ($scope.method.value === '$q') {
        var promise = service.getHistoricalDataWithQ($scope.symbol, $scope.startDate, $scope.endDate);

        promise.then(function(data) {
          $scope.items = data;
          $scope.gridOptions.data = $scope.items;

         // $scope.loaddetailsdata($scope.items, $scope);
        });
      }
      if ($scope.method.value === 'callback') {
        service.getHistoricalDataWithCallback(function(data) {
          $scope.items = data;
        }, $scope.symbol, $scope.startDate, $scope.endDate);
      }
      if ($scope.method.value === 'watch') {
        $scope.items = service.getHistoricalDataWithWatch($scope.symbol, $scope.startDate, $scope.endDate);
      }
    }
  }, true);


  $scope.loaddetailsdata = function(rowdata,$scope)
  {
    var details = [];


    var detailsgrid = [];

    var details = $scope.sortBy(rowdata ,{prop : "date"});

    var lowestvalue = $scope.sortBy(rowdata ,{prop : "Low"})[0]['Low'];
    var high1stvalue = $scope.sortBy(rowdata ,{prop : "high"})[0]['high'];


    $scope.mycol = [
      {field: 'High', displayName: 'High', width:"*" },
      {field: 'Low', displayName: 'Low', width:"*" },
      {field: 'Date', displayName: 'Date', width:"*" },
      {field: 'count', displayName: 'count', width:"*" }
    ]

    var counter =0;
    var monthyear = null;

    counter =1;

    var groupbydata = [];


    for(var k=0; k<details.length-1; k++)
    {

      groupbydata.push(
          {
            "High": details[k]['High'],
            "Low": details[k]['Low'],
            "Date": details[k]['Date'].split('-')[1] + "-" +details[k]['Date'].split('-')[0],
            "count":  counter

          }
      )
    }

    var obj = $scope.groupby(groupbydata,"Date");

    for(var k=0; k<obj.length-1; k++)
    {

      var min = $scope.sortBy(obj[k] , {prop: "Low"})[0]['Low'];
      var max = $scope.sortBy(obj[k] , {prop: "Low"})[obj[k].length-1]['High'];

      var lowerobj = $scope.sortBy(obj[k] , {prop: "Low"});

      for(var m=0; m<lowerobj.length-1; m++)
      {
        if(lowerobj[m]['Low'] >= min && lowerobj[m]['Low'] < Number(min)+ Number(1)) counter = counter +1;
        else        {
          detailsgrid.push(
              {
                "High": Number(min)+ Number(1),
                "Low": min,
                "Date": lowerobj[m]['Date'],
                "count":  counter

              }
          );
          counter =0;
          min = Number(min)+ Number(1);
        }
      }


    }
    $scope.gridOptionsprice.columnDefs = $scope.mycol;
    $scope.gridOptionsprice.data = detailsgrid;
  }

  $scope.sortBy = function()
  {
    //cached privated objects    var _toString = Object.prototype.toString,
    //the default parser function        _parser = function (x) { return x; },
    //gets the item to be sorted        _getItem = function (x) {
          return this.parser((_toString.call(x) === "[object Object]" && x[this.prop]) || x);
        };

    // Creates a method for sorting the Array    // @array: the Array of elements    // @o.prop: property name (if it is an Array of objects)    // @o.desc: determines whether the sort is descending    // @o.parser: function to parse the items to expected type    return function (array, o) {
      if (!(array instanceof Array) || !array.length)
        return [];
      if (_toString.call(o) !== "[object Object]")
        o = {};
      if (typeof o.parser !== "function")
        o.parser = _parser;
      //if @o.desc is false: set 1, else -1      o.desc = [1, -1][+!!o.desc];
      return array.sort(function (a, b) {
        a = _getItem.call(o, a);
        b = _getItem.call(o, b);
        return ((a > b) - (b > a)) * o.desc;
      });
    };
  }


  $scope.groupby = function(collection, property)
  {
    var i= 0, index,
        values =[],result =[];
    for(; i< collection.length; i++)
    {
      var val;
      val =collection[i][property];
      index = values.indexOf(val);
      if(index >-1)
        result[index].push(collection[i]);
      else {
        values.push(val);
        result.push([collection[i]]);
      }
    }
    return result;
  }

}).
controller('MyCtrl2', function ($scope) {
    // write Ctrl here
  });



app.factory('service', function($q, $http) {
  var fixedEncodeURIComponent = function(str) {
    return encodeURIComponent(str).replace(/[!'()]/g, escape).replace(/\*/g, "%2A").replace(/\"/g, "%22");
  };
  var format = '&format=json&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys&callback=JSON_CALLBACK';

  return {

    // return a promise to controller    getHistoricalDataWithQ: function(symbol, start, end) {
      var deferred = $q.defer();
      var query = 'select * from yahoo.finance.historicaldata where symbol = "' + symbol + '" and startDate = "' + start + '" and endDate = "' + end + '"';
      var url = 'http://query.yahooapis.com/v1/public/yql?q=' + fixedEncodeURIComponent(query) + format;

      console.log(url);

      $http.jsonp(url).success(function(json) {
        console.log(JSON.stringify(json));
        var quotes = json.query.results.quote;
        // filter + format quotes here if you want        deferred.resolve(quotes);
      }).error(function(error) {
        console.log(JSON.stringify(error));
      });
      return deferred.promise;
    },
    // add a callback from controller    getHistoricalDataWithCallback: function(callback, symbol, start, end) {
      var query = 'select * from yahoo.finance.historicaldata where symbol = "' + symbol + '" and startDate = "' + start + '" and endDate = "' + end + '"';
      var url = 'http://query.yahooapis.com/v1/public/yql?q=' + fixedEncodeURIComponent(query) + format;

      console.log(url);

      $http.jsonp(url).success(function(json) {
        console.log(JSON.stringify(json));
        var quotes = json.query.results.quote;
        // filter + format quotes here if you want        callback(quotes);
      }).error(function(error) {
        console.log(JSON.stringify(error));
      });
    },
    // let angular watch the scope change implicitly    getHistoricalDataWithWatch: function(symbol, start, end) {
      var query = 'select * from yahoo.finance.historicaldata where symbol = "' + symbol + '" and startDate = "' + start + '" and endDate = "' + end + '"';
      var url = 'http://query.yahooapis.com/v1/public/yql?q=' + fixedEncodeURIComponent(query) + format;

      console.log(url);

      var quotes = {};

      $http.jsonp(url).success(function(json) {
        console.log(JSON.stringify(json));
        quotes.list = json.query.results.quote;
      }).error(function(error) {
        console.log(JSON.stringify(error));
      });
      return quotes;
    }

  };
});






app.js
var app = angular.module('myApp', [
  'ngTouch',
  'ui.grid',
  'myApp.controllers',
  'myApp.filters',
  'myApp.services',
  'myApp.directives'
]).
config(function ($routeProvider, $locationProvider) {
  $routeProvider.
    when('/view1', {
      templateUrl: 'partials/partial1',
      controller: 'MyCtrl1'    }).
    when('/view2', {
      templateUrl: 'partials/partial2',
      controller: 'MyCtrl2'    }).
  when('/view3', {
    templateUrl: 'partials/partial3',
    controller: 'MyCtrl3'  }).
    otherwise({
      redirectTo: '/view1'    });

  $locationProvider.html5Mode(true);
});