Upgrading ng-app to use Controller as (Pluralsight Course)

Share httpJunkie.com on..
Tweet about this on TwitterShare on FacebookShare on Google+Share on TumblrEmail this to someone

This post is created to help others that are using the wonderful course from Pluralsight titled:

Building a Site with Bootstrap, AngularJS, ASP.NET, EF and Azure
by Shawn Wildermuth

I understand that these courses can get outdated quickly when using something like Angular which is changing so rapidly and I wanted to learn using this course but while also taking advantage of 1.3+ features and implementing Controller as instead of $scope. I have used the Angular Style Guide by John Papa to aid me in creating the updated code for this course and I will document everything from the first few videos of the second Angular Module in this course. If you need help before that, see my post in the discussion which hints at how to use Controller as in the first module, but that part should be pretty simple, it’s once you start adding modules and using it in conjunction with Controller as and best/simplest syntax as shown in the style guide..

Here is what your code would look like using the Controller as syntax right before we add our second controller in the Deeper into AngularJs module at the end of the video named “Adding Routes

/ng-modules/home-index.js

angular
    .module("homeIndex", ["ngRoute"])
    .config(config)
    .controller("topicsController", topicsController);

    function config($routeProvider) {
        $routeProvider
            .when("/", {
            templateUrl: "/ng-templates/topicsView.html",
            controller: "topicsController",
            controllerAs: "vm"
            })
            .otherwise({ redirectTo: "/" });
    };

    function topicsController($http) {
        var vm = this;
        vm.messages = [];
        vm.isBusy = true;

        $http.get("/api/v1/topics?includeReplies=true")
            .success(function(result) {
                vm.messages = result;
            })
            .error(function() {
                alert('error/failed');
            })
            .then(function() {
                vm.isBusy = false;
            });
    };

/Views/Shared/Layout.cshtml

<html lang="en" ng-app="@ViewBag.InitModule">

/Views/Home/Index.cshtml

@{
  ViewBag.Title = "Home Page";
  ViewBag.InitModule = "homeIndex";
}
<div data-ng-view=""></div>
@section Scripts {
  <script src="~/ng-modules/home-index.js"></script>
}

/ng-templates/topicsView.html

<html lang="en" ng-app="@ViewBag.InitModule">

/Views/Home/Index.cshtml

<h3>Message count: {{vm.messages.length}}</h3>
<div class="messages">
  <div class="message row" data-ng-repeat="i in vm.messages">
    <div class="title col-md-9">{{i.title}}</div>
    <div class="date col-md-3 text-right">{{i.created | date:"MMM d, y (h.m a)"}}</div>
    <div class="contents col-md-12">{{i.body}}</div>
    <div class="toolbar col-md-12"><button class="btn btn-primary reply-button">Reply</button></div>
    <div class="reply col-md-12" ng-repeat="r in i.messages">
      <div class="created pull-right">{{r.created | date: "medium"}}</div>
      <div class="content">{{r.body}}</div>
  </div>
  </div>
</div>

Now let’s move on to the next logical point in the course to update this code. In the Deeper into AngularJs module at the end of the video named “Angular JS Validation” The code should look something like this:

*Note that we are still using vm for (ViewModel) to replace the this keyword. This is fine because it is scoped to each function. Also I have only added the code here that has changed.


/ng-modules/home-index.js

angular
    .module("homeIndex", ["ngRoute"])
    .config(config)
    .controller("topicsController", topicsController)
    .controller("newTopicController", newTopicController);

    function config($routeProvider) {
        $routeProvider
            .when("/", {
                templateUrl: "/ng-templates/topicsView.html",
                controller: "topicsController",
                controllerAs: "vm"
            })
            .when("/newmessage", {
                templateUrl: "/ng-templates/newTopicView.html",
                controller: "newTopicController",
                controllerAs: "vm"
            })
            .otherwise({ redirectTo: "/" });
    };

    function topicsController($http) {
        var vm = this;
        vm.messages = [];
        vm.isBusy = true;

        $http.get("/api/v1/topics?includeReplies=true")
            .success(function(result) {
                vm.messages = result;
            })
            .error(function() {
                alert('error/failed');
            })
            .then(function() {
                vm.isBusy = false;
            });
    };

    function newTopicController($http, $window) {
        var vm = this;
        vm.newTopic = {};
        vm.save = function() {
            alert("title: " + vm.newTopic.title + " & body: " + vm.newTopic.body);
        };

    };

/ng-templates/newTopicView.html

<h3>New Topic</h3>
<form name="newTopicForm" novalidate ng-submit="vm.save()">
  <fieldset>
    <div class="row">
      <div class="col-md-12">
        <label for="title">Title</label><br />
        <input name="title" type="text" ng-model="vm.newTopic.title" required ng-minlength="5" />
        <span class="error" ng-show="newTopicForm.title.$error.required">*</span><br />
        <span class="error" ng-show="newTopicForm.title.$error.minlength">Must be 5 chars long</span><br />
        <label for="title">Body</label><br />
        <textarea name="body" rows="5" cols="30" ng-model="vm.newTopic.body" required ng-minlength="15"/>
        <span class="error" ng-show="newTopicForm.body.$error.required">*</span>
        <span class="error" ng-show="newTopicForm.body.$error.minlength">Must be 15 chars long</span><br />
      </div>
      <div class="col-md-12">
        <input type="submit" class="btn btn-primary" value="Save" ng-disabled="newTopicForm.$invalid" /> |
        <a href="/" class="btn btn-primary">Cancel</a>
      </div>
    </div>
  </fieldset>
</form>

At the end of “Saving Data to the API” our

newTopicController()

code should look like this:

//home-index.js

    function newTopicController($http, $window) {
        var vm = this;
        vm.newTopic = {};
        vm.save = function() {
            $http.post("/api/v1/topics", vm.newTopic)
                .success(function (result) {
                    var newTopic = result.data;
                    //TODO: merge with existing topics
                    alert("Thanks for your post");
                })
                .error(function() {
                    alert("Your broken, go fix yourself!");
                })
                .then(function() {
                    $window.location = "#/";
                });
        };

    };

Leave a Reply

You must be logged in to post a comment.