Skip to content

Instantly share code, notes, and snippets.

@arey
Last active August 29, 2015 14:00
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save arey/11011876 to your computer and use it in GitHub Desktop.
Save arey/11011876 to your computer and use it in GitHub Desktop.
HTML et JavaScript basé sur le hand's on labs "AngularJS from scratch : comprendre Angular en le re-faisant de zéro" de Devoxx France 2014
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>AngularJS from scratch</title>
</head>
<body class="container text-center">
<h1 class="page-header" ng-bind="labs.titre">AngularJS from scratch</h1>
<input type="text" ng-model="labs.titre"/>
<script src="http://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.6.0/underscore.js"></script>
<script type="text/javascript">
function Scope() {
this.$$watchers = [];
}
Scope.prototype.$watch = function (watcherFn, listenerFn) {
var watcher = {
watcherFn: watcherFn,
listenerFn: listenerFn,
last: undefined
};
this.$$watchers.push(watcher);
}
Scope.prototype.$digest = function () {
var dirty;
do {
dirty = false;
_.each(this.$$watchers, function (watcher) {
var newValue = watcher.watcherFn(this);
if (watcher.last !== newValue) {
watcher.listenerFn(newValue, watcher.last, this);
watcher.last = newValue;
dirty = true;
}
}.bind(this));
} while (dirty);
}
Scope.prototype.$apply = function (exprFn) {
try {
exprFn();
} finally {
this.$digest();
}
}
var $$directives = {};
var $directive = function (name, directiveFn) {
if (directiveFn) {
$$directives[name] = directiveFn;
}
return $$directives[name];
}
var $compile = function(element, scope) {
_.each(element.children, function (child) {
$compile(child, scope);
});
_.each(element.attributes, function(attribute) {
var directiveFn = $directive(attribute.name);
if (directiveFn) {
directiveFn(scope, element, element.attributes);
}
});
}
$directive('ng-bind', function (scope, element, attributes) {
scope.$watch(function(scope) {
return eval('scope.' + attributes['ng-bind'].value);
}, function(newValue) {
element.innerHTML = newValue;
});
});
$directive('ng-model', function(scope, element, attributes) {
scope.$watch(function() {
return eval('scope.' + attributes['ng-model'].value);
}, function(newValue) {
element.value = newValue;
});
element.addEventListener('keyup', function() {
scope.$apply(function() {
eval('scope.' + attributes['ng-model'].value + ' = \"' + element.value + '\"');
});
});
});
var scope = new Scope();
scope.labs = {
titre: "AngularJS from scratch",
date: new Date()
}
$compile(document.body, scope);
scope.$watch(function (scope) {
return scope.labst.itre;
}, function (newValue, oldValue, scope) {
console.log("La titre a changé de", oldValue, "à", newValue);
});
scope.$apply(function () {
scope.labs.titre = "Hello World";
})
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment