Displaying a prepopulated database with AngularJS


I am trying out different ways to have a prepopulated database in an app. This time I’m experimenting with AngularJS. The following article show how to display an array of data AngularJS style, filtering the output with two buttons. (This article is not using “ng-cordova.”) If you follow the other articles on this site, you can compare the different approaches for a “simple,” in-app, prepopulated DB.

Resources:
https://angularjs.org/
https://docs.angularjs.org/api/ng/filter
http://www.w3schools.com/angular/default.asp

My development environment:

Mac OS X Yosemite 10.10.1 on latest Mac Mini
cordova -v 4.0.0
Testing in device: Android-19, Nexus 7 with 4.4.2
No Jquery or other JS or CSS packages or frameworks used

Create sample Cordova or PhoneGap project

1. I’m creating this app in the folder /PhoneGap_apps, so I open the Terminal app, type cd and a space (for the change directory command), and drag that folder to its window, click on the Terminal to select it, and hit Enter. Now the Terminal commands are oriented to that folder, and the project will be built in that folder.

2. Create the barebones files:

cordova create ngtest

3. When that’s over and Terminal returns to the prompt, change to the new folder:

cd ngtest

4. Add the platform files to set it up for your devices:

cordova platform add android

(Each platform has its own version number. This installed the Android platform version 3.6.4.)

cordova platform add ios

(This installed the iOS platform version 3.6.3.)

Since this is only a test, I’ll be leaving all the defaults as is, including icon files.

5. Open /ngtest/www and delete all the files there.

Set up the AngularJS and content files

This template project will require four pages to create: three .js and one .html. They can all be placed into your /ngtest/www folder, and the .html file needs to reference the .js files.

1. The first is angular.min.js, which you can download from https://angularjs.org/ and insert into your /ngtest//www folder. It is 108kb.

2. Next is your myApp.js file, which consists of just a single line of text and also goes into your /ngtest//www folder. Create this by hand.

var app = angular.module("myApp", []);

3. The final .js file is myCtrl.js, your Controller file. You also create this by hand. It will contain all your functions and data for the database (which is actually a JavaScript array object in my example. You can also format as a JSON array). My filtered output is activated by two buttons; in this case, to show buggies only, or trucks only.

app.controller("myCtrl", function($scope) {
/* Make following line $scope.show = 'Buggy '; to make Buggy the default display on page load. As is, it will display the whole DB on page load. */
$scope.show = '';
 $scope.base = function() {
 return $scope.show;
 };
 $scope.bodyType = function() {
 return {bodyType: $scope.base()};
 };
 $scope.names = [{bodyType: 'Buggy'}, {bodyType: 'Short Course'}];
$scope.names = [
 {
 id: 1,
 bodyType:'Short Course',
 category:"SC18",
 name2:"SC18 Ready-To-Run",
 photo:"http://www.teamassociated.com/pictures/cars_and_trucks/SC18/RTR/20120.ps_md.jpg",
 resource:"http://www.teamassociated.com/cars_and_trucks/SC18/RTR/",
 caption:"Now you can enjoy Team Associated’s world-class performance with true scale authenticity in a 1:18 scale electric truck! The SC18 features a newly designed chassis with a fully enclosed, 2-belt drive train system that is capable of handling the extreme amount of power that today’s brushless motors and LiPo batteries can dish out. Along with durability, the drive train is sealed to help keep rocks and dirt away from the gears and pulleys." // no comma after the last of the series
 },
 {
 id: 2,
 bodyType:"Short Course",
 category:"Qualifier Series",
 name2:"ProSC 4x4 Ready-To-Run",
 photo:"http://www.teamassociated.com/pictures/cars_and_trucks/ProSC_4x4/RTR/Pro-SC-4x4-3Q_R.500_md.jpg",
 resource:"http://www.teamassociated.com/cars_and_trucks/ProSC_4x4/RTR/",
 caption:"Team Associated is proud to announce the ProSC 4x4 Ready-To-Run — a brushless-powered 4WD off-road short-course truck in the Qualifier Series! The ProSC 4x4 comes ready to rock with many high performance features including the XP 2.4GHz radio system, a Reedy brushless power system and a 7-cell 8.4 volt Reedy WolfPack battery wired with a High Current T-Plug."
 },
 {
 id: 3,
 bodyType:"Short Course",
 category:"SC10 4x4",
 name2:"SC10 4x4 RTR Combo",
 photo:"http://www.teamassociated.com/pictures/cars_and_trucks/SC10_4x4/RTR_Combo/lucas-body-left-7_7661_md.jpg",
 resource:"http://www.teamassociated.com/cars_and_trucks/SC10_4x4/RTR_Combo/",
 caption:"The SC10 4x4 Ready-To-Runs are RC replicas of the 800+ horsepower short course trucks driven in the Lucas Oil Off Road Racing Series."
 },
 {
 id: 4,
 bodyType:"Buggy",
 category:"RC10B5M",
 name2:"RC10B5M Team Kit",
 photo:"http://www.teamassociated.com/pictures/cars_and_trucks/RC10B5M/Team/RC10B5M_TK_2560x2048_md.jpg",
 resource:"http://www.teamassociated.com/cars_and_trucks/RC10B5M/Team/",
 caption:"The engineers in Team Associated’s Area 51 designed the RC10B5M to specifically address the demands of racing on high-speed, high-grip tracks where the mid-motor chassis is at its best."
 },
 {
 id: 5,
 bodyType:"Buggy",
 category:"RC10B44",
 name2:"B44.3 Factory Team",
 photo:"http://www.teamassociated.com/pictures/cars_and_trucks/B44.3/Factory_Team/B44.3_3Q%20White_md.jpg",
 resource:"http://www.teamassociated.com/cars_and_trucks/B44.3/Factory_Team/",
 caption:"Enter the RC10B44.3 Factory Team Kit, the latest evolution of Team Associated’s 1:10 4WD electric off road competition buggy. The most significant changes are found on the new hard-anodized aluminum chassis, which helps lower the center of gravity to improve handling and durability."
 } // no comma here
 ];
});

