Wednesday, June 5, 2013

App Context for Angular.JS

I'm now deep into converting the Wikibrains client application to the Angular.js Javascript infrastructure.
One of the most basic tools I needed was an application wide context to shift around data and events between controllers.

This is what I came up with:

angular.module('myApp.context', []).factory('Context', function($rootScope, $location) {
return {
'contentTypeFilter': "All",
'contentScopeFilter': "pub",
'focusedItemId': -1,
'profileData':{},
'broadcast': function(eventName){
console.log("! Broadcasting: "+ eventName);
$rootScope.$broadcast( eventName );
},
'wrapUp': function(){
return {id:this.focusedItemId, scope:this.contentScopeFilter, content:this.contentTypeFilter};
},
'feed': function(scope){
scope.contentTypeFilter = this.contentTypeFilter;
scope.contentScopeFilter = this.contentScopeFilter;
scope.focusedItemId = this.focusedItemId;
scope.profileData = this.profileData;
}
};
});
view raw Context.js hosted with ❤ by GitHub
function MyCtrl($scope,Context) {
//dump Context onto local $scope:
Context.feed($scope);
//Shake the tree when the context is changed
$scope.userChangedFocusItem = function(selectedItem){
Context.focusedItemId = selectedItem.id;
Context.broadcast("UserChangeFocusItem");
}
// Catch a change in the context and do something in consequence
$scope.$on('ChangeContext',function(){
Context.feed($scope);
});
}
view raw myController.js hosted with ❤ by GitHub

No comments:

Post a Comment

Please do not post spam on this blog, Spam sites will be reported to google.
thank you kindly.