Showing posts with label AngularJS. Show all posts
Showing posts with label AngularJS. Show all posts

Saturday, July 11, 2015

AngularJS UTC to Local Time Filter

In a previous post I detailed how to to implement the UTC time to local time conversion in Vanilla JS. Now let's take it a step further and utilize it in an AngularJS application. The best path forward will be to create a filter which will format the string being rendered. The end result will allow us to do something like the following:
<div class="row" ng-repeat="time in viewModel.times">
  <div class="col-md-6">
    <time datetime="{{time}}">{{ time | utctolocal }}</time>
  </div>
</div>
Basic usage is thus: create the filter, add the script tag to load the filter, add the module to be a dependency on the app.
angular.module('intPonfilters', [])
 .filter('utctolocal', function () {

 var LeadingZero = function (val) {
  return (val < 10) ? "0" + val : val;
 },
 ToDateString = function (dateObj, dateFormat) {
  var curr_year = dateObj.getFullYear(),
   curr_month = LeadingZero(dateObj.getMonth() + 1),
   curr_date = LeadingZero(dateObj.getDate()),
   curr_hour = LeadingZero(dateObj.getHours()),
   curr_min = LeadingZero(dateObj.getMinutes()),
   curr_sec = LeadingZero(dateObj.getSeconds()),
   curr_ampm = "AM";
  if (curr_hour > 11) {
   curr_ampm = "PM";
   curr_hour = (curr_hour == 12) ? 12 : curr_hour - 12;
  }
    var timestamp = curr_year + "-" + curr_month + "-" + curr_date + " " + curr_hour + ":" + curr_min + ":" + curr_sec + " " + curr_ampm + " " + LocalTimeZone();
  return timestamp;
 },
  LocalTimeZone = function() {
    // From http://stackoverflow.com/questions/2897478/get-client-timezone-not-gmt-offset-amount-in-js
    var now = new Date().toString(),
        timezone = now.indexOf('(') > -1 ?
          //now.match(/\([^\)]+\)/)[0] :  // Uncomment this line to return the full time zone text
          now.match(/\([^\)]+\)/)[0].match(/[A-Z]/g).join('') :  // Uncomment this line to return the full time zone abbreviation
          now.match(/[A-Z]{3,4}/)[0];
    if (timezone == "GMT" && /(GMT\W*\d{4})/.test(now))
      timezone = RegExp.$1;
    return timezone;
  };

 return function (input) {
  var inputDate = new Date(input);
  var dateString = ToDateString(inputDate);
  return dateString;
 };
});


An example can be found in my UTCtoLocalAngularJS GitHub repository.

Wednesday, September 3, 2014

IP Subnet Mask Expander The Web Client

In a previous post, I created a Node.Js project, IPSubnetMaskToIPRange, that takes a file with a list of IP subnet masks and then outputs 2 CSV files (one of the IP ranges and one of the expanded IP ranges).

Sometimes when I create a cool project, I end up having flashes of changes and improvements that I can make to it. This is one of those cases.

This project uses the same base functionality as the Node.Js project. This has the same functionality, except it is completely run from the browser leveraging AngularJS and Bootstrap 3. It outputs the ranges to the screen and provides buttons to download the IP ranges and the expanded IP ranges.

The working site can be found at IP Subnet Mask Expander and the source can be found on GitHub.

Monday, August 18, 2014

Angular.JS Service to Download Data Generated in Browser

I ran into a situation where I wanted to be able to download data that was generated in the browser. There are several libraries that handle this scenario, but I thought it should have been simpler than those large libraries.

Below is the result. It supports IE 10+ (potentially 9 haven't tested), FireFox, and Chrome.
angular.module('FileDownload')
.service('SaveFileService', [function () {
        this.Save = function(data, filename, mimeType) {
            var blob = new Blob([data.join('\n')], {type: mimeType});
            if (/\bMSIE\b|\bTrident\b|\bEdge\b/.test(navigator.userAgent)) {
                window.navigator.msSaveOrOpenBlob(blob, filename);
            } else {
                var url  = window.URL || window.webkitURL,
                    link = document.createElementNS("http://www.w3.org/1999/xhtml", "a"),
                    event = document.createEvent("MouseEvents");
                
                link.href = url.createObjectURL(blob);
                link.download = filename;

                event.initEvent("click", true, false);
                link.dispatchEvent(event);
            }
        };
    }]);
Basically, the Save function does a couple things. For IE browsers, it creates the blob and calls the msSaveOrOpenBlob (the msSaveBlob function would make IE only display a save dialog and not give the user the option to open it). For all other browsers, it creates the blob, generates a link element, creates a mouse click event, and has the link dispatch the created event.

To use the service, just inject the service into the controller and call the Save function w/ the needed parameters.

UPDATE 2015-09-28: Per Kevin's feedback, I have updated the regular expression to catch the Edge browser (so much for Microsoft making a standards evergreen browser). I have verified that the above change works as advertised.