Professional Documents
Culture Documents
AngularJS
design patterns for dealing with UI
complexity.
// in controller // in service
$http('api').success (data) => var data = []
$scope.data = data changeData = =>
$http('api').success (data) =>
data = []
// in first controller
$scope.data = service.data
// in second controller
service.changeData()
Complexity Fail: the controller is referencing the
original data, doesn't know about new value
(Overly) simple approach: placing data on the $rootScope and watching it on
different controllers.
Problems: This could lead to a collision, and also in the case of an isolated
scope will not be propagated.
http://jsfiddle.net/VxafF/
Using events
Using events we can clearly communicate between controllers. And when we are
communicating with code not integrated with angular, this is often the best approach
Problem:
using fragile strings. Potential (unexplored) solution: use signals.js or use variables
that contain the string names
Usage is a bit more obscure: we will likely end up broadcasting events to every
controller whether they care about them or not. We will search for a string to find the
event source rather than looking for a service
Some boilerplate in the controller
myModule.run(function($rootScope) { http://jsfiddle.net/VxafF/
$rootScope.$on('handleEmit', function(event, args) {
$rootScope.$broadcast('handleBroadcast', args);
});
});
function ControllerZero($scope) {
$scope.handleClick = function(msg) {
$scope.$emit('handleEmit', {message: msg});
};
}
function ControllerOne($scope) {
$scope.$on('handleBroadcast', function(event, args) {
$scope.message = 'ONE: ' + args.message;
});
}
Communication via services: getters
In AngularJS this can be
Events
changed to a function call
// in service
// in service
$rootScope.on 'change', changeData var data = []
$rootScope.broadcast('event', data) return {
changeData: => ...
// in controller
getData: => return data
$scope.on('event', ...)
}
// another controller
$rootScope.broadcast('change', []) // in controller, assign a function
$scope.data = service.getData
// in view: ng-bind="data()"
// could instead $watch the getter
// another controller
Communication via services: mutation
// in service // in controller
var data = []
var changeData = => $scope.data = service.data
$http(...).success (data) =>
data.length = 0
data.push(d) for d in data
return {
data: data
changeData: changeData
}
Dealing with complexity: not
AngularJS specific
* complex data modeling with adt.js
* managing complex UI State with statecharts
Data modeling with adt.js
https://github.com/natefaubion/adt.js