Skip to content

Instantly share code, notes, and snippets.

@ecowden
Created February 13, 2013 15:18
Show Gist options
  • Save ecowden/4945306 to your computer and use it in GitHub Desktop.
Save ecowden/4945306 to your computer and use it in GitHub Desktop.
How can we have several views show the same data without hitting the server each time? This is a simple idea, along with copious notes on my personal style. Fair warning: this is just a sketch and has never been executed.
ngModule.factory('contactSearchService', [
'ContactResource',
function (ContactResource) {
// This is pretty much the most naive cache possible; do whatever makes sense for your use case.
var lastQuery,
lastResults;
function invalidateCache() {
// Or similar mechanism...again, whatever makes sense for you.
lastQuery = null;
lastResults = null;
}
function searchContacts(query) {
if (query === lastQuery) {
return lastResults;
}
// You may or may not need a callback. The $resource service will return an empty object immediately
// and then update that object when the XHR returns. Since you're usually putting the result on
// $scope and reading it from the view or a $scope.$watch, you never need to worry about the update.
// Observable magic FTW.
lastResults = ContactResource.get({q: query});
return lastResults;
}
// I like separating the implementation, above, and the API defined here.
return {
invalidateCache: invalidateCache,
searchContacts: searchContacts
}
}
]);
ngModule.controller('CrmSearchCtrl', [
'$scope', 'contactSearchService',
function ($scope, contactSearchService) {
// *** Function Definition ***
// Try to pass arguments directly into functions instead of passing them the long way around through the scope.
// The latter becomes a big pain in tests. In the view, you can do something like:
// <input ng-model='query'>
// <button ng-click='doSearch(query)'>
function doSearch(query) {
$scope.contactResult = contactSearchService.searchContacts(query);
}
function openRecord(entityType, recordId) {
// AHH GLOBAL! ;-)
// just kidding...no worries for a POC, but in the long run, we've had success
// wrapping these into proxies that we can inject. Makes testing happy.
// See Angular's $document and $window, etc.
Xrm.Utility.openEntityForm(entityType, recordId, null);
}
// *** Scope Assignment ***
// ^ I like breaking these two sections up. Avoids trying to figure out where the hell some magic bit on the
// scope came from.
$scope.doSearch = doSearch;
$scope.openRecord = openRecord;
$scope.doSearch('sample');
}
]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment