major refactoring of scope

This commit is contained in:
Misko Hevery 2010-03-25 22:03:11 -07:00
parent 0cc9b07320
commit d934054cfc
8 changed files with 347 additions and 214 deletions

View file

@ -208,27 +208,6 @@ function bind(_this, _function) {
}; };
} }
function bindTry(_this, _function) {
var args = arguments,
last = args.length - 1,
curryArgs = slice.call(args, 2, last),
exceptionHandler = args[last];
return function() {
try {
return _function.apply(_this, curryArgs.concat(slice.call(arguments, 0, arguments.length)));
} catch (e) {
if (e = exceptionHandler(e)) throw e;
}
};
}
function errorHandlerFor(element) {
return function(error){
element.attr('ng-error', angular.toJson(error));
element.addClass('ng-exception');
};
}
function outerHTML(node) { function outerHTML(node) {
var temp = document.createElement('div'); var temp = document.createElement('div');
temp.appendChild(node); temp.appendChild(node);

View file

@ -14,7 +14,7 @@ Template.prototype = {
init: function(element, scope) { init: function(element, scope) {
element = jqLite(element); element = jqLite(element);
foreach(this.inits, function(fn) { foreach(this.inits, function(fn) {
scope.apply(fn, element); scope.$tryEval(fn, element, element);
}); });
var i, var i,
@ -92,14 +92,11 @@ Compiler.prototype = {
rawElement = jqLite(rawElement); rawElement = jqLite(rawElement);
var template = this.templatize(rawElement) || new Template(); var template = this.templatize(rawElement) || new Template();
return function(element, parentScope){ return function(element, parentScope){
var scope = new Scope(parentScope); var model = scope(parentScope);
scope.element = element; return extend(model, {
// todo return should be a scope with everything already set on it as element $element:element,
return { $init: bind(template, template.init, element, model)
scope: scope, });
element:element,
init: bind(template, template.init, element, scope)
};
}; };
}, },
@ -144,7 +141,7 @@ Compiler.prototype = {
exclusive = true; exclusive = true;
directiveQueue = []; directiveQueue = [];
} }
directiveQueue.push(bindTry(selfApi, directive, value, element, errorHandlerFor(element))); directiveQueue.push(bind(selfApi, directive, value, element));
} }
}); });

View file

