Skip to content

Instantly share code, notes, and snippets.

@capaj
Created October 10, 2013 16:15
Show Gist options
  • Save capaj/6921097 to your computer and use it in GitHub Desktop.
Save capaj/6921097 to your computer and use it in GitHub Desktop.
ng include in the same scope
// same as ng-include, but it does not create it's own scope, if element already has a scope
angular.module('ng-tools').directive('includeInScope',
['$http', '$templateCache', '$anchorScroll', '$compile',
function ($http, $templateCache, $anchorScroll, $compile) {
return {
restrict: 'ECA',
terminal: true,
compile: function (element, attr) {
var srcExp = attr.includeInScope || attr.src,
onloadExp = attr.onload || '',
autoScrollExp = attr.autoscroll;
return function (scope, element) {
var changeCounter = 0,
elmScope = element.scope();
var clearContent = function () {
element.html('');
};
scope.$watch(srcExp, function ngIncludeWatchAction(src) {
var thisChangeId = ++changeCounter;
if (src) {
$http.get(src, {cache: $templateCache}).success(function (response) {
if (thisChangeId !== changeCounter) return;
if (!elmScope) {
elmScope = scope.$new();
}
element.html(response);
$compile(element.contents())(elmScope);
if (angular.isDefined(autoScrollExp) && (!autoScrollExp || scope.$eval(autoScrollExp))) {
$anchorScroll();
}
elmScope.$emit('$includeContentLoaded');
scope.$eval(onloadExp);
}).error(function () {
if (thisChangeId === changeCounter) clearContent();
});
} else clearContent();
});
};
}
};
}
]
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment