Login or Sign Up to become a member!
LessThanDot Sit Logo

LessThanDot

Web Developer

Less Than Dot is a community of passionate IT professionals and enthusiasts dedicated to sharing technical knowledge, experience, and assistance. Inside you will find reference materials, interesting technical discussions, and expert tips and commentary. Once you register for an account you will have immediate access to the forums and all past articles and commentaries.

LTD Social Sitings

Lessthandot twitter Lessthandot Linkedin Lessthandot friendfeed Lessthandot facebook Lessthandot rss

Note: Watch for social icons on posts by your favorite authors to follow their postings on these and other social sites.

Your profile

    Search

    XML Feeds

    Google Ads

    « Angularjs and ng-gridNancy and jquery datatables; formatting data »
    comments

    Introduction

    It's superbowl Sunday and between the snacks it is time to learn something new. Today my eye fell on Angularjs. Angularjs is an MVC framework for javascript. It kinda puts the controllers and model on the clientside and not on the serverside like ASP.Net MVC does. I will use Nancy as our service to provide us with json data.

    Server

    Our server is pretty simple.

    Just make an empty asp.net application and add a Models folder.
    Here is my model.

    1. using System;
    2.  
    3. namespace NancyJTable.Models
    4. {
    5.     public class PlantModel
    6.     {
    7.         public int Id { get; set; }
    8.         public string Name { get; set; }
    9.         public string Genus { get; set; }
    10.         public string Species { get; set; }
    11.         public DateTime DateAdded { get; set; }
    12.     }
    13. }

    And here is my module, which I put in the Modules folder.

    1. using System;
    2. using System.Collections.Generic;
    3. using System.Linq;
    4. using Nancy;
    5. using NancyJTable.Models;
    6.  
    7. namespace NancyJTable.Modules
    8. {
    9.     public class PlantsModule:NancyModule
    10.     {
    11.         public PlantsModule()
    12.         {
    13.             Get["/plants/{Id}"] = parameters => Response.AsJson(GetPlantModels().SingleOrDefault(x => x.Id == parameters.Id));
    14.             Get["/plants"] = parameters =>
    15.                 {
    16.                     return Response.AsJson(GetPlantModels());
    17.                 };
    18.         }
    19.  
    20.         private IList<PlantModel> GetPlantModels()
    21.         {
    22.             var plantModels = new List<PlantModel>();
    23.             for (var i = 1; i <= 25; i++)
    24.             {
    25.                 var j = i.ToString("000");
    26.                 plantModels.Add(new PlantModel()
    27.                 {
    28.                     Id = i,
    29.                     Name = "name" + j,
    30.                     Genus = "genus" + j,
    31.                     Species = "Species" + j,
    32.                     DateAdded = DateTime.Now
    33.                 });
    34.             }
    35.             return plantModels;
    36.         }
    37.     }
    38.  
    39. }

    Client

    First I added another empty ASP.Net web application project to our solution.

    I added angularjs to my project. It is on nuget so no problems there.

    I want to add a list of plants and I want a details page.

    First I need to start with adding my app.j in the js folder. This will take care of the routes.

    1. angular.module('plantsapp', []).
    2.   config(['$routeProvider', function ($routeProvider) {
    3.       $routeProvider.
    4.           when('/plants', { templateUrl: 'partials/plants.html', controller: PlantsController }).
    5.           when('/plants/:Id', { templateUrl: 'partials/plant.html', controller: PlantController }).
    6.           otherwise({ redirectTo: '/plants' });
    7.   }]);

    You already see that I have two partial views and 2 controllers.

    The controllers are in my controllers.js file.

    1. function PlantsController($scope, $http) {
    2.     $http.get('http://localhost:59025/plants').success(function (data) {
    3.         $scope.plants = data;
    4.     });
    5. }
    6.  
    7. function PlantController($scope, $routeParams, $http) {
    8.     $http.get('http://localhost:59025/plants/' + $routeParams.Id).success(function (data) {
    9.         $scope.plant = data;
    10.     });
    11. }

    So I have a Plantscontroller that uses a get to get my json from my nancy service. And I have a PlantController that uses the routeparameter to tell which plant to get from my service.

    See how I inject http and how it magically gets injected for me.

    The next thing is to create an index.html which is the base of our views.

    1. <!DOCTYPE html>
    2.  
    3. <html lang="en" ng-app="plantsapp">
    4. <head>
    5.     <title>Plants</title>
    6.     <script src="/Scripts/angular.js"></script>
    7.     <script src="/js/controller.js"></script>
    8.     <script src="/js/app.js"></script>
    9. </head>
    10. <body>
    11.     <div ng-view></div>
    12. </body>
    13. </html>

    In the html tag I added an ng-app with the name I provided in my app.js.

    I import angular.js, controller.js and app.js.

    And I added a div with an ng-view attribute.

    Now I need the partials which I put in the partials folder.

    1. <table id="table_id">
    2.     <thead>
    3.         <tr>
    4.             <th>Id</th>
    5.             <th>Name</th>
    6.             <th>Genus</th>
    7.         </tr>
    8.     </thead>
    9.     <tbody ng-repeat="plant in plants">
    10.         <tr>
    11.             <td>{{plant.Id}}</td>
    12.             <td><a href="#/plants/{{plant.Id}}">{{plant.Name}}</a></td>
    13.             <td>{{plant.Genus}}</td>
    14.         </tr>
    15.     </tbody>
    16. </table>

    This is my plants.html file and it uses the plants object which I have added to the scope in my controller.

    See how I add the link (the # is important).

    The next file is the detail view, plant.html.

    1. <table id="table_id">
    2.     <tr>
    3.         <th>Id</th>
    4.         <th>{{plant.Id}}</th>
    5.     </tr>
    6.     <tr>
    7.         <th>Name</th>
    8.         <th>{{plant.Name}}</th>
    9.     </tr>
    10.     <tr>
    11.         <th>Genus</th>
    12.         <th>{{plant.Genus}}</th>
    13.     </tr>
    14. </table>

    Here I use plant because that is what I used to add the the scope in my controller.

    And that is it.

    Here are the screenshots. Look also at the url in the addressbarr.

    The plants.

    And here the detail view.

    Conclusion

    Yeah, uhm. Not sure. Not saying this is bad, but how will this scale ;-). One thing is for sure, the documentation was very good to get my started. Not that I read it before beginning but once I did, it helped.

    About the Author

    User bio imageChris is awesome.
    Social SitingsTwitterHomePageLTD RSS Feed
    angularjs, c#, nancy
    InstapaperVote on HN

    7 comments

    Comment from: SQLDenis [Member] Email
    SQLDenis Framework fatigue didn't kick in yet?
    02/03/13 @ 07:57
    Comment from: Christiaan Baes (chrissie1) [Member]
    Christiaan Baes (chrissie1) Oh yeah. I wish someone had a monopoly and take over this damn mess we call programming.
    02/03/13 @ 08:01
    Comment from: SQLDenis [Member] Email
    SQLDenis Yep, back in the year 2000 or so there was none of this stuff....no libraries, 2 browsers, php, asp, jsp, coldfusion or perl were the webstack technologies and that was pretty much what 93% of the world used
    02/03/13 @ 08:16
    Comment from: Jonathan Channon [Visitor] Email · http://blog.jonathanchannon.com
    Jonathan Channon Nice work. I've been reviewing Angular myself. One thing you could do is make a separate service or repository if you will and that can get injected into your controllers!
    02/03/13 @ 11:33
    Comment from: Hadi Hariri [Visitor] · http://hadihariri.com
    Hadi Hariri IF you use $resource instead of $http, you get a higher-level abstraction and you don't have to deal with any of the HTTP calls.

    @SQLDenis,

    Yes, back in the old days it was just CGI or ISAPI, but things are also different. Back then it was very much client-server with HTTP. This is all about being client with server only acting as data and processing, thus improving the experience with a more fluid and responsive design.
    02/03/13 @ 12:47
    Comment from: TYler Brinks [Visitor]
    TYler Brinks One feature worth elaborating on is Angular's HTML5 mode. That allows any browser supporting the history API to ditch the hashbang and use standard URL paths with the option to gracefully fall back.
    Having built a couple medium to large scale SPAs with Angular, I'd say it scales better than most of today's popular MV(*) JavaScript frameworks. It's on par with Ember, no doubt.
    02/05/13 @ 08:15
    Comment from: Jason Lee [Visitor] Email
    Jason Lee Ive googled this all day and haven't been able to get around this error. Closest Ive gotten was using jsonp instead of $http. Is there something I need to configure or set up to get this to work in local development and on a server.

    I tried adding delete $http.default.headers.common 'x-requested-with'. Ive also tried writing the angular side about 50 different ways :)


    XMLHttpRequest cannot load http://localhost:12116/plants. Origin http://localhost:51532 is not allowed by Access-Control-Allow-Origin.
    05/10/13 @ 10:14

    Leave a comment


    Your email address will not be revealed on this site.

    To mislead the spambots.

    Your URL will be displayed.
    (Line breaks become <br />)
    (Name, email & website)
    (Allow users to contact you through a message form (your email will not be revealed.)