Skip to content

Instantly share code, notes, and snippets.

@rfong
Last active December 3, 2019 23:44
Show Gist options
  • Save rfong/7eda2d4857dd2e96e5ee to your computer and use it in GitHub Desktop.
Save rfong/7eda2d4857dd2e96e5ee to your computer and use it in GitHub Desktop.
miscellaneous useful angular stuff that was mildly annoying to figure out
// Change angular templating for var interpolation
app.config(['$interpolateProvider', function($interpolateProvider) {
$interpolateProvider.startSymbol('{[');
$interpolateProvider.endSymbol(']}');
}]);
app.run(function($rootScope, $http, $cookies) {
$http.defaults.headers.post['X-CSRFToken'] = $cookies.csrftoken;
});
app.factory('asyncService', ['$http', function($http) {
var service = {};
service.asyncData = null;
service.observerCallbacks = [];
// To guarantee that data is loaded, register your callback here
// instead of directly accessing data
service.registerObserverCallback = function(callback) {
// If data loaded, call callback
if (service.asyncData) {
callback();
} else {
service.observerCallbacks.push(callback);
}
};
$http.get('/some_endpoint')
.success(function(data) {
service.asyncData = angular.fromJson(data);
// Now that it's loaded, execute all registered observer callbacks.
angular.forEach(service.observerCallbacks, function(callback) {
callback();
});
}).error(function() {
alert("Some information failed to load. Please refresh.");
});
return service;
}]);
// Globally available utility library.
(function (window, document) {
'use strict';
// attach as a property of window
var util = window.util || (window.util = {});
function doSomething() {};
// publish library
angular.extend(util, {
doSomething: doSomething,
});
})
app.filter('capitalize', function() {
return function(input, scope) {
return input.substring(0, 1).toUpperCase() + input.substring(1);
};
});
// help-tooltip
app.directive('helpTooltip', function() {
return {
restrict: 'A',
template: function(element, attributes) {
return '' +
'<a class="help-tooltip" ' +
' tooltip-placement="{[ tooltipPlacement ]}" ' +
' tooltip="{[ text ]}">' +
' <i class="fa fa-question-circle fa-lg"></i>' +
'</a>';
},
link: function($scope, element, attributes) {
$scope.text = attributes.text;
$scope.tooltipPlacement = attributes.tooltipPlacement || 'right';
},
};
});
// Includable factory containing config vars
app.factory('config', function() {
return {
foo: 'bar',
};
});
// Angular object
app.factory("MyObject", function($http) {
var MyObject = function(myobject) {
angular.extend(this, myobject);
var self = this;
this.initialize = function() {};
// call init for every new instance
this.initialize();
};
return (MyObject);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment