Talking to the backend

So now we need to connect our frontend to our backend. Instead of rendering data in our page on load, we want to use AJAX to connect and do all of our CRUD. Fortunately for us, Angular has a pretty elegant way of handling this.

Creating an AngularJS factory

Let's say that different parts of our application may need access to some of the same data endpoints, or some other functionality. A great way to handle this is with an AngularJS provider. A provider is essentially an injectable singleton, and there are a number of options available - see https://docs.angularjs.org/guide/providers.

The provider type we are going to use is a factory. Let's start by creating a services directory inside our public/javascripts directory. Create a new file called giftlistFactory.js inside that directory:

angular.module('giftlistServices', []) 
    .factory('List', function(){ 
        return {} 
    }); 

We've created another module for services, and then created a factory called List on that module. That factory doesn't do much yet, but we'll get to that.

Next, we'll load this file using a script tag in our dashboard.ejs template:

<!DOCTYPE html> 
<html ng-app="giftapp"> 
<head > 
    <title>Dashboard for <%= user.firstName %> <%= user.lastName %> </title> 
 
    <meta name="viewport" content="width=device-width, initial-scale=1"> 
 
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css"> 
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap-theme.min.css"> 
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script> 
    <script src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-router/0.2.15/angular-ui-router.min.js"></script> 
 
 
</head> 
<body> 
<nav class="nav navbar-default"> 
    <div class="container-fluid"> 
        <div class="navbar-header"> 
            <a class="navbar-brand" href="#"><%= user.firstName %> <%= user.lastName %> Dashboard</a> 
        </div> 
    </div> 
</nav> 
 
 
<div class="container"> 
 
    <div ui-view></div> 
 
     
 
</div> 
 
 
<script src="/javascripts/giftapp.js"></script> 
<script src="/javascripts/controllers/dashMainController.js"></script> 
<script src="/javascripts/services/giftlistFactory.js"></script> 
</body> 
</html> 

Now that we're loading this module, we can inject it into our controller. Open up dashMainController.js and edit the following:

angular.module('giftappControllers',['giftlistServices'])
    .controller('DashMainController', ['$scope','List', function($scope,List) { 
        $scope.lists = [{'name':'Christmas List'}, {'name':'Birthday List'}]; 
    }]); 

We inject the giftlistServices module into our giftappControllers module. In our DashMainController, we inject the List factory. Currently, List only returns an empty object, but anything we place in there going forward becomes available to our controller.

Using AngularJS $resource

The smart people who develop AngularJS figured out that a lot of what people want to do in an SPA is to talk to RESTful services. They had the idea to build a factory on top of their $http service (which provides AJAX functionality), which would provide an easy way to interact with a RESTful interface. That's precisely what $resource does.

We will begin by loading the ngResource module, which exposes $resource. In our dashboard.ejs template, add a script tag to load the module from CDN:

<!DOCTYPE html> 
<html ng-app="giftapp"> 
<head > 
    <title>Dashboard for <%= user.firstName %> <%= user.lastName %> </title> 
 
    <meta name="viewport" content="width=device-width, initial-scale=1"> 
 
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css"> 
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap-theme.min.css"> 
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script> 
    <script src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-router/0.2.15/angular-ui-router.min.js"></script> 
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-resource.js"></script> 
 
 
</head> 
<body> 
<nav class="nav navbar-default"> 
    <div class="container-fluid"> 
        <div class="navbar-header"> 
            <a class="navbar-brand" href="#"><%= user.firstName %> <%= user.lastName %> Dashboard</a> 
        </div> 
    </div> 
</nav> 
 
 
<div class="container"> 
 
    <div ui-view></div> 
 
 
</div> 
 
 
<script src="/javascripts/giftapp.js"></script> 
<script src="/javascripts/controllers/dashMainController.js"></script> 
<script src="/javascripts/services/giftlistFactory.js"></script> 
</body> 
</html> 

Now we have the module loaded, let's edit our factory to utilize $resource. Open giftlistFactory and make the following edits:

angular.module('giftlistServices', ['ngResource']) 
    .factory('List', function($resource){ 
        return $resource('/giftlist/:id',{id: '@_id'}) 
    }); 

You can see that we inject the ngResource module in our module. This allows us to inject $resource into our List factory. Lastly, we return the result of invoking $resouce with the path /giftlist/:id. This, combined with the second argument, sets up a number of functions that optionally include an id.

Remember the resourceful controller we built earlier? We're going to make an edit with some hardcoded data, for now. Opencontrollers/giftlist_controller.js:

exports.index = function(req, res){ 
 
        var db = req.db; 
        var collection = db.get('giftlist'); 
 
        collection.find({'owner_id':'566dd0cb1c09d090fd36ba83'}, {}, function(err,giftlists){ 
            if(err){ 
                res.send(err); 
            }else if(giftlists){ 
                res.json(giftlists); 
 
            }; 
        }); 
 
 
}; 

For now, only edit the index. You can see that I've hardcoded the owner_id for the query to match the user in the database I've been working with. You should match your user id accordingly as it will differ from mine.

Now, edit your dashMainController.js file:

angular.module('giftappControllers',['giftlistServices']) 
    .controller('DashMainController', ['$scope','List', function($scope,List) { 
        $scope.lists = List.query(); 
         
    }]); 

We set the value of $scope.lists to the result of running a query on our List resource. In this case, the result is an array of objects. If you restart your server and then reload the page, you'll see this:

Using AngularJS $resource

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.147.71.94