The Family Page–Part 8, using Angular.js to show the wish list.

Last time we made the wishlist datamodel, view and controller. Now we will start to use angular.js to show our data.

First I create some data to show – this is done the Seed() method of the migrations Configuration class. I have created a family “Dad”, “Mom”, “Son” ,”Daughter” and given each a few wishes. “Dad” has the role “Admin”, while “Mom” has the role “Editor”. The kids are normal users.

protected override void Seed(TheFamilyPage.Models.ApplicationDbContext context) { var userManager = new ApplicationUserManager(new UserStore<ApplicationUser>(context)); var roleManager = new ApplicationRoleManager(new RoleStore<IdentityRole>(context)); var dad = CreateUser(userManager, roleManager, "dad@thefamilypage.com", "Dad@123456", "Dad", ApplicationDbInitializer.AdminRoleName); var mom = CreateUser(userManager, roleManager, "mom@thefamilypage.com", "Mom@123456", "Mom", ApplicationDbInitializer.EditorRoleName); var son = CreateUser(userManager, roleManager, "son@thefamilypage.com", "Son@123456", "Son", ApplicationDbInitializer.UserRoleName); var daughter = CreateUser(userManager, roleManager, "daughter@thefamilypage.com", "Daughter@123456", "Daughter", ApplicationDbInitializer.UserRoleName); context.Wishes.AddOrUpdate(p => p.TheWish, new Wish { TheWish = "LEGO Star Wars game", Shop = "The Toy Store", Note = "The new one", User = son }); context.Wishes.AddOrUpdate(p => p.TheWish, new Wish { TheWish = "Bike", Shop = "Bikes online", Note = "Must be blue", Url = "http://www.bikesonline.org", User = son }); context.Wishes.AddOrUpdate(p => p.TheWish, new Wish { TheWish = "Bike", Shop = "Bikes online", Note = "The pink one with stars on the saddle", Url = "http://www.bikesonline.org", User = daughter }); context.Wishes.AddOrUpdate(p => p.TheWish, new Wish { TheWish = "Dress", Shop = "Cocktaildresses'R'Us", User = mom }); context.Wishes.AddOrUpdate(p => p.TheWish, new Wish { TheWish = "Xamarin Studio", Shop = "Xamarin", Url = "http://xamarin.com", User = dad }); } static ApplicationUser CreateUser(ApplicationUserManager userManager, ApplicationRoleManager roleManager, string email, string password, string name, string roleName) { var user = userManager.FindByName(email); if (user == null) { user = new ApplicationUser { UserName = email, Email = email, Name = name }; userManager.Create(user, password); userManager.SetLockoutEnabled(user.Id, false); } // Add user admin to Role Admin if not already added var rolesForUser = userManager.GetRoles(user.Id); var role = roleManager.FindByName(roleName); if (role == null) { role = new IdentityRole(roleName); roleManager.Create(role); } if (!rolesForUser.Contains(role.Name)) { userManager.AddToRole(user.Id, role.Name); } return user; }

 

 

 

The current wishlist index view looks like this:

@model IEnumerable<TheFamilyPage.Models.Wish>

@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>

<p>
    @Html.ActionLink("Create New", "Create")
</p>
<table class="table">
    <tr>
        <th>
            @Html.DisplayNameFor(model => model.TheWish)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.Url)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.Shop)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.Note)
        </th>
        <th></th>
    </tr>

@foreach (var item in Model) {
    <tr>
        <td>
            @Html.DisplayFor(modelItem => item.TheWish)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.Url)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.Shop)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.Note)
        </td>
        <td>
            @Html.ActionLink("Edit", "Edit", new { id=item.Id }) |
            @Html.ActionLink("Details", "Details", new { id=item.Id }) |
            @Html.ActionLink("Delete", "Delete", new { id=item.Id })
        </td>
    </tr>
}

</table>

Which produces the output:

image

 

This is lists all the wishes but we can not see who wishes for what, and the code is not very pretty.  I will try to make it a little better by using angular.js.

First I change the Index method in the controller so it does not return any data. Angualr will ask for the data in another controller method called GetWishes. GetWishes returns its data as JSON, so it is directly usable by angular:

        public async Task<ActionResult> Index()
        {
            return View();
        }

        [HttpGet]
        public async Task<JsonResult> GetWishes()
        {
          return Json(await db.Wishes.ToListAsync(), JsonRequestBehavior.AllowGet);
        }

Next I need to use angualr.js – I do this by adding these two lines to the _layout.cshtml file:

  <script src="~/Scripts/angular.js"></script>
  <script src="~/Scripts/angular-resource.js"></script>

Then we need to add a javascript file of our own. I have called it wish.js, and I have create a ‘js’ folder for my own javescript files.

Wish.js contains a small module ‘ngWishApp’ with wishController that gets the data from my WishesController.cs:

var ngWishApp = angular.module("ngWishApp", ['ngResource']);

ngWishApp.factory("wishService", function($resource) {
  return {
    getWishes: $resource("/Wishes/GetWishes")
  }
});

ngWishApp.controller("wishController", function($scope, wishService) {
  $scope.wishes = wishService.getWishes.query({}, isArray = true);
});

To really understand the module, factory and reosurce stuff going on here, you can read this very good article at dotnetcurry.

Now we only need to update our WishesIndex view – I remove all the razor view code, and add some simple angualr.js code:

@model IEnumerable<TheFamilyPage.Models.Wish>
<script src="~/js/wish.js"></script>

@{
    ViewBag.Title = "Index";
}

<h2>Wishes</h2>

<div ng-app="ngWishApp">
  <div ng-controller="wishController">
    <ul>
      <li ng-repeat="item in wishes">
        {{item.UserName}}, {{item.TheWish}}, {{item.Url}}, {{item.Shop}}, {{item.Note}}
      </li>
    </ul>
  </div>
</div>
<p>

ng-app in the outer div-tag defines the area of html code where the ngWishApp is active. Further we indicate that we are using the wishController. I then create a list of wishes using the ng-repeat keyword. 

The result looks like this:

image

There is no doubt that this can be more pretty, but right now I am satisfied that I have started to use angualr.js.

Advertisements

About Lund

Owner of iCodeIT, a software consulting company. I am primarily working the .NET development and architecture.
This entry was posted in Ikke kategoriseret. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

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