Exactly one month go I posted a little message stating that I’m going to venture into the world of angularJS. This blogpost is for myself as a post-it note to keep the most important parts easy to find:
- the framework is awsome
- the framework is awsome
- the framework is awsome
- the framework is awsome
$scope
keeping track of scope variables can be a pain in the ###. Use $scope.$watch(‘<variable name>) to get notified about changes. first call is always some sort of initialization call!
use inline scopes in directives, this way the directive can be mean and clean.
scope: { variable: "outervariable", variable: "@attribute", }
$http
use $http for low level ajax calls. $http uses promises. Promises are a observer/observable like tech to call funtions when a specified asynchronous task completes. When multiple ‘objects’ use the same service add a addListener method like so
var service = function($scope, $http) { var listeners = []; var self = this; this.addListeners = function(l) { this.listeners.push(l); } this.doGet = function() { $http.get('<someurldotstuff', self.onSuccess, self.onError); } this.onError = function(data) { for (var i = 0; i < listeners.length; i++) { listeners[i].onError(data); } } this.onSuccess = function(data) { for (var i = 0; i < listeners.length; i++) { listeners[i].onSuccess(data); } } }
This way you can have multiple ‘listeners’ and don’t worry in your service on what is happening and break things by changing parsing the result.
Controllers
Don’t use anonymous functions!! Use a function defined at /App/controllers.js It makes your life easier
When defining a controller be aware of the DI properties. Always check the order of things 😉
Divide and conquer
Use the following app structure*
– /App
/App/libs : Contains all the javascript libraries needed to get it working such as moment.js or something similar
/App/pojo: Contains your ‘classes’ that are to be used. For instance in my runkeeper project I have a pojo for a workout, for a list of workouts and for heartrate data.
/App/app.js: Main module for the project.
/App/controller.js: Controller javascript. Contains all the controllers used throughout the application. no mather where they are used, in directives or just as a basic view controller.
/App/services.js: service object definitions module
/App/directives.js: main service definition module. Uses controller.js and service.js to get the work done. *be aware of this in <html><header>
/Templates: contains the main view templates
/Templates/partials: contains sub templates such as used by directives.