@ -53,6 +53,21 @@ Scope.getter = function(instance, path) {
return instance; return instance;
}; };
Scope.setter = function(instance, path, value){
var element = path.split('.');
for ( var i = 0; element.length > 1; i++) {
var key = element.shift();
var newInstance = instance[key];
if (!newInstance) {
newInstance = {};
instance[key] = newInstance;
}
instance = newInstance;
}
instance[element.shift()] = value;
return value;
};
Scope.prototype = { Scope.prototype = {
// TODO: rename to update? or eval? // TODO: rename to update? or eval?
updateView: function() { updateView: function() {
@ -98,19 +113,8 @@ Scope.prototype = {
set: function(path, value) { set: function(path, value) {
// log('SCOPE.set', path, value); // log('SCOPE.set', path, value);
var element = path.split('.');
var instance = this.state; var instance = this.state;
for ( var i = 0; element.length > 1; i++) { return Scope.setter(instance, path, value);
var key = element.shift();
var newInstance = instance[key];
if (!newInstance) {
newInstance = {};
instance[key] = newInstance;
}
instance = newInstance;
}
instance[element.shift()] = value;
return value;
}, },
setEval: function(expressionText, value) { setEval: function(expressionText, value) {
@ -134,9 +138,9 @@ Scope.prototype = {
}; };
}, },
eval: function(expressionText, context) { eval: function(exp, context) {
// log('Scope.eval', expressionText); // log('Scope.eval', expressionText);
return this.compile(expressionText)(context); return this.compile(exp)(context);
}, },
//TODO: Refactor. This function needs to be an execution closure for widgets //TODO: Refactor. This function needs to be an execution closure for widgets
@ -241,3 +245,163 @@ Scope.prototype = {
fn.apply(this.state, slice.call(arguments, 1, arguments.length)); fn.apply(this.state, slice.call(arguments, 1, arguments.length));
} }
}; };
//////////////////////////////
function getter(instance, path) {
if (!path) return instance;
var element = path.split('.');
var key;
var lastInstance = instance;
var len = element.length;
for ( var i = 0; i < len; i++) {
key = element[i];
if (!key.match(/^[\$\w][\$\w\d]*$/))
throw "Expression '" + path + "' is not a valid expression for accesing variables.";
if (instance) {
lastInstance = instance;
instance = instance[key];
}
if (_.isUndefined(instance) && key.charAt(0) == '$') {
var type = angular['Global']['typeOf'](lastInstance);
type = angular[type.charAt(0).toUpperCase()+type.substring(1)];
var fn = type ? type[[key.substring(1)]] : undefined;
if (fn) {
instance = _.bind(fn, lastInstance, lastInstance);
return instance;
}
}
}
if (typeof instance === 'function' && !instance['$$factory']) {
return bind(lastInstance, instance);
}
return instance;
};
function setter(instance, path, value){
var element = path.split('.');
for ( var i = 0; element.length > 1; i++) {
var key = element.shift();
var newInstance = instance[key];
if (!newInstance) {
newInstance = {};
instance[key] = newInstance;
}
instance = newInstance;
}
instance[element.shift()] = value;
return value;
};
var compileCache = {};
function expressionCompile(exp){
if (isFunction(exp)) return exp;
var expFn = compileCache[exp];
if (!expFn) {
var parser = new Parser(exp);
expFn = parser.statements();
parser.assertAllConsumed();
compileCache[exp] = expFn;
}
// return expFn
// TODO(remove this hack)
return function(){
return expFn({
scope: {
set: this.$set,
get: this.$get
}
});
};
};
var NON_RENDERABLE_ELEMENTS = {
'#text': 1, '#comment':1, 'TR':1, 'TH':1
};
function isRenderableElement(element){
return element && element[0] && !NON_RENDERABLE_ELEMENTS[element[0].nodeName];
}
function rethrow(e) { throw e; }
function errorHandlerFor(element) {
while (!isRenderableElement(element)) {
element = element.parent() || jqLite(document.body);
}
return function(error) {
element.attr('ng-error', angular.toJson(error));
element.addClass('ng-exception');
};
}
function scope(parent, Class) {
function Parent(){}
function API(){}
function Behavior(){}
var instance, behavior, api, watchList = [], evalList = [];
Class = Class || noop;
parent = Parent.prototype = parent || {};
api = API.prototype = new Parent();
behavior = Behavior.prototype = extend(new API(), Class.prototype);
instance = new Behavior();
extend(api, {
$parent: parent,
$bind: bind(instance, bind, instance),
$get: bind(instance, getter, instance),
$set: bind(instance, setter, instance),
$eval: function(exp) {
if (isDefined(exp)) {
return expressionCompile(exp).apply(instance, slice.call(arguments, 1, arguments.length));
} else {
foreach(evalList, function(eval) {
instance.$tryEval(eval.fn, eval.handler);
});
foreach(watchList, function(watch) {
var value = instance.$tryEval(watch.watch, watch.handler);
if (watch.last !== value) {
instance.$tryEval(watch.listener, watch.handler, value, watch.last);
watch.last = value;
}
});
}
},
$tryEval: function (expression, exceptionHandler) {
try {
return expressionCompile(expression).apply(instance, slice.call(arguments, 2, arguments.length));
} catch (e) {
error(e);
if (isFunction(exceptionHandler)) {
exceptionHandler(e);
} else if (exceptionHandler) {
errorHandlerFor(exceptionHandler)(e);
}
}
},
$watch: function(watchExp, listener, exceptionHandler) {
var watch = expressionCompile(watchExp);
watchList.push({
watch: watch,
last: watch.call(instance),
handler: exceptionHandler,
listener:expressionCompile(listener)
});
},
$onEval: function(expr, exceptionHandler){
evalList.push({
fn: expressionCompile(expr),
handler: exceptionHandler
});
}
});
Class.apply(instance, slice.call(arguments, 2, arguments.length));
return instance;
}

View file

@ -1,12 +1,12 @@
angularDirective("ng-init", function(expression){ angularDirective("ng-init", function(expression){
return function(){ return function(element){
this.$eval(expression); this.$tryEval(expression, element);
}; };
}); });
angularDirective("ng-eval", function(expression){ angularDirective("ng-eval", function(expression){
return function(){ return function(element){
this.$addEval(expression); this.$onEval(expression, element);
}; };
}); });
@ -14,7 +14,7 @@ angularDirective("ng-bind", function(expression){
return function(element) { return function(element) {
this.$watch(expression, function(value){ this.$watch(expression, function(value){
element.text(value); element.text(value);
}); }, element);
}; };
}); });
@ -45,23 +45,23 @@ angularDirective("ng-bind-template", function(expression){
var templateFn = compileBindTemplate(expression); var templateFn = compileBindTemplate(expression);
return function(element) { return function(element) {
var lastValue; var lastValue;
this.$addEval(function() { this.$onEval(function() {
var value = templateFn.call(this); var value = templateFn.call(this);
if (value != lastValue) { if (value != lastValue) {
element.text(value); element.text(value);
lastValue = value; lastValue = value;
} }
}); }, element);
}; };
}); });
angularDirective("ng-bind-attr", function(expression){ angularDirective("ng-bind-attr", function(expression){
return function(element){ return function(element){
this.$addEval(function(){ this.$onEval(function(){
foreach(this.$eval(expression), function(value, key){ foreach(this.$eval(expression), function(value, key){
element.attr(key, compileBindTemplate(value).call(this)); element.attr(key, compileBindTemplate(value).call(this));
}, this); }, this);
}); }, element);
}; };
}); });
@ -70,76 +70,73 @@ angularDirective("ng-non-bindable", function(){
}); });
angularDirective("ng-repeat", function(expression, element){ angularDirective("ng-repeat", function(expression, element){
var reference = this.comment("ng-repeat: " + expression), element.removeAttr('ng-repeat');
r = element.removeAttr('ng-repeat'), element.replaceWith(this.comment("ng-repeat: " + expression));
template = this.compile(element), var template = this.compile(element);
match = expression.match(/^\s*(.+)\s+in\s+(.*)\s*$/), return function(reference){
lhs, rhs, valueIdent, keyIdent; var match = expression.match(/^\s*(.+)\s+in\s+(.*)\s*$/),
if (! match) { lhs, rhs, valueIdent, keyIdent;
throw "Expected ng-repeat in form of 'item in collection' but got '" + if (! match) {
throw "Expected ng-repeat in form of 'item in collection' but got '" +
expression + "'."; expression + "'.";
} }
lhs = match[1]; lhs = match[1];
rhs = match[2]; rhs = match[2];
match = lhs.match(/^([\$\w]+)|\(([\$\w]+)\s*,\s*([\$\w]+)\)$/); match = lhs.match(/^([\$\w]+)|\(([\$\w]+)\s*,\s*([\$\w]+)\)$/);
if (!match) { if (!match) {
throw "'item' in 'item in collection' should be identifier or (key, value) but got '" + throw "'item' in 'item in collection' should be identifier or (key, value) but got '" +
keyValue + "'."; keyValue + "'.";
} }
valueIdent = match[3] || match[1]; valueIdent = match[3] || match[1];
keyIdent = match[2]; keyIdent = match[2];
var parent = element.parent(); var children = [], currentScope = this;
element.replaceWith(reference); this.$onEval(function(){
return function(){
var children = [],
currentScope = this;
this.$addEval(rhs, function(items){
var index = 0, childCount = children.length, childScope, lastElement = reference; var index = 0, childCount = children.length, childScope, lastElement = reference;
foreach(items || [], function(value, key){ foreach(this.$tryEval(rhs, reference), function(value, key){
if (index < childCount) { if (index < childCount) {
// reuse existing child // reuse existing child
childScope = children[index]; childScope = children[index];
} else { } else {
// grow children // grow children
childScope = template(element.clone(), currentScope); childScope = template(element.clone(), currentScope);
childScope.init(); lastElement.after(childScope.$element);
childScope.scope.set('$index', index); childScope.$index = index;
childScope.element.attr('ng-index', index); childScope.$element.attr('ng-index', index);
lastElement.after(childScope.element); childScope.$init();
children.push(childScope); children.push(childScope);
} }
childScope.scope.set(valueIdent, value); childScope[valueIdent] = value;
if (keyIdent) childScope.scope.set(keyIdent, key); if (keyIdent) childScope[keyIdent] = key;
childScope.scope.updateView(); childScope.$eval();
lastElement = childScope.element; lastElement = childScope.$element;
index ++; index ++;
}); });
// shrink children // shrink children
while(children.length > index) { while(children.length > index) {
children.pop().element.remove(); children.pop().$element.remove();
} }
}); }, reference);
}; };
}, {exclusive: true}); }, {exclusive: true});
angularDirective("ng-action", function(expression, element){ angularDirective("ng-action", function(expression, element){
return function(){ return function(element){
var self = this; var self = this;
element.click(function(){ element.click(function(){
self.$eval(expression); self.$tryEval(expression, element);
}); });
}; };
}); });
angularDirective("ng-watch", function(expression, element){ angularDirective("ng-watch", function(expression, element){
var match = expression.match(/^([^.]*):(.*)$/); var match = expression.match(/^([^.]*):(.*)$/);
if (!match) { return function(element){
throw "Expecting watch expression 'ident_to_watch: watch_statement' got '" if (!match) {
+ expression + "'"; throw "Expecting watch expression 'ident_to_watch: watch_statement' got '"
} + expression + "'";
return function(){ }
this.$watch(match[1], match[2]); this.$watch(match[1], match[2], element);
}; };
}); });
@ -147,12 +144,13 @@ function ngClass(selector) {
return function(expression, element){ return function(expression, element){
var existing = element[0].className + ' '; var existing = element[0].className + ' ';
return function(element){ return function(element){
this.$addEval(expression, function(value){ this.$onEval(function(){
var value = this.$eval(expression);
if (selector(this.$index)) { if (selector(this.$index)) {
if (isArray(value)) value = value.join(' '); if (isArray(value)) value = value.join(' ');
element[0].className = (existing + value).replace(/\s\s+/g, ' '); element[0].className = (existing + value).replace(/\s\s+/g, ' ');
} }
}); }, element);
}; };
}; };
} }
@ -163,25 +161,25 @@ angularDirective("ng-class-even", ngClass(function(i){return i % 2 == 0;}));
angularDirective("ng-show", function(expression, element){ angularDirective("ng-show", function(expression, element){
return function(element){ return function(element){
this.$addEval(expression, function(value){ this.$onEval(function(){
element.css('display', toBoolean(value) ? '' : 'none'); element.css('display', toBoolean(this.$eval(expression)) ? '' : 'none');
}); }, element);
}; };
}); });
angularDirective("ng-hide", function(expression, element){ angularDirective("ng-hide", function(expression, element){
return function(element){ return function(element){
this.$addEval(expression, function(value){ this.$onEval(function(){
element.css('display', toBoolean(value) ? 'none' : ''); element.css('display', toBoolean(this.$eval(expression)) ? 'none' : '');
}); }, element);
}; };
}); });
angularDirective("ng-style", function(expression, element){ angularDirective("ng-style", function(expression, element){
return function(element){ return function(element){
this.$addEval(expression, function(value){ this.$onEval(function(){
element.css(value); element.css(this.$eval(expression));
}); }, element);
}; };
}); });

