Skip to content

Instantly share code, notes, and snippets.

@martinsik
Last active August 29, 2015 14:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save martinsik/d1d7664d7128626c8580 to your computer and use it in GitHub Desktop.
Save martinsik/d1d7664d7128626c8580 to your computer and use it in GitHub Desktop.
// Alternative to Angular's ng-include that doesn't create new scopes.
module.directive('includeNoScope', function($http, $templateCache, $compile, $cacheFactory) {
return function(scope, element, attrs) {
var templatePath = attrs.staticInclude;
$http.get(templatePath, { cache: $templateCache }).success(function(response) {
var contents = element.html(response).contents();
$compile(contents)(scope);
});
};
});
// Refresh HTML with one time bindings by interpolating the HTML template and binding new watchers.
module.directive('OneTimeRefresh', function($compile, $interpolate) {
function copyLocalVariables(oldScope, newScope) {
angular.forEach(oldScope, function(val, key) {
if (key[0] !== '$') {
newScope[key] = val;
}
});
}
function removeChildrenWatchers(element) {
angular.forEach(element.children(), function(childElement) {
removeAllWatchers(angular.element(childElement));
});
}
function removeAllWatchers(element) {
if (element.data().hasOwnProperty('$scope')) {
element.data().$scope.$$watchers = [];
}
removeChildrenWatchers(element);
}
return {
scope: false,
compile: function($el) {
var template;
var exp;
template = $el.html();
// Compile HTML template into an interpolation function.
exp = $interpolate(template);
return function(scope, $el, attrs) {
// Unique id for this row.
var itemId = attrs.id;
var el = $el;
el.closest('tbody').on('refresh-item-' + itemId, function(e) {
// Remove all watchers from the old element and all its children.
removeChildrenWatchers(el);
var newScope = scope.$parent.$new();
// Copy scope variables from the old root element (<tr> in our case).
copyLocalVariables(scope, newScope);
// Interpolate one time bindings with values and create.
// Also create new watch expressions for ng-show, ng-href and so on.
var html = $compile(exp(newScope))(newScope);
el.html(html);
});
}
},
restrict: 'A'
};
});
// Get text dimension by rendering it into canvas
var contextCache;
function textDimensions(text) {
// re-use canvas object for better performance
if (!contextCache) {
var canvas = document.getElementById('my-canvas');
var context = canvas.getContext("2d");
context.font = '14px Helvetica';
contextCache = context;
}
var metrics = contextCache.measureText(text);
return [metrics.width, metrics.height];
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment