Elegant Scroll To In AngularJs

Scrolling to a certain section of the view is incredibly easy with AngularJs.

Understanding The Problem

You may have noticed that the classic scrolling to an anchor id no longer works when you start building in Angular. This is because the traditional method involves clicking a link, modifying the fragment and sending the user to the specified anchor id as specified by the fragment. Since the fragment is used by Angular to handle the view states we are unable to use this method of page navigation.

The solution to the problem is fortunately very simple and friendly although I should mention. It is possible to still use traditional javascript scrolling methods which, in some cases, perform better.

The Angular Solution

The solution via angular is to simply use the following lines of code.

1
2
3
4
// Location of the hash we will scroll to.
$location.hash('id-string-representation');
// Actually performing the scroll.
$anchorScroll();

Note: you will need to inject $location and $anchorScroll into the controller that you are calling these functions from.

Real World Use

In reality it is likely that the web application will contain various links. It is also likely that these links will be generated using the controller. We will be creating an example of how to use the scrolling functionality that angular has.

1
2
3
4
5
6
7
8
9
10
11
12
<!-- Links to scroll to various sections -->
<a ng-click="scrollTo(1)">1</a>
<a ng-click="scrollTo(2)">2</a>
<a ng-click="scrollTo(3)">3</a>
<a ng-click="scrollTo(4)">4</a>
 
<!-- various sections we will scroll to. Please excuse the inline styles -->
<div id="test-1" style="height: 400px;">1</div>
<div id="test-2" style="height: 400px;">2</div>
<div id="test-3" style="height: 400px;">3</div>
<div id="test-4" style="height: 400px;">4</div>
<div id="test-5" style="height: 400px;">5</div>

The controller will contain a function called ‘scrollTo’ that will take an integer which is the div we will attempt to scroll to.

1
2
3
4
$scope.scrollTo = function(div) {
    $location.hash('test-'+div);
    $anchorScroll();
}

In Summary

You should be able to scroll to various divs now. Modification of the scrollTo function is also advised as it should simply consume the entire id rather than an integer which will make the use much more practical.

1
<a ng-click="scrollTo('container')">top</a>
1
2
3
4
$scope.scrollTo = function(div) {
    $location.hash(div);
    $anchorScroll();
}

Two way data binding from service to controller in angularjs

Here is a quick and simple post on how to get two way data binding to work in angularjs between a service and a controller.

First an outline of what we are trying to achieve. We want variables within our service to automatically bind with the view values. We also want these values to go through the controller, allowing us to manipulate information where and when we desire it.

View -> Controller -> Service -> Controller -> View

This will come in useful if you need global application values stored in a service that will be used across different controllers and views. Ie: an AuthenticationService or a ApplicationService that will contain page title, and meta information.

The view

The view is going to be simple. It doesn’t really matter what is displayed so long as it will bind to the variable. In this case we will be displaying a movie title from the service.

1
2
3
4
<div ng-controller="MovieController">
    <h1>{{movie.title}}</h1>
    <p>{{movie.description}}</p>
</div>

Note that we are going to be using the object ‘movie’. This will be the object that we are using in the controller and the service.

The Movie Service

This little section of code will be used load the movie information from the server or something. It isn’t actually important at all and using movies as an example in this article probably isn’t the most realistic use of the service binding.

app.factory('MovieService', function() {
    var movie = {
        title: "",
        description: "",
    };
 
    return {
        setMovie: function(name, description) {
            movie.title       = name;
            movie.description = description;
        },
        // We return the object in the service to the controller. This will allow
        // us to bind values to and from the service.
        movie: movies
    }
});

This service, if you are unfamiliar with them, will keep the object movie for the life time of the application. This way many controllers can set and get one static value across the entire application.

These values will be able to be accessed via watch() and MovieService.setMovie(“Pulp Fiction”,”A lot of Sam Jackson quotes.”);

The Controller

The controller will tie everything together. You may have noticed that the view is already referencing a controller with the first attribute in the first tag ng-controller=”MovieController”.

app.controller('MovieController', function($scope, MovieService) {
    $scope.$watch(
        function () { return MovieService.movie; },
        function (data) {$scope.movie = movie;},
        true
    );
});

$watch will allow us to monitor changes in the service and update the controller with said changes. There is a simple get and set on the values as well as a boolean for arguments. With the blunt return of an object this boolean is very important. Without it there will be no checks deep into the object.
This also means that there will be a performance drop when binding very complicated objects in this manor. (That will be tough to deal with anyway though)

In Summary

By going through this article you should have a basic understanding of how to bind a variable to a service through a controller in angularjs.
Some of the issues you may encounter are injector issues which comes when there is a problem finding the service you are attempting to inject into the controller. You may also run into digest cycle issues which will come into play when the view is already attempting to update.

Javascript Arrays

Introductions

An array is simply a list of data contained in one variable and accessed by indices. An example of an array would be an array of ages containing 0, 1, 2, 3 etc. The array doesn’t have to be integers, it can be an array of strings, objects or even arrays.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
// Create an array
var ages = new Array(1,2,4,99,54,23);
 
// Create another array
var names = new Array(“bill”, “bob”);
 
// Create a literal array
var games = [“minecraft”,”half life”,”freecell”];
 
// Add values to an empty array
var ages = new Array();
ages[0] = 1;
ages[1] = 2;
ages[2] = 9;

It is important to know that the array is actually an object that contains values. Because this type is actually an object there are properties that can be called to help handle the information inside of the array.

Helper Functions And Properties

In javascript, along with many other languages, there are functions built around arrays that will allow you, the developer, to better use them and be more efficient in your coding. The length property is one of the most commonly used properties when going through an array.

1
2
3
4
5
6
7
8
9
// Going through the items in an array.
// Create the array
var ages = new Array(1,2,3,5,7);
 
// Loop through using the length property
for(var x = 0; x &lt; ages.length; x++) {
// Print out the items one by one with an alert.
<p dir="ltr">alert(ages[x]);</p>
}

Array push and pop are commonly used to add items to the array without having to get the position of where the item will be added yourself.

1
2
3
4
5
6
7
8
// Create an array with one item
var names = [“bob”];
 
// push an item onto the array.
names.push(“caleb”);
 
// the resulting array will now be the same as it would be if you created it like this.
var names = [“bob”,”caleb”];

Now we are going to pop an element off of the end of the array and return the item. This call not only returns the value but it will alter the array in memory changing the values within it.

1
2
3
4
5
// create a new array of names that we will play with
var names = [“chewbacca”,”yoda”,”skywalker”,”ben”];
var poppedValue = names.pop();
 
// As a result the names array will no longer have “ben” in it and the poppedValue will contain the string “ben”;

Two Dimensional Array

The concept of a 2D array can seem a little intimidating at first until you realize that you need to look at the data as columns and rows. Here is an example of what a 2D array would look like.

1
2
3
4
// Creating a 2D array
var x = new Array(0,1);
x[0] = new Array(0,0);
x[1] = new Array(0,0);

In order to access a property within the second array you will just need to fetch the value using the key.

1
2
// Display the item that is in the first column of the first row.
alert(x[0][0]);

Another way to create an array like this is to loop through the items upon creation.

1
2
3
4
5
6
7
8
9
10
11
//Create the array container
var names = new Array();
 
for(var x = 0; x &lt; 10; x++) {
names[x] = new Array();
// Go through the second dimension and set the values.
for(var y = 0; y &lt; 10; y++) {
// Assign the value of the item to bob.
names[x][y] = “bob”;
}
}

Note: in strongly typed languages an array must consist of the same data types. Since javascript is not a strongly typed language; the information stored can consist of mixed data types.

Google Drive API

Introduction

Google Drive is out! Yes that’s right, Google’s Drive project which allows users to store content onto a Google server and pull it from any device is now available. This product offers 5GB free to google users with additional packages for extra money.

This is a pretty cool thing and not just because Google is doing drop box properly but more so because they are doing drop box across the Google platforms and offering an API to those of us that are interested in developing for it.

My plans

My plan over the next couple of days is to create a way to store server logs and general statistics for my server to the Google Drive. This will allow me to easily check on how things are going from my mobile device.

Google Drive API

If you are interested in working with Google Drive than I suggest that you take a look at the API that Google has provided us. https://developers.google.com/drive/v1/reference/

If you are going to work with the API that is available you will have to register your own app. https://developers.google.com/drive/register

Performance

The API has some interesting features for performance. When performing an update you can receive a partial response. This response type will only return the specific fields that you ask for rather than the entire object. The API also supports a header type of gzip to allow for speedier and smaller sent and received packets of information.

For more information on Google Drive API performance: https://developers.google.com/drive/performance

Javascript Canvas: Basic Game Logic and Movement

Introduction

