Refactoring the js code structure PhoneGap and Angular (Part 4).

Published on May 06, 2014

Other articles in the Ionic series.

  1. Building an iOS app with PhoneGap, Angular.js and the ionic framework (Part 1).
  2. Building a basic iOS UI using Angular and Ionic (Part 2).
  3. Recording Geo location data with PhoneGap and Angular (Part 3).
  4. Uploading files with PhoneGap and Angular (Part 5).
  5. A few different ways to improve user feedback in our Ionic application (Part 6).
  6. Displaying current and max speed with PhoneGap and Ionic (Part 7).
  7. Deleting files with PhoneGap (Part 8).
  8. Calculating distance and speed with the GeoLocation API - PhoneGap (Part 9).

Code for this series is available on [Github](https://github.com/hgarcia/dynamic-sports)

The last time we created our first services, controllers and directives. We can see that if we keep adding controllers to the controller.js file things are going to get out of control soon.

What we want is to create each entity on it’s own file and concatenate all the js files together as part of the build process.
We are going to create a js folder under the root of the project and inside it three subfolders for each type of entity.



	js
	|-controllers
	|-directives
	|-services

We are going to move the files from www/js inside the new folders. The app.js file will be at the root of the new structure and the other files inside each folder.

We will create a new home_controller.js file and copy the code for the HomeController to it.

We will do the same for the service and diretcives.

Concatenation

We open the gulpfile.js file and we add a new task.



	gulp.task('scripts', function() {
	  gulp.src(['./js/*.js', './js/**/*.js'])
	    .pipe(concat('all.js'))
	    .pipe(gulp.dest('./www/js/'));
	});

We will need to modify the paths object as well since the sass property doesn’t make a lot of sense anymore.



	var paths = {
  		all: ['./scss/**/*.scss', './js/*.js', './js/**/*.js']
	};

And we will add the new scripts task to the watch and default tasks.



	gulp.task('watch', function() {
	  gulp.watch(paths.all, ['sass', 'scripts']);
	});

	gulp.task('default', ['sass', 'scripts']);

We will also need to modify the package.json file to call the default gulp task.



	"ios": "gulp && ionic emulate ios"

Modify our karma.config.js file for our test to load the new files.



	files: [
    	'lib/ionic/js/ionic.bundle.js',
      	'lib/ionic/js/angular/angular-mocks.js',
      	'../js/*.js',
      	'../js/**/*.js',
      	'../tests/**/*_spec.js'
    ],

Finally, we need to use the new concatenate file on our index.html and remove the script tags for the all files.



	<script src="js/all.js"></script>

Next steps.

We want to send the information we recorded to a server for saving and processing, but we can only do that while connected to a network. We will also want to give the user the option to only upload files when the device is using a Wi-Fi connection.