added ng-controller directive

This commit is contained in:
Misko Hevery 2010-04-05 21:26:52 -07:00
parent 2107eafcde
commit e646068586
4 changed files with 40 additions and 3 deletions

View file

@ -1,4 +1,4 @@
function getter(instance, path) {
function getter(instance, path, unboundFn) {
if (!path) return instance;
var element = path.split('.');
var key;
@ -22,7 +22,7 @@ function getter(instance, path) {
}
}
}
if (typeof instance === 'function' && !instance['$$factory']) {
if (!unboundFn && isFunction(instance) && !instance['$$factory']) {
return bind(lastInstance, instance);
}
return instance;
@ -146,7 +146,17 @@ function createScope(parent, services, existing) {
fn: expressionCompile(expr),
handler: exceptionHandler
});
},
$become: function(Class) {
// remove existing
foreach(behavior, function(value, key){ delete behavior[key]; });
foreach((Class || noop).prototype, function(fn, name){
behavior[name] = bind(instance, fn);
});
(Class || noop).call(instance);
}
});
if (!parent.$root) {

View file

@ -4,6 +4,17 @@ angularDirective("ng-init", function(expression){
};
});
angularDirective("ng-controller", function(expression){
return function(element){
var controller = getter(window, expression, true) || getter(this, expression, true);
if (!controller)
throw "Can not find '"+expression+"' controller.";
if (!isFunction(controller))
throw "Reference '"+expression+"' is not a class.";
this.$become(controller);
};
});
angularDirective("ng-eval", function(expression){
return function(element){
this.$onEval(expression, element);

View file

@ -115,7 +115,8 @@ JQLite.prototype = {
remove: function() {
this.dealoc();
this[0].parentNode.removeChild(this[0]);
var parentNode = this[0].parentNode;
if (parentNode) parentNode.removeChild(this[0]);
},
removeAttr: function(name) {

View file

@ -156,4 +156,19 @@ describe("directives", function(){
scope.$eval();
expect(element.css('display')).toEqual('');
});
it('should ng-controller', function(){
window.Greeter = function(){
this.greeting = 'hello';
};
window.Greeter.prototype = {
greet: function(name) {
return this.greeting + ' ' + name;
}
};
var scope = compile('<div ng-controller="Greeter"></div>');
expect(scope.greeting).toEqual('hello');
expect(scope.greet('misko')).toEqual('hello misko');
delete window.Greeter;
});
});