If you are interested in writing a game in javascript using the new canvas tag than look no further. In this lesson I will be going over the game loop and what is required to get started with your own. If you have not yet gone through the introduction to the canvas you should click here. It only takes a couple minutes to go through and it will have the required code for this lesson.

The Basic Loop

In order to create a loop we are going to base it off of seconds using the set_interval() function. This function will allow us to call on a function x times per second. This is a good function to use when making a loop based game because it will wait for the function to finish before calling on it again even if the time is exceeded.

1
2
// call on a function every 100 milliseconds.
setInterval(“methodName(), 100);

Drawing to the canvas

For now we are going to simply draw to the canvas using a draw function. You can call on a class.method in the set interval function. In the draw function that we are creating, we are going to have to draw something to the canvas. In the following code we will draw a line from point a to point b.

1
2
3
4
5
6
7
function draw() {
ctx.strokeStyle = “#333333;
ctx.beginPath();
ctx.moveTo(50,50);
ctx.lineTo(60, 50);
ctx.stroke();
}

If the setInterval function has been properly setup, to take the draw function, than you should see a line appear on the canvas. Now lets get a little wild and crazy and give that line some movement.

Layers

The canvas works in layers. If you draw something to it, the item will stay until something has been drawn over it. Because of this the canvas needs to be reset and will need to be reset and have everything drawn back on to it in layers from the background to the foreground.

In a two dimensional game you are going to want to draw the items from the bottom up. The items should be drawn in the following order if you are looking at the ground from a birds eye view.

Draw the dirt
Draw the grass
Draw the trees
Draw the birds

Movement

Create public variables for x position, y position and counter.

1
2
3
var posX = 50;
var posY = 50;
var counter = 0;

Within the draw function we are going to add the following code which will increase the counter and set the position of the line. In the draw method we will need to redraw the background to clear the canvas. Add the following code to the function and place it above everything else within the code block.

1
2
ctx.fillStlye = “#ffffff”;
ctx.fillRect(0,0,800,400);

This will clear the previous items on every draw event. Now we can draw the items onto this layer by adding some logic to the draw function and changing the lineTo using the x and y positions.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
function draw() {
 
// redraw the background.
ctx.fillStyle = “#ffffff”;
ctx.fillRect(0,0,800,400);
 
// increase the counter
counter++;
 
// reset the counter so the line doesn’t get out of hand.
if(counter == 100) {
counter = 0;
}
 
// Stroke the line.
ctx.strokeStyle = “#333333;
ctx.beginPath();
ctx.moveTo(posX,posY);
ctx.lineTo(posX + counter, posY + counter);
ctx.stroke();
}

You will now have a moving line on the canvas that will reset every 100 updates.

An Introduction to the Canvas

Before we get started we are going to need to setup our coding environment. This will be a quick and dirty copy paste solution for you.

We need two files. The first will be index.html and the second file will be: main.js Fill the index.html file with the following code…

1
2
3
4
5
6
7
8
9
10
<!DOCTYPE HTML5>
<html>
<head>
<script src="main.js"></script>
<title>Caleb Jonasson Canvas Demo</title>
</head>
<body onload="onLoad()" style="margin:0px; padding:0px;">
<canvas id="canvas" width="800" height="400"></canvas>
</body>
</html>

Now paste this code into the main.js file. The two files should be placed in the same directory.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
var ctx = null;
 
function onLoad() {
// Get the context from the canvas
ctx = document.getElementById("canvas").getContext("2d");
 
// Add an event listener
document.addEventListener("click", registerInteraction, true);
 
}
var registerInteraction = function()
{
var x = window.event.pageX;
var y = window.event.pageY;
log("clicked: x"+x+", y"+y);
}
function log(content) {
console.log(content);
}

Using the Context

You will notice that in the onLoad function we are getting the context of the canvas from the page. This ctx value will allow us to draw on the canvas. The common variable for the context is either “ctx” or “context”. This value is declared at the top of the document and will be public for everything to use.

We are going to start this lesson by drawing a background onto the canvas so we know where it starts and ends. Add the following code to the onLoad function.

1
2
ctx.fillStyle = "#94B73E";
ctx.fillRect(0,0, 800, 400);

The fill style is a variable sets the fill color of the item. The fillRect function simply fill a rectangle. The first two parameters are the x and y coordinates of where you would like to start drawing the rectangle. The second parameters are the ending coordinates of the rectangle. Upon running the script you will notice that we now have a solid background.