Victor's Blog

Live as if you were to die tomorrow. Learn as if you were to live forever


How to format a datetime column in ng-grid?

I have been playing with ngGrid control these days. Today, I want to format a date column in the grid. After a little bit research, I found it was very easy to do. All you need is put this in the gridOption object in your controller.

    $scope.gridOptions = {
      data: 'mydata',
      enableRowSelection: true,
      multiSelect: false,
      enableColumnResize: true,
      columnDefs: [
        { field: 'startDate', displayName: 'Date', cellFilter: 'date:\'yyyy-MM-dd\'' }]

In the example, I use "yyyy-MM-dd" as format. But you can change that to whatever format you like :).

Make Angular.js and MVC work harmoniously

I am always a hardcore .net guy. And I really like Angular.js too. So in my recent pet project, I tried to make these two work together. I know this is not a new topic. But I want to show you how you can fully utilize MVC inside a Angular SPA. 

First, you would need to create your normal MVC project and add angular.js into your project.

Your MVC home controller will look like 

public class HomeController : Controller
    public ActionResult Index()
      return View();

    public ActionResult Home()
      return View();

    public ActionResult Contact()
      return View();

Now create your angular.js file. Let's call it app.js

"use strict";

angular.module("demo", ["ngRoute"]).
  config(["$routeProvider", "$locationProvider", function ($routeProvider, $locationProvider) {
      .when("/", { templateUrl: "/Home/Home" })
      .when("/contact", { templateUrl: "/Home/Contact" })
      .otherwise({ redirectTo: "/" });


Now here are things you need to be aware of. 

  1.   Since Angular V1.2 ngRoute has been separated to it's own file (angular-route.js). So don't forget to reference them in the view.
  2.   $locationProvider is optional. If you want to use html5Mode, you need to change the code to $locationProvider.html5Mode(true). You also need to configure URL rewrite at server side. Otherwise when you refresh the page, you will get 404 error. 
  3.   You should set Layout = null in your views except for your start page. You may noticed in my controller, I have Index and Home. But I only reference Home in the JavaScript. I only set the layout in the Index view otherwise you will create a recursive loop between your views. Index view will only be used as place holder unless the website can't initialize angular properly. Users will only see Home view as the start page.

This is my _laytout.cshtml looks like

<!DOCTYPE html>
<html lang="en" data-ng-app="demo">
 <!-- put your links here -->
    <div class="navbar navbar-inverse" role="navigation">
        <div class="container">
            <div class="collapse navbar-collapse navbar-ex1-collapse">
                <ul class="nav navbar-nav">
                    <li><a href="#!/contact">
        <div id="body" data-ng-view class="container">


    Layout = "~/Views/Shared/_Layout.cshtml"; 


  Layout = null;

<div>Home content</div>


These is pretty much all you need to start coding your wonderful MVC&Angular website. Happy coding.

Use Geolocation API with Angular.js

Today, I played a little with the Geolocation API. I am really surprised by how accurate it is for a normal laptop if you have the Wifi enabled. So I decided to write something to make it work with Angular.js. Here is what I did:

1. Angular.js
2. Google Maps Javascript API 3.x
3. Angular ui-map

Here is my html:

<body ng-app="geo">
    <div class="container main" ng-controller="mainController">
            <div class="row">
                <div id="map_canvas" ui-map="model.myMap" class="map" ui-options="mapOptions">
                <div ng-repeat="marker in myMarkers" ui-map-marker="myMarkers[$index]">
            <div class="row" ng-show="showResult()">
               Latitude: {{lat}} <br />
               Longitude: {{lng}} <br />
               Accuracy: {{accuracy}}
            <div class="row" ng-show="!showResult()">
                Error : {{error}}
                Error Code: {{error.code}}

Here is my javascript:

var app = angular.module("geo", ["", "ui.event"])
    .controller("mainController", function ($scope) {
        $ = "0";
        $scope.lng = "0";
        $scope.accuracy = "0";
        $scope.error = "";
        $scope.model = { myMap: undefined };
        $scope.myMarkers = [];

        $scope.showResult = function () {
            return $scope.error == "";

        $scope.mapOptions = {
            center: new google.maps.LatLng($, $scope.lng),
            zoom: 15,
            mapTypeId: google.maps.MapTypeId.ROADMAP

        $scope.showPosition = function (position) {
            $ = position.coords.latitude;
            $scope.lng = position.coords.longitude;
            $scope.accuracy = position.coords.accuracy;

            var latlng = new google.maps.LatLng($, $scope.lng);
            $scope.myMarkers.push(new google.maps.Marker({ map: $scope.model.myMap, position: latlng }));

        $scope.showError = function (error) {
            switch (error.code) {
                case error.PERMISSION_DENIED:
                    $scope.error = "User denied the request for Geolocation."
                case error.POSITION_UNAVAILABLE:
                    $scope.error = "Location information is unavailable."
                case error.TIMEOUT:
                    $scope.error = "The request to get user location timed out."
                case error.UNKNOWN_ERROR:
                    $scope.error = "An unknown error occurred."

        $scope.getLocation = function () {
            if (navigator.geolocation) {
                navigator.geolocation.getCurrentPosition($scope.showPosition, $scope.showError);
            else {
                $scope.error = "Geolocation is not supported by this browser.";


Here is a working example.

Note: If you run this on your desktop without Wifi, the Accuracy will probably quite big(the bigger the value, the less the accuracy). This is because if you don't have Wifi, the geolocation api can only use your IP address to determine your location. 

Hope you can have some fun with it.