Skip to main content

Setting Up Our Angular Application

Setting Up Our Angular Application
For our Angular application, we will want:
  • 2 different pages (Home, Nerds)
  • A different Angular controller for each
  • An Angular service for Nerds
  • No page refresh when switching pages
Let’s create the files needed for our Angular application. This will be done in public/js. Here is the application structure for our frontend:


    - public 
    ----- js
    ---------- controllers 
    -------------------- MainCtrl.js
    -------------------- NerdCtrl.js
    ---------- services
    -------------------- NerdService.js
    ---------- app.js 
    ---------- appRoutes.js


Once we have created our controllersservices, and routes, we will combine them all and inject these modules into our main app.js file to get everything working together.


Angular Controllers

We won’t go too far in depth here so let’s just show off all three of our controllers and their code.
// public/js/controllers/MainCtrl.js
angular.module('MainCtrl', []).controller('MainController', function($scope) {

    $scope.tagline = 'To the moon and back!';   

});

// public/js/controllers/NerdCtrl.js
angular.module('NerdCtrl', []).controller('NerdController', function($scope) {

    $scope.tagline = 'Nothing beats a pocket protector!';

});

Of course in the future you will be doing a lot more with your controllers, but since this is more about application setup, we’ll move onto the services.

#Angular Services

This is where you would use $http or $resource to do your API calls to the Node backend from your Angular frontend.
// public/js/services/NerdService.js
angular.module('NerdService', []).factory('Nerd', ['$http', function($http) {

    return {
        // call to get all nerds
        get : function() {
            return $http.get('/api/nerds');
        },


                // these will work when more API routes are defined on the Node side of things
        // call to POST and create a new nerd
        create : function(nerdData) {
            return $http.post('/api/nerds', nerdData);
        },

        // call to DELETE a nerd
        delete : function(id) {
            return $http.delete('/api/nerds/' + id);
        }
    }       

}]);

That’s it for our services. The only function that will work in that NerdService is the get function. The other two are just placeholders and they won’t work unless you define those specific routes in your app/routes.js file. For more on building APIs, here’s a tutorial for Building a RESTful Node API.
These services will call our Node backend, retrieve data in JSON format, and then we can use it in our Angular controllers.


Angular Routes

Now we will define our Angular routes inside of our public/js/appRoutes.jsfile.
// public/js/appRoutes.js
    angular.module('appRoutes', []).config(['$routeProvider', '$locationProvider', function($routeProvider, $locationProvider) {

    $routeProvider

        // home page
        .when('/', {
            templateUrl: 'views/home.html',
            controller: 'MainController'
        })

        // nerds page that will use the NerdController
        .when('/nerds', {
            templateUrl: 'views/nerd.html',
            controller: 'NerdController'
        });

    $locationProvider.html5Mode(true);

}]);

Our Angular frontend will use the template file and inject it into the <div ng-view></div> in our index.html file. It will do this without a page refresh which is exactly what we want for a single page application.
For more information on Angular routing and templating, check out our other tutorial: Single Page Apps with AngularJS.


Updated View Files

With all of the Angular routing ready to go, we just need to create the view files and then the smaller template files (home.htmlnerd.html, and geek.html) will be injected into our index.html file inside of the <div ng-view></div>.
Notice in our index.html file we are calling the resources we pulled in using bower.
<!-- public/index.html -->
<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <base href="/">

    <title>Starter Node and Angular</title>

    <!-- CSS -->
    <link rel="stylesheet" href="libs/bootstrap/dist/css/bootstrap.min.css">
    <link rel="stylesheet" href="css/style.css"> <!-- custom styles -->

    <!-- JS -->
    <script src="libs/angular/angular.min.js"></script>
    <script src="libs/angular-route/angular-route.min.js"></script>

    <!-- ANGULAR CUSTOM -->
    <script src="js/controllers/MainCtrl.js"></script>
    <script src="js/controllers/NerdCtrl.js"></script>
    <script src="js/services/NerdService.js"></script>
    <script src="js/appRoutes.js"></script>
    <script src="js/app.js"></script>
</head>
<body ng-app="sampleApp" ng-controller="NerdController">
<div class="container">

    <!-- HEADER -->
    <nav class="navbar navbar-inverse">
        <div class="navbar-header">
            <a class="navbar-brand" href="/">Stencil: Node and Angular</a>
        </div>

        <!-- LINK TO OUR PAGES. ANGULAR HANDLES THE ROUTING HERE -->
        <ul class="nav navbar-nav">
            <li><a href="/nerds">Nerds</a></li>
        </ul>
    </nav>

    <!-- ANGULAR DYNAMIC CONTENT -->
    <div ng-view></div>

</div>
</body>
</html>

<!-- public/views/home.html -->

<div class="jumbotron text-center">
    <h1>Home Page 4 Life</h1>

    <p>{{ tagline }}</p>
</div>



<!-- public/views/nerd.html -->

<div class="jumbotron text-center">
    <h1>Nerds and Proud</h1>

    <p>{{ tagline }}</p>
</div>

Comments

Popular posts from this blog

ASP.NET Core - Create New Project

You can start building a new ASP.NET Core Application from the  File → New Project  menu option. On the New Project dialog box, you will see the following three different templates for Web projects − ASP.NET Web Application  − The simple ASP.NET application templates . ASP.NET Core Web Application (.NET Core)  − This will start you with a crossplatform compatible project that runs on the .NET Core framework. ASP.NET Core Web Application (.NET Framework)  − This starts a new project that runs on the standard .NET Framework on Windows. In the left pane, select  Templates → Visual C# → Web  and in the middle pane select the ASP.NET Core Web Application (.NET Core) template. Let us call this application  FirstAppDemo  and also specify the Location for your ASP.NET Core project and then Click OK. In the above dialog box, you can select a specific template for the ASP.NET application from the available ASP.NET Core Templates. ...

Setting Up Our Node Application server.js

Since this is our starter kit for a single page MEAN application, we are going to keep this simple. The entire code for the file is here and it is commented for help understanding. // server.js // modules ================================================= var express = require ( 'express' ) ; var app = express ( ) ; var bodyParser = require ( 'body-parser' ) ; var methodOverride = require ( 'method-override' ) ; // configuration =========================================== // config files var db = require ( './config/db' ) ; // set our port var port = process . env . PORT || 8080 ; // connect to our mongoDB database // (uncomment after you enter in your own credentials in config/db.js) // mongoose.connect(db.url); // get all data/stuff of the body (POST) parameters // parse application/json app . use ( bodyParser . json ( ) ) ; // parse application/vnd.api+json as json app . use ( bodyPar...

Become a MEAN Stack Developer

The MEAN stack is  MongoDB ,  Express.js ,  AngularJS  (or  Angular ), and  Node.js . Because all components of the MEAN stack support programs written in JavaScript, MEAN applications can be written in one language for both  server-side  and  client-side  execution environments. MEAN  was coined by Valeri Karpov, a MongoDB developer. He introduced the term in a blog post. The logo concept, initially created by Austin Anderson for the original MEAN stack  LinkedIn  group, is an assembly of the first letter of each component of the MEAN acronym. The components of the MEAN stack are as follows: M ongoDB, a NoSQL database E xpress.js, a web application framework that runs on Node.js A ngular.js or  A ngular, JavaScript MVC frameworks that run in browser JavaScript engines N ode.js, an execution environment for event-driven server-side and networking appl...