-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy path04-rendering-vs-binding.html
112 lines (100 loc) · 3.91 KB
/
04-rendering-vs-binding.html
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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>AngularJS Rendering vs. Binding Example</title>
<script src="angular.js"></script>
<script type="text/javascript">
'use strict';
(function (app) {
var db = 'Current is Rendered; Switch to Data-Binding',
r = 'Current is Data-binding; Switch to Rendered';
function countWatches () {
var watchers = [],
f = function (element) {
if (element.scope()) {
angular.forEach(element.scope().$$watchers, function (w) {
watchers.push(w);
});
}
angular.forEach(element.children(), function (child) {
f(angular.element(child));
});
};
f(angular.element(document.getElementsByTagName('body')));
return watchers.length;
}
function Controller ($compile, $scope, $timeout) {
var idx = 0;
this.compile = function (e) {
$compile(e)($scope);
};
this.$timeout = $timeout;
this.list = [];
while (idx < 1000) {
this.list.push(Math.random());
idx += 1;
}
this.countWatches();
}
Controller.$inject = ['$compile', '$scope', '$timeout'];
angular.extend(Controller.prototype, {
watches: 0,
countWatches: function () {
var _this = this;
this.$timeout(function () {
_this.watches = countWatches()
}, 0);
},
text: db,
dataBound: false,
toggle: function () {
this.text = this.dataBound ? db : r;
this.dataBound = !this.dataBound;
this.countWatches();
}
});
app.controller('myCtrl', Controller);
app.directive('renderList', function () {
return {
restrict: 'E',
scope: {
list: '='
},
replace: true,
link: function (scope, element, attrs) {
var list, idx, html;
if (attrs.list) {
list = scope.$parent.$eval(attrs.list).slice(0);
if (list && list.length) {
html = '<div>';
for (idx = 0; idx < list.length; idx += 1) {
html += ('<span>' + list[idx].toString() + '</span>');
}
html += '</div>';
}
else {
html = '<div/>';
}
element.html(html);
scope.$destroy();
}
}
};
});
})(angular.module('angularApp', []));
</script>
</head>
<body data-ng-app="angularApp">
<h1>Angular Debugging and Performance</h1>
<h2>Rendering vs. Binding</h2>
<p>Example of rendering static data vs. using data-binding.</p>
<div data-ng-controller="myCtrl as ctrl">
<p>Watch Count: {{ctrl.watches}}</p>
<button data-ng-click="ctrl.countWatches()">Refresh</button>
<button data-ng-click="ctrl.toggle()">{{ctrl.text}}</button>
<render-list data-ng-if="!ctrl.dataBound" data-list="ctrl.list"></render-list>
<div data-ng-if="ctrl.dataBound"><span data-ng-repeat="number in ctrl.list">{{number}}</span></div>
</div>
</body>
</html>