4. The index.html file will hold the AngularJS code structure and style the output. I commented the lines throughout. Just make sure the field names match up perfectly with the field names in myCtrl.js.

<!-- ******************* BEGIN ******************* -->
<!DOCTYPE html>
 <html ng-app="myApp"><!-- The container of the app. See myApp.js. Automatically bootstraps the app when page is loaded. -->
 <head>
 <meta charset="utf-8" />
 <meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width, height=device-height, target-densitydpi=device-dpi" />
 <title>AngularJS DB Test</title>
<!-- cordova is not being used in this test
 <script src="javascripts/cordova.js"></script>
 <script type="text/javascript" charset="utf-8">
 // Wait for device API libraries to load
 //
 document.addEventListener("deviceready", onDeviceReady, false);
 // device APIs are available
 //
 function onDeviceReady() {
 }
 </script> -->
<!-- Reference the js file in the head -->
<script src= "angular.min.js"></script>
<!-- Stylize the HTML elements -->
 <style type="text/css">
 .buttonClass, h2, p {
 font-family: "Helvetica"; color: #000; font-size:1em;
 }
 .buttonClass {
 border-radius:8px; background-color:#fff;
 border:#878787 solid 1px; padding:0 1em;margin:.5em;
 height: 3em; width: 300px;
 text-align:center;
 -webkit-appearance:none;
 }
 .segment {
 display:block; border-radius:8px; background-color:#eee;
 border:#878787 solid 1px; padding:1em; margin:.5em;
 -webkit-appearance:none;
 }
 h2 {
 font-size:1.3em; font-weight: bold;
 }
p {
 text-align:left; margin-left: 170px;
 }
 p.title {
 font-weight:bold;font-size:1em;text-align:center; color:#000
 }
 p.more {
 font-size:.8em;text-align:center;font-style:italic;
 }
 a {
 color:#666
 }
 img.pic {
 width:150px;
 float: left;
 }
 </style>
</head>
<body>
<!-- The controller (in myCrtl.js) only works for elements within this div. -->
<div ng-controller="myCtrl">
<!-- These buttons integrate with the code in myCrtl.js -->
 <button class="buttonClass" ng-click="show='Buggy'">Buggy</button>
 <br><br>
 <button class="buttonClass" ng-click="show='Short Course'">Truck</button>
 <br><br>
<script> 
 
</script>
<!-- 
{{}} = binding expressions: data from controller goes in here. 
ng-repeat = directive used on an array of objects. 
orderBy = set it to the field by which you want to order the contents. 
More filtering options here: https://docs.angularjs.org/api/ng/filter
-->
<div class='segment' ng-repeat="x in names | filter: bodyType() | orderBy:'id'">
 <p class='title'>{{ x.id }} -- {{ x.bodyType }}: {{ x.name2 }}</p>
 <img class='pic' src='{{ x.photo }}' width='100px'> 
 <p class='caption'>{{ x.caption }}</p>
 <p class='more'><a href='{{ x.resource }}'>More</a></p>
 </div>
</div>
<!-- Module file -->
<script src="myApp.js"></script>
<!-- Controller file contains functions and the database array entries -->
<script src="myCtrl.js"></script>
</body>
</html>

<!-- ******************* END ******************* -->

Test the file

1. Double-click the index.html file in /www to test it in your browser. The buggies should list by default. Click on the Trucks then Buggies buttons to see the filtering in action.

2. Now test the app in your device. Output debug versions of the files. In Terminal:

cordova build

3. Add the /platforms/android/ant-build/CordovaApp-debug.apk file to your Android device (I used Dropbox to transfer the file), and test by tapping the Show All button at top.

Here is a screen shot of the screen when Buggy is pressed:

ngtest screenshot, AngularJS test

ngtest screenshot, AngularJS test

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.