View file

@ -96,7 +96,7 @@ var NG_ERROR = 'ng-error',
'radio': inputWidget('click', modelAccessor, radioAccessor, undefined), 'radio': inputWidget('click', modelAccessor, radioAccessor, undefined),
'select-one': inputWidget('click', modelAccessor, valueAccessor, null), 'select-one': inputWidget('click', modelAccessor, valueAccessor, null),
'select-multiple': inputWidget('click', modelAccessor, optionsAccessor, []) 'select-multiple': inputWidget('click', modelAccessor, optionsAccessor, [])
// 'file': [{}, 'click'] // 'file': fileWidget???
}; };
function inputWidget(events, modelAccessor, viewAccessor, initValue) { function inputWidget(events, modelAccessor, viewAccessor, initValue) {

View file

@ -1,49 +1,49 @@
describe("directives", function(){ describe("directives", function(){
var compile, element; var compile, model, element;
beforeEach(function() { beforeEach(function() {
var compiler = new Compiler(angularTextMarkup, angularAttrMarkup, angularDirective, angularWidget); var compiler = new Compiler(angularTextMarkup, angularAttrMarkup, angularDirective, angularWidget);
compile = function(html) { compile = function(html) {
element = jqLite(html); element = jqLite(html);
var view = compiler.compile(element)(element); model = compiler.compile(element)(element);
view.init(); model.$init();
return view.scope; return model;
}; };
}); });
afterEach(function() { afterEach(function() {
element.remove(); model.$element.remove();
expect(_(jqCache).size()).toEqual(0); expect(_(jqCache).size()).toEqual(0);
}); });
it("should ng-init", function() { it("should ng-init", function() {
var scope = compile('<div ng-init="a=123"></div>'); var scope = compile('<div ng-init="a=123"></div>');
expect(scope.get('a')).toEqual(123); expect(scope.a).toEqual(123);
}); });
it("should ng-eval", function() { it("should ng-eval", function() {
var scope = compile('<div ng-init="a=0" ng-eval="a = a + 1"></div>'); var scope = compile('<div ng-init="a=0" ng-eval="a = a + 1"></div>');
expect(scope.get('a')).toEqual(0); expect(scope.a).toEqual(0);
scope.updateView(); scope.$eval();
expect(scope.get('a')).toEqual(1); expect(scope.a).toEqual(1);
scope.updateView(); scope.$eval();
expect(scope.get('a')).toEqual(2); expect(scope.a).toEqual(2);
}); });
it('should ng-bind', function() { it('should ng-bind', function() {
var scope = compile('<div ng-bind="a"></div>'); var scope = compile('<div ng-bind="a"></div>');
expect(element.text()).toEqual(''); expect(element.text()).toEqual('');
scope.set('a', 'misko'); scope.a = 'misko';
scope.updateView(); scope.$eval();
expect(element.text()).toEqual('misko'); expect(element.text()).toEqual('misko');
}); });
it('should ng-bind-template', function() { it('should ng-bind-template', function() {
var scope = compile('<div ng-bind-template="Hello {{name}}!"></div>'); var scope = compile('<div ng-bind-template="Hello {{name}}!"></div>');
expect(element.text()).toEqual(''); expect(element.text()).toEqual('');
scope.set('name', 'Misko'); scope.$set('name', 'Misko');
scope.updateView(); scope.$eval();
expect(element.text()).toEqual('Hello Misko!'); expect(element.text()).toEqual('Hello Misko!');
}); });
@ -51,75 +51,73 @@ describe("directives", function(){
var scope = compile('<img ng-bind-attr="{src:\'mysrc\', alt:\'myalt\'}"/>'); var scope = compile('<img ng-bind-attr="{src:\'mysrc\', alt:\'myalt\'}"/>');
expect(element.attr('src')).toEqual(null); expect(element.attr('src')).toEqual(null);
expect(element.attr('alt')).toEqual(null); expect(element.attr('alt')).toEqual(null);
scope.updateView(); scope.$eval();
expect(element.attr('src')).toEqual('mysrc'); expect(element.attr('src')).toEqual('mysrc');
expect(element.attr('alt')).toEqual('myalt'); expect(element.attr('alt')).toEqual('myalt');
}); });
it('should ng-non-bindable', function(){ it('should ng-non-bindable', function(){
var scope = compile('<div ng-non-bindable><span ng-bind="name"></span></div>'); var scope = compile('<div ng-non-bindable><span ng-bind="name"></span></div>');
scope.set('name', 'misko'); scope.$set('name', 'misko');
scope.updateView(); scope.$eval();
expect(element.text()).toEqual(''); expect(element.text()).toEqual('');
}); });
it('should ng-repeat over array', function(){ it('should ng-repeat over array', function(){
var scope = compile('<ul><li ng-repeat="item in items" ng-init="suffix = \';\'" ng-bind="item + suffix"></li></ul>'); var scope = compile('<ul><li ng-repeat="item in items" ng-init="suffix = \';\'" ng-bind="item + suffix"></li></ul>');
scope.set('items', ['misko', 'shyam']); scope.$set('items', ['misko', 'shyam']);
scope.updateView(); scope.$eval();
expect(element.text()).toEqual('misko;shyam;'); expect(element.text()).toEqual('misko;shyam;');
scope.set('items', ['adam', 'kai', 'brad']); scope.$set('items', ['adam', 'kai', 'brad']);
scope.updateView(); scope.$eval();
expect(element.text()).toEqual('adam;kai;brad;'); expect(element.text()).toEqual('adam;kai;brad;');
scope.set('items', ['brad']); scope.$set('items', ['brad']);
scope.updateView(); scope.$eval();
expect(element.text()).toEqual('brad;'); expect(element.text()).toEqual('brad;');
}); });
it('should ng-repeat over object', function(){ it('should ng-repeat over object', function(){
var scope = compile('<ul><li ng-repeat="(key, value) in items" ng-bind="key + \':\' + value + \';\' "></li></ul>'); var scope = compile('<ul><li ng-repeat="(key, value) in items" ng-bind="key + \':\' + value + \';\' "></li></ul>');
scope.set('items', {misko:'swe', shyam:'set'}); scope.$set('items', {misko:'swe', shyam:'set'});
scope.updateView(); scope.$eval();
expect(element.text()).toEqual('misko:swe;shyam:set;'); expect(element.text()).toEqual('misko:swe;shyam:set;');
}); });
it('should error on wrong parsing of ng-repeat', function(){ it('should error on wrong parsing of ng-repeat', function(){
var scope = compile('<ul><li ng-repeat="i dont parse"></li></ul>'); var scope = compile('<ul><li ng-repeat="i dont parse"></li></ul>');
var log = ""; var log = "";
eachNode(element, function(li){ log += element.attr('ng-error') + ';';
log += li.attr('ng-error') + ';'; log += element.hasClass('ng-exception') + ';';
log += li.hasClass('ng-exception') + ';';
});
expect(log).toEqual("\"Expected ng-repeat in form of 'item in collection' but got 'i dont parse'.\";true;"); expect(log).toEqual("\"Expected ng-repeat in form of 'item in collection' but got 'i dont parse'.\";true;");
}); });
it('should ng-watch', function(){ it('should ng-watch', function(){
var scope = compile('<div ng-watch="i: count = count + 1" ng-init="count = 0">'); var scope = compile('<div ng-watch="i: count = count + 1" ng-init="count = 0">');
scope.updateView(); scope.$eval();
scope.updateView(); scope.$eval();
expect(scope.get('count')).toEqual(0); expect(scope.$get('count')).toEqual(0);
scope.set('i', 0); scope.$set('i', 0);
scope.updateView(); scope.$eval();
scope.updateView(); scope.$eval();
expect(scope.get('count')).toEqual(1); expect(scope.$get('count')).toEqual(1);
}); });
it('should ng-action', function(){ it('should ng-action', function(){
var scope = compile('<div ng-action="clicked = true"></div>'); var scope = compile('<div ng-action="clicked = true"></div>');
scope.updateView(); scope.$eval();
expect(scope.get('clicked')).toBeFalsy(); expect(scope.$get('clicked')).toBeFalsy();
element.click(); element.click();
expect(scope.get('clicked')).toEqual(true); expect(scope.$get('clicked')).toEqual(true);
}); });
it('should ng-class', function(){ it('should ng-class', function(){
var scope = compile('<div class="existing" ng-class="[\'A\', \'B\']"></div>'); var scope = compile('<div class="existing" ng-class="[\'A\', \'B\']"></div>');
scope.updateView(); scope.$eval();
expect(element.hasClass('existing')).toBeTruthy(); expect(element.hasClass('existing')).toBeTruthy();
expect(element.hasClass('A')).toBeTruthy(); expect(element.hasClass('A')).toBeTruthy();
expect(element.hasClass('B')).toBeTruthy(); expect(element.hasClass('B')).toBeTruthy();
@ -127,7 +125,7 @@ describe("directives", function(){
it('should ng-class odd/even', function(){ it('should ng-class odd/even', function(){
var scope = compile('<ul><li ng-repeat="i in [0,1]" class="existing" ng-class-odd="\'odd\'" ng-class-even="\'even\'"></li><ul>'); var scope = compile('<ul><li ng-repeat="i in [0,1]" class="existing" ng-class-odd="\'odd\'" ng-class-even="\'even\'"></li><ul>');
scope.updateView(); scope.$eval();
var e1 = jQuery(element.parent()[0]).find('li:first'); var e1 = jQuery(element.parent()[0]).find('li:first');
var e2 = jQuery(element.parent()[0]).find('li:last'); var e2 = jQuery(element.parent()[0]).find('li:last');
expect(e1.hasClass('existing')).toBeTruthy(); expect(e1.hasClass('existing')).toBeTruthy();
@ -138,25 +136,25 @@ describe("directives", function(){
it('should ng-style', function(){ it('should ng-style', function(){
var scope = compile('<div ng-style="{color:\'red\'}"></div>'); var scope = compile('<div ng-style="{color:\'red\'}"></div>');
scope.updateView(); scope.$eval();
expect(element.css('color')).toEqual('red'); expect(element.css('color')).toEqual('red');
}); });
it('should ng-show', function(){ it('should ng-show', function(){
var scope = compile('<div ng-hide="hide"></div>'); var scope = compile('<div ng-hide="hide"></div>');
scope.updateView(); scope.$eval();
expect(element.css('display')).toEqual(''); expect(element.css('display')).toEqual('');
scope.set('hide', true); scope.$set('hide', true);
scope.updateView(); scope.$eval();
expect(element.css('display')).toEqual('none'); expect(element.css('display')).toEqual('none');
}); });
it('should ng-hide', function(){ it('should ng-hide', function(){
var scope = compile('<div ng-show="show"></div>'); var scope = compile('<div ng-show="show"></div>');
scope.updateView(); scope.$eval();
expect(element.css('display')).toEqual('none'); expect(element.css('display')).toEqual('none');
scope.set('show', true); scope.$set('show', true);
scope.updateView(); scope.$eval();
expect(element.css('display')).toEqual(''); expect(element.css('display')).toEqual('');
}); });
}); });

View file

@ -8,9 +8,8 @@ describe("markups", function(){
var compiler = new Compiler(angularTextMarkup, angularAttrMarkup, angularDirective, angularWidget); var compiler = new Compiler(angularTextMarkup, angularAttrMarkup, angularDirective, angularWidget);
compile = function(html) { compile = function(html) {
element = jqLite(html); element = jqLite(html);
var view = compiler.compile(element)(element); scope = compiler.compile(element)(element);
view.init(); scope.$init();
scope = view.scope;
}; };
}); });
@ -24,16 +23,16 @@ describe("markups", function(){
it('should translate {{}} in text', function(){ it('should translate {{}} in text', function(){
compile('<div>hello {{name}}!</div>'); compile('<div>hello {{name}}!</div>');
expect(element.html()).toEqual('hello <span ng-bind="name"></span>!'); expect(element.html()).toEqual('hello <span ng-bind="name"></span>!');
scope.set('name', 'Misko'); scope.$set('name', 'Misko');
scope.updateView(); scope.$eval();
expect(element.html()).toEqual('hello <span ng-bind="name">Misko</span>!'); expect(element.html()).toEqual('hello <span ng-bind="name">Misko</span>!');
}); });
it('should translate {{}} in terminal nodes', function(){ it('should translate {{}} in terminal nodes', function(){
compile('<select name="x"><option value="">Greet {{name}}!</option></select>'); compile('<select name="x"><option value="">Greet {{name}}!</option></select>');
expect(element.html()).toEqual('<option ng-bind-template="Greet {{name}}!" value=""></option>'); expect(element.html()).toEqual('<option ng-bind-template="Greet {{name}}!" value=""></option>');
scope.set('name', 'Misko'); scope.$set('name', 'Misko');
scope.updateView(); scope.$eval();
expect(element.html()).toEqual('<option ng-bind-template="Greet {{name}}!" value="">Greet Misko!</option>'); expect(element.html()).toEqual('<option ng-bind-template="Greet {{name}}!" value="">Greet Misko!</option>');
}); });
@ -41,8 +40,8 @@ describe("markups", function(){
compile('<img src="http://server/{{path}}.png"/>'); compile('<img src="http://server/{{path}}.png"/>');
expect(element.attr('src')).toEqual(); expect(element.attr('src')).toEqual();
expect(element.attr('ng-bind-attr')).toEqual('{"src":"http://server/{{path}}.png"}'); expect(element.attr('ng-bind-attr')).toEqual('{"src":"http://server/{{path}}.png"}');
scope.set('path', 'a/b'); scope.$set('path', 'a/b');
scope.updateView(); scope.$eval();
expect(element.attr('src')).toEqual("http://server/a/b.png"); expect(element.attr('src')).toEqual("http://server/a/b.png");
}); });

View file

@ -1,6 +1,6 @@
describe("input widget", function(){ describe("input widget", function(){
var compile, element, scope, model; var compile, element, scope;
beforeEach(function() { beforeEach(function() {
scope = null; scope = null;
@ -8,10 +8,8 @@ describe("input widget", function(){
var compiler = new Compiler(angularTextMarkup, angularAttrMarkup, angularDirective, angularWidget); var compiler = new Compiler(angularTextMarkup, angularAttrMarkup, angularDirective, angularWidget);
compile = function(html) { compile = function(html) {
element = jqLite(html); element = jqLite(html);
var view = compiler.compile(element)(element); scope = compiler.compile(element)(element);
view.init(); scope.$init();
scope = view.scope;
model = scope.state;
}; };
}); });
@ -22,35 +20,35 @@ describe("input widget", function(){
it('should input-text auto init and handle keyup/change events', function(){ it('should input-text auto init and handle keyup/change events', function(){
compile('<input type="Text" name="name" value="Misko" ng-action="count = count + 1" ng-init="count=0"/>'); compile('<input type="Text" name="name" value="Misko" ng-action="count = count + 1" ng-init="count=0"/>');
expect(scope.get('name')).toEqual("Misko"); expect(scope.$get('name')).toEqual("Misko");
expect(scope.get('count')).toEqual(0); expect(scope.$get('count')).toEqual(0);
scope.set('name', 'Adam'); scope.$set('name', 'Adam');
scope.updateView(); scope.$eval();
expect(element.val()).toEqual("Adam"); expect(element.val()).toEqual("Adam");
element.val('Shyam'); element.val('Shyam');
element.trigger('keyup'); element.trigger('keyup');
expect(scope.get('name')).toEqual('Shyam'); expect(scope.$get('name')).toEqual('Shyam');
expect(scope.get('count')).toEqual(1); expect(scope.$get('count')).toEqual(1);
element.val('Kai'); element.val('Kai');
element.trigger('change'); element.trigger('change');
expect(scope.get('name')).toEqual('Kai'); expect(scope.$get('name')).toEqual('Kai');
expect(scope.get('count')).toEqual(2); expect(scope.$get('count')).toEqual(2);
}); });
it("should process ng-format", function(){ it("should process ng-format", function(){
compile('<input type="Text" name="list" value="a,b,c" ng-format="list"/>'); compile('<input type="Text" name="list" value="a,b,c" ng-format="list"/>');
expect(scope.get('list')).toEqual(['a', 'b', 'c']); expect(scope.$get('list')).toEqual(['a', 'b', 'c']);
scope.set('list', ['x', 'y', 'z']); scope.$set('list', ['x', 'y', 'z']);
scope.updateView(); scope.$eval();
expect(element.val()).toEqual("x, y, z"); expect(element.val()).toEqual("x, y, z");
element.val('1, 2, 3'); element.val('1, 2, 3');
element.trigger('keyup'); element.trigger('keyup');
expect(scope.get('list')).toEqual(['1', '2', '3']); expect(scope.$get('list')).toEqual(['1', '2', '3']);
}); });
it("should process ng-validation", function(){ it("should process ng-validation", function(){
@ -58,8 +56,8 @@ describe("input widget", function(){
expect(element.hasClass('ng-validation-error')).toBeTruthy(); expect(element.hasClass('ng-validation-error')).toBeTruthy();
expect(element.attr('ng-error')).toEqual('Not a number'); expect(element.attr('ng-error')).toEqual('Not a number');
scope.set('price', '123'); scope.$set('price', '123');
scope.updateView(); scope.$eval();
expect(element.hasClass('ng-validation-error')).toBeFalsy(); expect(element.hasClass('ng-validation-error')).toBeFalsy();
expect(element.attr('ng-error')).toBeFalsy(); expect(element.attr('ng-error')).toBeFalsy();
@ -74,8 +72,8 @@ describe("input widget", function(){
expect(element.hasClass('ng-validation-error')).toBeTruthy(); expect(element.hasClass('ng-validation-error')).toBeTruthy();
expect(element.attr('ng-error')).toEqual('Required'); expect(element.attr('ng-error')).toEqual('Required');
scope.set('price', 'xxx'); scope.$set('price', 'xxx');
scope.updateView(); scope.$eval();
expect(element.hasClass('ng-validation-error')).toBeFalsy(); expect(element.hasClass('ng-validation-error')).toBeFalsy();
expect(element.attr('ng-error')).toBeFalsy(); expect(element.attr('ng-error')).toBeFalsy();
@ -87,41 +85,41 @@ describe("input widget", function(){
it("should process ng-required", function() { it("should process ng-required", function() {
compile('<textarea name="name">Misko</textarea>'); compile('<textarea name="name">Misko</textarea>');
expect(scope.get('name')).toEqual("Misko"); expect(scope.$get('name')).toEqual("Misko");
scope.set('name', 'Adam'); scope.$set('name', 'Adam');
scope.updateView(); scope.$eval();
expect(element.val()).toEqual("Adam"); expect(element.val()).toEqual("Adam");
element.val('Shyam'); element.val('Shyam');
element.trigger('keyup'); element.trigger('keyup');
expect(scope.get('name')).toEqual('Shyam'); expect(scope.$get('name')).toEqual('Shyam');
element.val('Kai'); element.val('Kai');
element.trigger('change'); element.trigger('change');
expect(scope.get('name')).toEqual('Kai'); expect(scope.$get('name')).toEqual('Kai');
}); });
it('should call ng-action on button click', function(){ it('should call ng-action on button click', function(){
compile('<input type="button" value="Click Me" ng-action="clicked = true"/>'); compile('<input type="button" value="Click Me" ng-action="clicked = true"/>');
element.click(); element.click();
expect(scope.get('clicked')).toEqual(true); expect(scope.$get('clicked')).toEqual(true);
}); });
it('should support button alias', function(){ it('should support button alias', function(){
compile('<button ng-action="clicked = true">Click Me</button>'); compile('<button ng-action="clicked = true">Click Me</button>');
element.click(); element.click();
expect(scope.get('clicked')).toEqual(true); expect(scope.$get('clicked')).toEqual(true);
}); });
it('should type="checkbox"', function(){ it('should type="checkbox"', function(){
compile('<input type="checkbox" name="checkbox" checked ng-action="action = true"/>'); compile('<input type="checkbox" name="checkbox" checked ng-action="action = true"/>');
expect(scope.get('checkbox')).toEqual(true); expect(scope.$get('checkbox')).toEqual(true);
element.click(); element.click();
expect(scope.get('checkbox')).toEqual(false); expect(scope.$get('checkbox')).toEqual(false);
expect(scope.get('action')).toEqual(true); expect(scope.$get('action')).toEqual(true);
element.click(); element.click();
expect(scope.get('checkbox')).toEqual(true); expect(scope.$get('checkbox')).toEqual(true);
}); });
it('should type="radio"', function(){ it('should type="radio"', function(){
@ -131,21 +129,21 @@ describe("input widget", function(){
'</div>'); '</div>');
var a = element[0].childNodes[0]; var a = element[0].childNodes[0];
var b = element[0].childNodes[1]; var b = element[0].childNodes[1];
expect(model.chose).toEqual('B'); expect(scope.chose).toEqual('B');
expect(model.clicked).not.toBeDefined(); expect(scope.clicked).not.toBeDefined();
model.chose = 'A'; scope.chose = 'A';
model.$updateView(); scope.$eval();
expect(a.checked).toEqual(true); expect(a.checked).toEqual(true);
model.chose = 'B'; scope.chose = 'B';
model.$updateView(); scope.$eval();
expect(a.checked).toEqual(false); expect(a.checked).toEqual(false);
expect(b.checked).toEqual(true); expect(b.checked).toEqual(true);
expect(model.clicked).not.toBeDefined(); expect(scope.clicked).not.toBeDefined();
jqLite(a).click(); jqLite(a).click();
expect(model.chose).toEqual('A'); expect(scope.chose).toEqual('A');
expect(model.clicked).toEqual(1); expect(scope.clicked).toEqual(1);
}); });
it('should type="select-one"', function(){ it('should type="select-one"', function(){
@ -154,10 +152,10 @@ describe("input widget", function(){
'<option>A</option>' + '<option>A</option>' +
'<option selected>B</option>' + '<option selected>B</option>' +
'</select>'); '</select>');
expect(model.selection).toEqual('B'); expect(scope.selection).toEqual('B');
model.selection = 'A'; scope.selection = 'A';
model.$updateView(); scope.$eval();
expect(model.selection).toEqual('A'); expect(scope.selection).toEqual('A');
expect(element[0].childNodes[0].selected).toEqual(true); expect(element[0].childNodes[0].selected).toEqual(true);
}); });
@ -167,14 +165,14 @@ describe("input widget", function(){
'<option>A</option>' + '<option>A</option>' +
'<option selected>B</option>' + '<option selected>B</option>' +
'</select>'); '</select>');
expect(model.selection).toEqual(['B']); expect(scope.selection).toEqual(['B']);
model.selection = ['A']; scope.selection = ['A'];
model.$updateView(); scope.$eval();
expect(element[0].childNodes[0].selected).toEqual(true); expect(element[0].childNodes[0].selected).toEqual(true);
}); });
it('should report error on missing field', function(){ it('should report error on missing field', function(){
//compile('<input type="text"/>');
}); });
it('should report error on assignment error', function(){ it('should report error on assignment error', function(){