This repository has been archived by the owner on Apr 3, 2022. It is now read-only.
forked from megawebmaster/angularjs-viewhead
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathangularjs-viewhead.js
79 lines (71 loc) · 3.22 KB
/
angularjs-viewhead.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
(function (angular) {
var mod = angular.module('viewhead', []);
var title;
var titleChanged;
mod.directive(
'viewTitle',
['$rootScope', '$timeout', function ($rootScope, $timeout) {
return {
restrict: 'EA',
link: function (scope, iElement, iAttrs, controller, transcludeFn) {
// If we've been inserted as an element then we detach from the DOM because the caller
// doesn't want us to have any visual impact in the document.
// Otherwise, we're piggy-backing on an existing element so we'll just leave it alone.
var tagName = iElement[0].tagName.toLowerCase();
if (tagName === 'view-title' || tagName === 'viewtitle') {
iElement.remove();
}
scope.$watch(
function () {
return iElement.text();
},
function (newTitle) {
titleChanged = true;
$rootScope.viewTitle = title = newTitle;
}
);
scope.$on(
'$destroy',
function () {
title = undefined;
// Wait until next digest cycle do delete viewTitle
$timeout(function() {
if(!title && !titleChanged) {
// No other view-title has reassigned title.
delete $rootScope.viewTitle;
}
titleChanged = false;
});
}
);
}
};
}]
);
mod.directive(
'viewHead',
['$document', function ($document) {
var head = angular.element($document[0].head);
return {
restrict: 'A',
link: function (scope, iElement, iAttrs, controller, transcludeFn) {
// Move the element into the head of the document.
// Although the physical location of the document changes, the element remains
// bound to the scope in which it was declared, so it can refer to variables from
// the view scope if necessary.
head.append(iElement);
// When the scope is destroyed, remove the element.
// This is on the assumption that we're being used in some sort of view scope.
// It doesn't make sense to use this directive outside of the view, and nor does it
// make sense to use it inside other scope-creating directives like ng-repeat.
scope.$on(
'$destroy',
function () {
iElement.remove();
}
);
}
};
}]
);
})(angular);