refactor(scope): separate controller from scope

Controller is standalone object, created using "new" operator, not messed up with scope anymore.
Instead, related scope is injected as $scope.

See design proposal: https://docs.google.com/document/pub?id=1SsgVj17ec6tnZEX3ugsvg0rVVR11wTso5Md-RdEmC0k

Closes #321
Closes #425

Breaks controller methods are not exported to scope automatically
Breaks Scope#$new() does not take controller as argument anymore
This commit is contained in:
Vojta Jina 2011-11-29 21:51:59 -08:00
parent f5343c9fd3
commit 992c790f07
34 changed files with 481 additions and 520 deletions

View file

@ -40,8 +40,8 @@ All `inputType` widgets support:
<doc:example> <doc:example>
<doc:source> <doc:source>
<script> <script>
angular.inputType('json', function() { angular.inputType('json', function(element, scope) {
this.$parseView = function() { scope.$parseView = function() {
try { try {
this.$modelValue = angular.fromJson(this.$viewValue); this.$modelValue = angular.fromJson(this.$viewValue);
if (this.$error.JSON) { if (this.$error.JSON) {
@ -52,19 +52,19 @@ All `inputType` widgets support:
} }
} }
this.$parseModel = function() { scope.$parseModel = function() {
this.$viewValue = angular.toJson(this.$modelValue); this.$viewValue = angular.toJson(this.$modelValue);
} }
}); });
function Ctrl() { function Ctrl($scope) {
this.data = { $scope.data = {
framework:'angular', framework:'angular',
codenames:'supper-powers' codenames:'supper-powers'
} }
this.required = false; $scope.required = false;
this.disabled = false; $scope.disabled = false;
this.readonly = false; $scope.readonly = false;
} }
</script> </script>
<div ng:controller="Ctrl"> <div ng:controller="Ctrl">

View file

@ -8,10 +8,8 @@ detection, and preventing invalid form submission.
<doc:example> <doc:example>
<doc:source> <doc:source>
<script> <script>
function UserForm() { function UserForm($scope) {
this.state = /^\w\w$/; var master = {
this.zip = /^\d\d\d\d\d$/;
this.master = {
name: 'John Smith', name: 'John Smith',
address:{ address:{
line1: '123 Main St.', line1: '123 Main St.',
@ -23,40 +21,42 @@ detection, and preventing invalid form submission.
{type:'phone', value:'1(234) 555-1212'} {type:'phone', value:'1(234) 555-1212'}
] ]
}; };
this.cancel();
}
UserForm.prototype = { $scope.state = /^\w\w$/;
cancel: function() { $scope.zip = /^\d\d\d\d\d$/;
this.form = angular.copy(this.master);
},
save: function() { $scope.cancel = function() {
this.master = this.form; $scope.form = angular.copy(master);
this.cancel(); };
},
addContact: function() { $scope.save = function() {
this.form.contacts.push({type:'', value:''}); master = $scope.form;
}, $scope.cancel();
};
removeContact: function(contact) { $scope.addContact = function() {
for ( var i = 0, ii = this.form.contacts.length; i < ii; i++) { $scope.form.contacts.push({type:'', value:''});
if (contact === this.form.contacts[i]) { };
this.form.contacts.splice(i, 1);
$scope.removeContact = function(contact) {
var contacts = $scope.form.contacts;
for (var i = 0, ii = contacts.length; i < ii; i++) {
if (contact === contacts[i]) {
contacts.splice(i, 1);
} }
} }
}, };
isCancelDisabled: function() { $scope.isCancelDisabled = function() {
return angular.equals(this.master, this.form); return angular.equals(master, $scope.form);
}, };
isSaveDisabled: function() { $scope.isSaveDisabled = function() {
return this.myForm.$invalid || angular.equals(this.master, this.form); return $scope.myForm.$invalid || angular.equals(master, $scope.form);
} };
}; $scope.cancel();
}
</script> </script>
<div ng:controller="UserForm"> <div ng:controller="UserForm">
@ -91,8 +91,7 @@ detection, and preventing invalid form submission.
<hr/> <hr/>
Debug View: Debug View:
<pre>form={{form}} <pre>form={{form}}</pre>
master={{master}}</pre>
</div> </div>
</doc:source> </doc:source>
<doc:scenario> <doc:scenario>

View file

@ -39,42 +39,38 @@ The two partials are defined in the following URLs:
<doc:example> <doc:example>
<doc:source jsfiddle="false"> <doc:source jsfiddle="false">
<script> <script>
AppCntl.$inject = ['$route'] AppCntl.$inject = ['$scope', '$route']
function AppCntl($route) { function AppCntl($scope, $route) {
// define routes // define routes
$route.when("/welcome", {template:'./examples/welcome.html', controller:WelcomeCntl}); $route.when("/welcome", {template:'./examples/welcome.html', controller:WelcomeCntl});
$route.when("/settings", {template:'./examples/settings.html', controller:SettingsCntl}); $route.when("/settings", {template:'./examples/settings.html', controller:SettingsCntl});
$route.parent(this); $route.parent($scope);
// initialize the model to something useful // initialize the model to something useful
this.person = { $scope.person = {
name:'anonymous', name:'anonymous',
contacts:[{type:'email', url:'anonymous@example.com'}] contacts:[{type:'email', url:'anonymous@example.com'}]
}; };
} }
function WelcomeCntl($route){} function WelcomeCntl($scope) {
WelcomeCntl.prototype = { $scope.greet = function() {
greet: function() { alert("Hello " + $scope.person.name);
alert("Hello " + this.person.name); };
}
};
SettingsCntl.$inject = ['$location'];
function SettingsCntl($location){
this.$location = $location;
this.cancel();
} }
SettingsCntl.prototype = {
cancel: function() {
this.form = angular.copy(this.person);
},
save: function() { function SettingsCntl($scope, $location) {
angular.copy(this.form, this.person); $scope.cancel = function() {
this.$location.path('/welcome'); $scope.form = angular.copy($scope.person);
} };
};
$scope.save = function() {
angular.copy($scope.form, $scope.person);
$location.path('/welcome');
};
$scope.cancel();
}
</script> </script>
<div ng:controller="AppCntl"> <div ng:controller="AppCntl">
<h1>Your App Chrome</h1> <h1>Your App Chrome</h1>

View file

@ -10,23 +10,23 @@ allow a user to enter data.
<doc:example> <doc:example>
<doc:source> <doc:source>
<script> <script>
function FormController() { function FormController($scope) {
this.user = { $scope.user = {
name: 'John Smith', name: 'John Smith',
address:{line1: '123 Main St.', city:'Anytown', state:'AA', zip:'12345'}, address:{line1: '123 Main St.', city:'Anytown', state:'AA', zip:'12345'},
contacts:[{type:'phone', value:'1(234) 555-1212'}] contacts:[{type:'phone', value:'1(234) 555-1212'}]
}; };
this.state = /^\w\w$/; $scope.state = /^\w\w$/;
this.zip = /^\d\d\d\d\d$/; $scope.zip = /^\d\d\d\d\d$/;
this.addContact = function() { $scope.addContact = function() {
this.user.contacts.push({type:'', value:''}); $scope.user.contacts.push({type:'', value:''});
}; };
this.removeContact = function(contact) { $scope.removeContact = function(contact) {
for ( var i = 0, ii = this.user.contacts.length; i < ii; i++) { for (var i = 0, ii = this.user.contacts.length; i < ii; i++) {
if (contact === this.user.contacts[i]) { if (contact === this.user.contacts[i]) {
this.user.contacts.splice(i, 1); $scope.user.contacts.splice(i, 1);
} }
} }
}; };

View file

@ -5,8 +5,8 @@
<doc:example> <doc:example>
<doc:source> <doc:source>
<script> <script>
function HelloCntl() { function HelloCntl($scope) {
this.name = 'World'; $scope.name = 'World';
} }
</script> </script>
<div ng:controller="HelloCntl"> <div ng:controller="HelloCntl">

View file

@ -14,9 +14,8 @@ no connection between the controller and the view.
<doc:example> <doc:example>
<doc:source> <doc:source>
<script> <script>
function TicTacToeCntl($location){ function TicTacToeCntl($scope, $location) {
this.$location = $location; $scope.cellStyle= {
this.cellStyle= {
'height': '20px', 'height': '20px',
'width': '20px', 'width': '20px',
'border': '1px solid black', 'border': '1px solid black',
@ -24,30 +23,40 @@ no connection between the controller and the view.
'vertical-align': 'middle', 'vertical-align': 'middle',
'cursor': 'pointer' 'cursor': 'pointer'
}; };
this.reset();
this.$watch('$location.search().board', this.readUrl); $scope.reset = function() {
} $scope.board = [
TicTacToeCntl.prototype = {
dropPiece: function(row, col) {
if (!this.winner && !this.board[row][col]) {
this.board[row][col] = this.nextMove;
this.nextMove = this.nextMove == 'X' ? 'O' : 'X';
this.setUrl();
}
},
reset: function() {
this.board = [
['', '', ''], ['', '', ''],
['', '', ''], ['', '', ''],
['', '', ''] ['', '', '']
]; ];
this.nextMove = 'X'; $scope.nextMove = 'X';
this.winner = ''; $scope.winner = '';
this.setUrl(); setUrl();
}, };
grade: function() {
var b = this.board; $scope.dropPiece = function(row, col) {
this.winner = if (!$scope.winner && !$scope.board[row][col]) {
$scope.board[row][col] = $scope.nextMove;
$scope.nextMove = $scope.nextMove == 'X' ? 'O' : 'X';
setUrl();
}
};
$scope.reset();
$scope.$watch(function() { return $location.search().board;}, readUrl);
function setUrl() {
var rows = [];
angular.forEach($scope.board, function(row) {
rows.push(row.join(','));
});
$location.search({board: rows.join(';') + '/' + $scope.nextMove});
}
function grade() {
var b = $scope.board;
$scope.winner =
row(0) || row(1) || row(2) || row(0) || row(1) || row(2) ||
col(0) || col(1) || col(2) || col(0) || col(1) || col(2) ||
diagonal(-1) || diagonal(1); diagonal(-1) || diagonal(1);
@ -55,25 +64,19 @@ no connection between the controller and the view.
function col(col) { return same(b[0][col], b[1][col], b[2][col]);} function col(col) { return same(b[0][col], b[1][col], b[2][col]);}
function diagonal(i) { return same(b[0][1-i], b[1][1], b[2][1+i]);} function diagonal(i) { return same(b[0][1-i], b[1][1], b[2][1+i]);}
function same(a, b, c) { return (a==b && b==c) ? a : '';}; function same(a, b, c) { return (a==b && b==c) ? a : '';};
}, }
setUrl: function() {
var rows = []; function readUrl(scope, value) {
angular.forEach(this.board, function(row){
rows.push(row.join(','));
});
this.$location.search({board: rows.join(';') + '/' + this.nextMove});
},
readUrl: function(scope, value) {
if (value) { if (value) {
value = value.split('/'); value = value.split('/');
this.nextMove = value[1]; $scope.nextMove = value[1];
angular.forEach(value[0].split(';'), function(row, col){ angular.forEach(value[0].split(';'), function(row, col){
this.board[col] = row.split(','); $scope.board[col] = row.split(',');
}, this); });
this.grade(); grade();
} }
} }
}; }
</script> </script>
<h3>Tic-Tac-Toe</h3> <h3>Tic-Tac-Toe</h3>

View file

@ -51,14 +51,14 @@ You can try evaluating different expressions here:
<doc:example> <doc:example>
<doc:source> <doc:source>
<script> <script>
function Cntl2() { function Cntl2($scope) {
this.exprs = []; $scope.exprs = [];
this.expr = '3*10|currency'; $scope.expr = '3*10|currency';
this.addExp = function(expr) { $scope.addExp = function(expr) {
this.exprs.push(expr); this.exprs.push(expr);
}; };
this.removeExp = function(contact) { $scope.removeExp = function(contact) {
for ( var i = 0, ii = this.exprs.length; i < ii; i++) { for ( var i = 0, ii = this.exprs.length; i < ii; i++) {
if (contact === this.exprs[i]) { if (contact === this.exprs[i]) {
this.exprs.splice(i, 1); this.exprs.splice(i, 1);
@ -101,10 +101,10 @@ the global state (a common source of subtle bugs).
<doc:example> <doc:example>
<doc:source> <doc:source>
<script> <script>
function Cntl1($window){ function Cntl1($window, $scope){
this.name = 'World'; $scope.name = 'World';
this.greet = function() { $scope.greet = function() {
($window.mockWindow || $window).alert('Hello ' + this.name); ($window.mockWindow || $window).alert('Hello ' + this.name);
} }
} }

View file

@ -111,10 +111,10 @@ The following example demonstrates:
.ng-form {display: block;} .ng-form {display: block;}
</style> </style>
<script> <script>
function UserFormCntl() { function UserFormCntl($scope) {
this.state = /^\w\w$/; $scope.state = /^\w\w$/;
this.zip = /^\d\d\d\d\d$/; $scope.zip = /^\d\d\d\d\d$/;
this.master = { $scope.master = {
customer: 'John Smith', customer: 'John Smith',
address:{ address:{
line1: '123 Main St.', line1: '123 Main St.',
@ -123,28 +123,26 @@ The following example demonstrates:
zip:'12345' zip:'12345'
} }
}; };
this.cancel();
$scope.cancel = function() {
$scope.form = angular.copy($scope.master);
};
$scope.save = function() {
$scope.master = $scope.form;
$scope.cancel();
};
$scope.isCancelDisabled = function() {
return angular.equals($scope.master, $scope.form);
};
$scope.isSaveDisabled = function() {
return $scope.userForm.$invalid || angular.equals($scope.master, $scope.form);
};
$scope.cancel();
} }
UserFormCntl.prototype = {
cancel: function() {
this.form = angular.copy(this.master);
},
save: function() {
this.master = this.form;
this.cancel();
},
isCancelDisabled: function() {
return angular.equals(this.master, this.form);
},
isSaveDisabled: function() {
return this.userForm.$invalid || angular.equals(this.master, this.form);
}
};
</script> </script>
<div ng:controller="UserFormCntl"> <div ng:controller="UserFormCntl">
@ -282,15 +280,13 @@ This example shows how to implement a custom HTML editor widget in Angular.
<doc:example> <doc:example>
<doc:source> <doc:source>
<script> <script>
function EditorCntl() { function EditorCntl($scope) {
this.htmlContent = '<b>Hello</b> <i>World</i>!'; $scope.htmlContent = '<b>Hello</b> <i>World</i>!';
} }
HTMLEditorWidget.$inject = ['$element', 'htmlFilter']; HTMLEditorWidget.$inject = ['$element', '$scope', 'htmlFilter'];
function HTMLEditorWidget(element, htmlFilter) { function HTMLEditorWidget(element, scope, htmlFilter) {
var self = this; scope.$parseModel = function() {
this.$parseModel = function() {
// need to protect for script injection // need to protect for script injection
try { try {
this.$viewValue = htmlFilter( this.$viewValue = htmlFilter(
@ -305,13 +301,13 @@ This example shows how to implement a custom HTML editor widget in Angular.
} }
} }
this.$render = function() { scope.$render = function() {
element.html(this.$viewValue); element.html(this.$viewValue);
} }
element.bind('keyup', function() { element.bind('keyup', function() {
self.$apply(function() { scope.$apply(function() {
self.$emit('$viewChange', element.html()); scope.$emit('$viewChange', element.html());
}); });
}); });
} }
@ -364,13 +360,13 @@ validation.
<doc:example> <doc:example>
<doc:source> <doc:source>
<script> <script>
function Ctrl() { function Ctrl($scope) {
this.input1 = ''; $scope.input1 = '';
this.input2 = ''; $scope.input2 = '';
this.input3 = 'A'; $scope.input3 = 'A';
this.input4 = false; $scope.input4 = false;
this.input5 = 'c'; $scope.input5 = 'c';
this.input6 = []; $scope.input6 = [];
} }
</script> </script>
<table style="font-size:.9em;" ng:controller="Ctrl"> <table style="font-size:.9em;" ng:controller="Ctrl">

View file

@ -43,9 +43,9 @@ easier a web developer's life can if they're using angular:
<doc:example> <doc:example>
<doc:source> <doc:source>
<script> <script>
function InvoiceCntl() { function InvoiceCntl($scope) {
this.qty = 1; $scope.qty = 1;
this.cost = 19.95; $scope.cost = 19.95;
} }
</script> </script>
<div ng:controller="InvoiceCntl"> <div ng:controller="InvoiceCntl">

View file

@ -34,8 +34,8 @@ text upper-case and assigns color.
} }
}); });
function Ctrl() { function Ctrl($scope) {
this.greeting = 'hello'; $scope.greeting = 'hello';
} }
</script> </script>

View file

@ -1,9 +1,8 @@
DocsController.$inject = ['$location', '$window', '$cookies', '$filter']; DocsController.$inject = ['$scope', '$location', '$window', '$cookies', '$filter'];
function DocsController($location, $window, $cookies, $filter) { function DocsController(scope, $location, $window, $cookies, $filter) {
window.$root = this.$root; window.$root = scope.$root;
var scope = this, var OFFLINE_COOKIE_NAME = 'ng-offline',
OFFLINE_COOKIE_NAME = 'ng-offline',
DOCS_PATH = /^\/(api)|(guide)|(cookbook)|(misc)|(tutorial)/, DOCS_PATH = /^\/(api)|(guide)|(cookbook)|(misc)|(tutorial)/,
INDEX_PATH = /^(\/|\/index[^\.]*.html)$/, INDEX_PATH = /^(\/|\/index[^\.]*.html)$/,
filter = $filter('filter'); filter = $filter('filter');
@ -160,6 +159,6 @@ angular.module('ngdocs', [], function($locationProvider, $filterProvider) {
return text && text.replace(/^angular\.module\.([^\.]+)(\.(.*))?$/, function(_, module, _0, name){ return text && text.replace(/^angular\.module\.([^\.]+)(\.(.*))?$/, function(_, module, _0, name){
return 'Module ' + module + (name ? ' - ' + name : ''); return 'Module ' + module + (name ? ' - ' + name : '');
}); });
} };
}); });
}); });

View file

@ -26,26 +26,26 @@ var LOGS = 'logs';
/** /**
* The controller for the personal log app. * The controller for the personal log app.
*/ */
function LogCtrl($cookieStore) { function LogCtrl($cookieStore, $scope) {
var self = this,
logs = self.logs = $cookieStore.get(LOGS) || []; //main model var logs = $scope.logs = $cookieStore.get(LOGS) || []; //main model
/** /**
* Adds newMsg to the logs array as a log, persists it and clears newMsg. * Adds newMsg to the logs array as a log, persists it and clears newMsg.
* @param {string} msg Message to add (message is passed as parameter to make testing easier). * @param {string} msg Message to add (message is passed as parameter to make testing easier).
*/ */
this.addLog = function(msg) { $scope.addLog = function(msg) {
var newMsg = msg || self.newMsg; var newMsg = msg || $scope.newMsg;
if (!newMsg) return; if (!newMsg) return;
var log = { var log = {
at: new Date().getTime(), at: new Date().getTime(),
msg: newMsg msg: newMsg
} };
logs.push(log); logs.push(log);
$cookieStore.put(LOGS, logs); $cookieStore.put(LOGS, logs);
self.newMsg = ''; $scope.newMsg = '';
}; };
@ -53,7 +53,7 @@ function LogCtrl($cookieStore) {
* Persistently removes a log from logs. * Persistently removes a log from logs.
* @param {object} log The log to remove. * @param {object} log The log to remove.
*/ */
this.rmLog = function(log) { $scope.rmLog = function(log) {
for ( var i = 0; i < logs.length; i++) { for ( var i = 0; i < logs.length; i++) {
if (log === logs[i]) { if (log === logs[i]) {
logs.splice(i, 1); logs.splice(i, 1);
@ -68,14 +68,14 @@ function LogCtrl($cookieStore) {
/** /**
* Persistently removes all logs. * Persistently removes all logs.
*/ */
this.rmLogs = function() { $scope.rmLogs = function() {
logs.splice(0, logs.length); logs.splice(0, logs.length);
$cookieStore.remove(LOGS); $cookieStore.remove(LOGS);
}; };
} }
//inject //inject
LogCtrl.$inject = ['$cookieStore']; LogCtrl.$inject = ['$cookieStore', '$scope'];
//export //export
example.personalLog.LogCtrl = LogCtrl; example.personalLog.LogCtrl = LogCtrl;

View file

@ -1,63 +1,58 @@
describe('example.personalLog.LogCtrl', function() { describe('example.personalLog.LogCtrl', function() {
var logCtrl; var logScope;
function createNotesCtrl() {
var injector = angular.injector(['ng', 'ngMock']);
var scope = injector.get('$rootScope');
scope.$cookies = injector.get('$cookies');
return scope.$new(example.personalLog.LogCtrl);
}
beforeEach(function() { beforeEach(function() {
logCtrl = createNotesCtrl(); var injector = angular.injector(['ng', 'ngMock']);
logScope = injector.get('$rootScope');
logScope.$cookies = injector.get('$cookies');
injector.instantiate(example.personalLog.LogCtrl, {$scope: logScope});
}); });
it('should initialize notes with an empty array', function() { it('should initialize notes with an empty array', function() {
expect(logCtrl.logs).toEqual([]); expect(logScope.logs).toEqual([]);
}); });
describe('addLog', function() { describe('addLog', function() {
beforeEach(function() { beforeEach(function() {
expect(logCtrl.logs).toEqual([]); expect(logScope.logs).toEqual([]);
}); });
it('should add newMsg to logs as a log entry', function() { it('should add newMsg to logs as a log entry', function() {
logCtrl.newMsg = 'first log message'; logScope.newMsg = 'first log message';
logCtrl.addLog(); logScope.addLog();
expect(logCtrl.logs.length).toBe(1); expect(logScope.logs.length).toBe(1);
expect(logCtrl.logs[0].msg).toBe('first log message'); expect(logScope.logs[0].msg).toBe('first log message');
//one more msg, this time passed in as param //one more msg, this time passed in as param
logCtrl.addLog('second log message'); logScope.addLog('second log message');
expect(logCtrl.logs.length).toBe(2); expect(logScope.logs.length).toBe(2);
expect(logCtrl.logs[0].msg).toBe('first log message'); expect(logScope.logs[0].msg).toBe('first log message');
expect(logCtrl.logs[1].msg).toBe('second log message'); expect(logScope.logs[1].msg).toBe('second log message');
}); });
it('should clear newMsg when log entry is persisted', function() { it('should clear newMsg when log entry is persisted', function() {
logCtrl.addLog('first log message'); logScope.addLog('first log message');
expect(logCtrl.newMsg).toBe(''); expect(logScope.newMsg).toBe('');
}); });
it('should store logs in the logs cookie', function() { it('should store logs in the logs cookie', function() {
expect(logCtrl.$cookies.logs).not.toBeDefined(); expect(logScope.$cookies.logs).not.toBeDefined();
logCtrl.addLog('first log message'); logScope.addLog('first log message');
expect(logCtrl.$cookies.logs).toBeTruthy(); expect(logScope.$cookies.logs).toBeTruthy();
}); });
it('should do nothing if newMsg is empty', function() { it('should do nothing if newMsg is empty', function() {
logCtrl.addLog(''); logScope.addLog('');
expect(logCtrl.logs.length).toBe(0); expect(logScope.logs.length).toBe(0);
}); });
}); });
@ -65,35 +60,35 @@ describe('example.personalLog.LogCtrl', function() {
describe('rmLog', function() { describe('rmLog', function() {
beforeEach(function() { beforeEach(function() {
logCtrl.addLog('message1'); logScope.addLog('message1');
logCtrl.addLog('message2'); logScope.addLog('message2');
logCtrl.addLog('message3'); logScope.addLog('message3');
logCtrl.addLog('message4'); logScope.addLog('message4');
expect(logCtrl.logs.length).toBe(4); expect(logScope.logs.length).toBe(4);
}); });
it('should delete a message identified by index', function() { it('should delete a message identified by index', function() {
logCtrl.rmLog(logCtrl.logs[1]); logScope.rmLog(logScope.logs[1]);
expect(logCtrl.logs.length).toBe(3); expect(logScope.logs.length).toBe(3);
logCtrl.rmLog(logCtrl.logs[2]); logScope.rmLog(logScope.logs[2]);
expect(logCtrl.logs.length).toBe(2); expect(logScope.logs.length).toBe(2);
expect(logCtrl.logs[0].msg).toBe('message1'); expect(logScope.logs[0].msg).toBe('message1');
expect(logCtrl.logs[1].msg).toBe('message3'); expect(logScope.logs[1].msg).toBe('message3');
}); });
it('should update cookies when a log is deleted', function() { it('should update cookies when a log is deleted', function() {
expect(logCtrl.$cookies.logs).toMatch(/\[\{.*?\}(,\{.*?\}){3}\]/); expect(logScope.$cookies.logs).toMatch(/\[\{.*?\}(,\{.*?\}){3}\]/);
logCtrl.rmLog(logCtrl.logs[1]); logScope.rmLog(logScope.logs[1]);
expect(logCtrl.$cookies.logs).toMatch(/\[\{.*?\}(,\{.*?\}){2}\]/); expect(logScope.$cookies.logs).toMatch(/\[\{.*?\}(,\{.*?\}){2}\]/);
logCtrl.rmLog(logCtrl.logs[0]); logScope.rmLog(logScope.logs[0]);
logCtrl.rmLog(logCtrl.logs[0]); logScope.rmLog(logScope.logs[0]);
logCtrl.rmLog(logCtrl.logs[0]); logScope.rmLog(logScope.logs[0]);
expect(logCtrl.$cookies.logs).toMatch(/\[\]/); expect(logScope.$cookies.logs).toMatch(/\[\]/);
}); });
}); });
@ -101,24 +96,24 @@ describe('example.personalLog.LogCtrl', function() {
describe('rmLogs', function() { describe('rmLogs', function() {
beforeEach(function() { beforeEach(function() {
logCtrl.addLog('message1'); logScope.addLog('message1');
logCtrl.addLog('message2'); logScope.addLog('message2');
logCtrl.addLog('message3'); logScope.addLog('message3');
logCtrl.addLog('message4'); logScope.addLog('message4');
expect(logCtrl.logs.length).toBe(4); expect(logScope.logs.length).toBe(4);
}); });
it('should remove all logs', function() { it('should remove all logs', function() {
logCtrl.rmLogs(); logScope.rmLogs();
expect(logCtrl.logs).toEqual([]); expect(logScope.logs).toEqual([]);
}); });
it('should remove logs cookie', function() { it('should remove logs cookie', function() {
expect(logCtrl.$cookies.logs).toBeTruthy(); expect(logScope.$cookies.logs).toBeTruthy();
logCtrl.rmLogs(); logScope.rmLogs();
expect(logCtrl.$cookies.logs).not.toBeDefined(); expect(logScope.$cookies.logs).not.toBeDefined();
}); });
}); });
}); });

View file

@ -97,28 +97,30 @@ angularDirective("ng:init", function(expression){
<doc:example> <doc:example>
<doc:source> <doc:source>
<script type="text/javascript"> <script type="text/javascript">
function SettingsController() { function SettingsController($scope) {
this.name = "John Smith"; $scope.name = "John Smith";
this.contacts = [ $scope.contacts = [
{type:'phone', value:'408 555 1212'}, {type:'phone', value:'408 555 1212'},
{type:'email', value:'john.smith@example.org'} ]; {type:'email', value:'john.smith@example.org'} ];
}
SettingsController.prototype = { $scope.greet = function() {
greet: function() {
alert(this.name); alert(this.name);
}, };
addContact: function() {
$scope.addContact = function() {
this.contacts.push({type:'email', value:'yourname@example.org'}); this.contacts.push({type:'email', value:'yourname@example.org'});
}, };
removeContact: function(contactToRemove) {
$scope.removeContact = function(contactToRemove) {
var index = this.contacts.indexOf(contactToRemove); var index = this.contacts.indexOf(contactToRemove);
this.contacts.splice(index, 1); this.contacts.splice(index, 1);
}, };
clearContact: function(contact) {
$scope.clearContact = function(contact) {
contact.type = 'phone'; contact.type = 'phone';
contact.value = ''; contact.value = '';
} };
}; }
</script> </script>
<div ng:controller="SettingsController"> <div ng:controller="SettingsController">
Name: <input type="text" ng:model="name"/> Name: <input type="text" ng:model="name"/>
@ -156,16 +158,15 @@ angularDirective("ng:init", function(expression){
</doc:scenario> </doc:scenario>
</doc:example> </doc:example>
*/ */
angularDirective("ng:controller", function(expression){ angularDirective("ng:controller", function(expression) {
this.scope(function(scope){ this.scope(true);
var Controller = return ['$injector', '$window', function($injector, $window) {
getter(scope, expression, true) || var scope = this,
getter(window, expression, true); Controller = getter(scope, expression, true) || getter($window, expression, true);
assertArgFn(Controller, expression); assertArgFn(Controller, expression);
inferInjectionArgs(Controller); $injector.instantiate(Controller, {$scope: scope});
return Controller; }];
});
return noop;
}); });
/** /**
@ -189,8 +190,8 @@ angularDirective("ng:controller", function(expression){
<doc:example> <doc:example>
<doc:source> <doc:source>
<script> <script>
function Ctrl() { function Ctrl($scope) {
this.name = 'Whirled'; $scope.name = 'Whirled';
} }
</script> </script>
<div ng:controller="Ctrl"> <div ng:controller="Ctrl">
@ -277,9 +278,9 @@ angularDirective("ng:bind", function(expression, element){
<doc:example> <doc:example>
<doc:source> <doc:source>
<script> <script>
function Ctrl() { function Ctrl($scope) {
this.salutation = 'Hello'; $scope.salutation = 'Hello';
this.name = 'World'; $scope.name = 'World';
} }
</script> </script>
<div ng:controller="Ctrl"> <div ng:controller="Ctrl">
@ -363,8 +364,8 @@ angularDirective("ng:bind-template", function(expression, element){
<doc:example> <doc:example>
<doc:source> <doc:source>
<script> <script>
function Ctrl() { function Ctrl($scope) {
this.query = 'AngularJS'; $scope.query = 'AngularJS';
} }
</script> </script>
<div ng:controller="Ctrl"> <div ng:controller="Ctrl">
@ -470,10 +471,10 @@ angularDirective("ng:click", function(expression, element){
<doc:example> <doc:example>
<doc:source> <doc:source>
<script> <script>
function Ctrl() { function Ctrl($scope) {
this.list = []; $scope.list = [];
this.text = 'hello'; $scope.text = 'hello';
this.submit = function() { $scope.submit = function() {
if (this.text) { if (this.text) {
this.list.push(this.text); this.list.push(this.text);
this.text = ''; this.text = '';

View file

@ -152,7 +152,16 @@ angular.scenario.Runner.prototype.afterEach = function(body) {
* @param {Object} scope parent scope * @param {Object} scope parent scope
*/ */
angular.scenario.Runner.prototype.createSpecRunner_ = function(scope) { angular.scenario.Runner.prototype.createSpecRunner_ = function(scope) {
return scope.$new(angular.scenario.SpecRunner); var child = scope.$new();
var Cls = angular.scenario.SpecRunner;
// Export all the methods to child scope manually as now we don't mess controllers with scopes
// TODO(vojta): refactor scenario runner so that these objects are not tightly coupled as current
for (var name in Cls.prototype)
child[name] = angular.bind(child, Cls.prototype[name]);
Cls.call(child);
return child;
}; };
/** /**

View file

@ -22,7 +22,7 @@ function $CompileProvider(){
var childScope = scope, var childScope = scope,
locals = {$element: element}; locals = {$element: element};
if (this.newScope) { if (this.newScope) {
childScope = isFunction(this.newScope) ? scope.$new(this.newScope(scope)) : scope.$new(); childScope = scope.$new();
element.data($$scope, childScope); element.data($$scope, childScope);
} }
forEach(this.linkFns, function(fn) { forEach(this.linkFns, function(fn) {

View file

@ -18,8 +18,8 @@
<doc:example> <doc:example>
<doc:source> <doc:source>
<script> <script>
function Ctrl() { function Ctrl($scope) {
this.amount = 1234.56; $scope.amount = 1234.56;
} }
</script> </script>
<div ng:controller="Ctrl"> <div ng:controller="Ctrl">
@ -69,8 +69,8 @@ function currencyFilter($locale) {
<doc:example> <doc:example>
<doc:source> <doc:source>
<script> <script>
function Ctrl() { function Ctrl($scope) {
this.val = 1234.56789; $scope.val = 1234.56789;
} }
</script> </script>
<div ng:controller="Ctrl"> <div ng:controller="Ctrl">
@ -448,8 +448,8 @@ var uppercaseFilter = valueFn(uppercase);
<doc:example> <doc:example>
<doc:source> <doc:source>
<script> <script>
function Ctrl() { function Ctrl($scope) {
this.snippet = $scope.snippet =
'<p style="color:blue">an html\n' + '<p style="color:blue">an html\n' +
'<em onmouseover="this.textContent=\'PWN3D!\'">click here</em>\n' + '<em onmouseover="this.textContent=\'PWN3D!\'">click here</em>\n' +
'snippet</p>'; 'snippet</p>';
@ -538,8 +538,8 @@ function htmlFilter() {
<doc:example> <doc:example>
<doc:source> <doc:source>
<script> <script>
function Ctrl() { function Ctrl($scope) {
this.snippet = $scope.snippet =
'Pretty text with some links:\n'+ 'Pretty text with some links:\n'+
'http://angularjs.org/,\n'+ 'http://angularjs.org/,\n'+
'mailto:us@somewhere.org,\n'+ 'mailto:us@somewhere.org,\n'+

View file

@ -25,9 +25,9 @@
<doc:example> <doc:example>
<doc:source> <doc:source>
<script> <script>
function Ctrl() { function Ctrl($scope) {
this.numbers = [1,2,3,4,5,6,7,8,9]; $scope.numbers = [1,2,3,4,5,6,7,8,9];
this.limit = 3; $scope.limit = 3;
} }
</script> </script>
<div ng:controller="Ctrl"> <div ng:controller="Ctrl">

View file

@ -32,14 +32,14 @@
<doc:example> <doc:example>
<doc:source> <doc:source>
<script> <script>
function Ctrl() { function Ctrl($scope) {
this.friends = $scope.friends =
[{name:'John', phone:'555-1212', age:10}, [{name:'John', phone:'555-1212', age:10},
{name:'Mary', phone:'555-9876', age:19}, {name:'Mary', phone:'555-9876', age:19},
{name:'Mike', phone:'555-4321', age:21}, {name:'Mike', phone:'555-4321', age:21},
{name:'Adam', phone:'555-5678', age:35}, {name:'Adam', phone:'555-5678', age:35},
{name:'Julie', phone:'555-8765', age:29}] {name:'Julie', phone:'555-8765', age:29}]
this.predicate = '-age'; $scope.predicate = '-age';
} }
</script> </script>
<div ng:controller="Ctrl"> <div ng:controller="Ctrl">

View file

@ -25,15 +25,13 @@
<doc:example> <doc:example>
<doc:source> <doc:source>
<script> <script>
function EditorCntl() { function EditorCntl($scope) {
this.html = '<b>Hello</b> <i>World</i>!'; $scope.html = '<b>Hello</b> <i>World</i>!';
} }
HTMLEditorWidget.$inject = ['$element', 'htmlFilter']; HTMLEditorWidget.$inject = ['$element', '$scope', 'htmlFilter'];
function HTMLEditorWidget(element, htmlFilter) { function HTMLEditorWidget(element, scope, htmlFilter) {
var self = this; scope.$parseModel = function() {
this.$parseModel = function() {
// need to protect for script injection // need to protect for script injection
try { try {
this.$viewValue = htmlFilter(this.$modelValue || '').get(); this.$viewValue = htmlFilter(this.$modelValue || '').get();
@ -47,13 +45,13 @@
} }
} }
this.$render = function() { scope.$render = function() {
element.html(this.$viewValue); element.html(this.$viewValue);
} }
element.bind('keyup', function() { element.bind('keyup', function() {
self.$apply(function() { scope.$apply(function() {
self.$emit('$viewChange', element.html()); scope.$emit('$viewChange', element.html());
}); });
}); });
} }
@ -104,7 +102,8 @@
function $FormFactoryProvider() { function $FormFactoryProvider() {
var $parse; var $parse;
this.$get = ['$rootScope', '$parse', function($rootScope, $parse_) { this.$get = ['$rootScope', '$parse', '$injector',
function($rootScope, $parse_, $injector) {
$parse = $parse_; $parse = $parse_;
/** /**
* @ngdoc proprety * @ngdoc proprety
@ -136,7 +135,9 @@ function $FormFactoryProvider() {
return formFactory; return formFactory;
function formFactory(parent) { function formFactory(parent) {
return (parent || formFactory.rootForm).$new(FormController); var scope = (parent || formFactory.rootForm).$new();
$injector.instantiate(FormController, {$scope: scope});
return scope;
} }
}]; }];
@ -230,8 +231,11 @@ function $FormFactoryProvider() {
* @param {*} viewValue The new value for the view which will be assigned to `widget.$viewValue`. * @param {*} viewValue The new value for the view which will be assigned to `widget.$viewValue`.
*/ */
function FormController() { FormController.$inject = ['$scope', '$injector'];
var form = this, function FormController($scope, $injector) {
this.$injector = $injector;
var form = this.form = $scope,
$error = form.$error = {}; $error = form.$error = {};
form.$on('$destroy', function(event){ form.$on('$destroy', function(event){
@ -257,6 +261,7 @@ function $FormFactoryProvider() {
}); });
propertiesUpdate(form); propertiesUpdate(form);
form.$createWidget = bind(this, this.$createWidget);
function removeWidget(queue, errorKey, widget) { function removeWidget(queue, errorKey, widget) {
if (queue) { if (queue) {
@ -354,17 +359,19 @@ function $FormFactoryProvider() {
* @returns {Widget} Instance of a widget scope. * @returns {Widget} Instance of a widget scope.
*/ */
FormController.prototype.$createWidget = function(params) { FormController.prototype.$createWidget = function(params) {
var form = this, var form = this.form,
modelScope = params.scope, modelScope = params.scope,
onChange = params.onChange, onChange = params.onChange,
alias = params.alias, alias = params.alias,
scopeGet = $parse(params.model), scopeGet = $parse(params.model),
scopeSet = scopeGet.assign, scopeSet = scopeGet.assign,
widget = this.$new(params.controller, params.controllerArgs); widget = form.$new();
this.$injector.instantiate(params.controller, extend({$scope: widget}, params.controllerArgs));
if (!scopeSet) { if (!scopeSet) {
throw Error("Expression '" + params.model + "' is not assignable!"); throw Error("Expression '" + params.model + "' is not assignable!");
}; }
widget.$error = {}; widget.$error = {};
// Set the state to something we know will change to get the process going. // Set the state to something we know will change to get the process going.

View file

@ -395,29 +395,28 @@ function $HttpProvider() {
<doc:example> <doc:example>
<doc:source jsfiddle="false"> <doc:source jsfiddle="false">
<script> <script>
function FetchCtrl($http) { function FetchCtrl($scope, $http) {
var self = this; $scope.method = 'GET';
this.method = 'GET'; $scope.url = 'examples/http-hello.html';
this.url = 'examples/http-hello.html';
this.fetch = function() { $scope.fetch = function() {
self.code = null; $scope.code = null;
self.response = null; $scope.response = null;
$http({method: self.method, url: self.url}). $http({method: $scope.method, url: $scope.url}).
success(function(data, status) { success(function(data, status) {
self.status = status; $scope.status = status;
self.data = data; $scope.data = data;
}). }).
error(function(data, status) { error(function(data, status) {
self.data = data || "Request failed"; $scope.data = data || "Request failed";
self.status = status; $scope.status = status;
}); });
}; };
this.updateModel = function(method, url) { $scope.updateModel = function(method, url) {
self.method = method; $scope.method = method;
self.url = url; $scope.url = url;
}; };
} }
</script> </script>

View file

@ -63,8 +63,8 @@
</doc:example> </doc:example>
*/ */
function $RouteProvider(){ function $RouteProvider(){
this.$get = ['$rootScope', '$location', '$routeParams', this.$get = ['$rootScope', '$location', '$routeParams', '$injector',
function( $rootScope, $location, $routeParams) { function( $rootScope, $location, $routeParams, $injector) {
/** /**
* @ngdoc event * @ngdoc event
* @name angular.module.ng.$route#$beforeRouteChange * @name angular.module.ng.$route#$beforeRouteChange
@ -278,8 +278,10 @@ function $RouteProvider(){
} }
} else { } else {
copy(next.params, $routeParams); copy(next.params, $routeParams);
(Controller = next.controller) && inferInjectionArgs(Controller); next.scope = parentScope.$new();
next.scope = parentScope.$new(Controller); if (next.controller) {
$injector.instantiate(next.controller, {$scope: next.scope});
}
} }
} }
$rootScope.$broadcast('$afterRouteChange', next, last); $rootScope.$broadcast('$afterRouteChange', next, last);

View file

@ -126,8 +126,9 @@ function $RootScopeProvider(){
* @function * @function
* *
* @description * @description
* Creates a new child {@link angular.module.ng.$rootScope.Scope scope}. The new scope can optionally behave as a * Creates a new child {@link angular.module.ng.$rootScope.Scope scope}.
* controller. The parent scope will propagate the {@link angular.module.ng.$rootScope.Scope#$digest $digest()} and *
* The parent scope will propagate the {@link angular.module.ng.$rootScope.Scope#$digest $digest()} and
* {@link angular.module.ng.$rootScope.Scope#$digest $digest()} events. The scope can be removed from the scope * {@link angular.module.ng.$rootScope.Scope#$digest $digest()} events. The scope can be removed from the scope
* hierarchy using {@link angular.module.ng.$rootScope.Scope#$destroy $destroy()}. * hierarchy using {@link angular.module.ng.$rootScope.Scope#$destroy $destroy()}.
* *
@ -135,13 +136,10 @@ function $RootScopeProvider(){
* the scope and its child scopes to be permanently detached from the parent and thus stop * the scope and its child scopes to be permanently detached from the parent and thus stop
* participating in model change detection and listener notification by invoking. * participating in model change detection and listener notification by invoking.
* *
* @param {function()=} Class Constructor function which the scope should be applied to the scope.
* @param {...*} curryArguments Any additional arguments which are curried into the constructor.
* See {@link guide/dev_guide.di dependency injection}.
* @returns {Object} The newly created child scope. * @returns {Object} The newly created child scope.
* *
*/ */
$new: function(Class, curryArguments) { $new: function() {
var Child = function() {}; // should be anonymous; This is so that when the minifier munges var Child = function() {}; // should be anonymous; This is so that when the minifier munges
// the name it does not become random set of chars. These will then show up as class // the name it does not become random set of chars. These will then show up as class
// name in the debugger. // name in the debugger.
@ -161,15 +159,6 @@ function $RootScopeProvider(){
} else { } else {
this.$$childHead = this.$$childTail = child; this.$$childHead = this.$$childTail = child;
} }
// short circuit if we have no class
if (Class) {
// can't use forEach, we need speed!
var ClassPrototype = Class.prototype;
for(var key in ClassPrototype) {
child[key] = bind(child, ClassPrototype[key]);
}
$injector.invoke(Class, child, curryArguments);
}
return child; return child;
}, },

View file

@ -52,8 +52,8 @@
<doc:example> <doc:example>
<doc:source> <doc:source>
<script> <script>
function Ctrl() { function Ctrl($scope) {
this.text = 'guest'; $scope.text = 'guest';
} }
</script> </script>
<div ng:controller="Ctrl"> <div ng:controller="Ctrl">

View file

@ -31,9 +31,9 @@ var INTEGER_REGEXP = /^\s*(\-|\+)?\d+\s*$/;
<doc:example> <doc:example>
<doc:source> <doc:source>
<script> <script>
function Ctrl() { function Ctrl($scope) {
this.text = 'guest'; $scope.text = 'guest';
this.word = /^\w*$/; $scope.word = /^\w*$/;
} }
</script> </script>
<div ng:controller="Ctrl"> <div ng:controller="Ctrl">
@ -96,8 +96,8 @@ var INTEGER_REGEXP = /^\s*(\-|\+)?\d+\s*$/;
<doc:example> <doc:example>
<doc:source> <doc:source>
<script> <script>
function Ctrl() { function Ctrl($scope) {
this.text = 'me@example.com'; $scope.text = 'me@example.com';
} }
</script> </script>
<div ng:controller="Ctrl"> <div ng:controller="Ctrl">
@ -136,9 +136,8 @@ var INTEGER_REGEXP = /^\s*(\-|\+)?\d+\s*$/;
</doc:scenario> </doc:scenario>
</doc:example> </doc:example>
*/ */
angularInputType('email', function() { angularInputType('email', function(element, widget) {
var widget = this; widget.$on('$validate', function(event) {
this.$on('$validate', function(event){
var value = widget.$viewValue; var value = widget.$viewValue;
widget.$emit(!value || value.match(EMAIL_REGEXP) ? "$valid" : "$invalid", "EMAIL"); widget.$emit(!value || value.match(EMAIL_REGEXP) ? "$valid" : "$invalid", "EMAIL");
}); });
@ -170,8 +169,8 @@ angularInputType('email', function() {
<doc:example> <doc:example>
<doc:source> <doc:source>
<script> <script>
function Ctrl() { function Ctrl($scope) {
this.text = 'http://google.com'; $scope.text = 'http://google.com';
} }
</script> </script>
<div ng:controller="Ctrl"> <div ng:controller="Ctrl">
@ -210,9 +209,8 @@ angularInputType('email', function() {
</doc:scenario> </doc:scenario>
</doc:example> </doc:example>
*/ */
angularInputType('url', function() { angularInputType('url', function(element, widget) {
var widget = this; widget.$on('$validate', function(event) {
this.$on('$validate', function(event){
var value = widget.$viewValue; var value = widget.$viewValue;
widget.$emit(!value || value.match(URL_REGEXP) ? "$valid" : "$invalid", "URL"); widget.$emit(!value || value.match(URL_REGEXP) ? "$valid" : "$invalid", "URL");
}); });
@ -239,8 +237,8 @@ angularInputType('url', function() {
<doc:example> <doc:example>
<doc:source> <doc:source>
<script> <script>
function Ctrl() { function Ctrl($scope) {
this.names = ['igor', 'misko', 'vojta']; $scope.names = ['igor', 'misko', 'vojta'];
} }
</script> </script>
<div ng:controller="Ctrl"> <div ng:controller="Ctrl">
@ -270,7 +268,7 @@ angularInputType('url', function() {
</doc:scenario> </doc:scenario>
</doc:example> </doc:example>
*/ */
angularInputType('list', function() { angularInputType('list', function(element, widget) {
function parse(viewValue) { function parse(viewValue) {
var list = []; var list = [];
forEach(viewValue.split(/\s*,\s*/), function(value){ forEach(viewValue.split(/\s*,\s*/), function(value){
@ -278,14 +276,14 @@ angularInputType('list', function() {
}); });
return list; return list;
} }
this.$parseView = function() { widget.$parseView = function() {
isString(this.$viewValue) && (this.$modelValue = parse(this.$viewValue)); isString(widget.$viewValue) && (widget.$modelValue = parse(widget.$viewValue));
}; };
this.$parseModel = function() { widget.$parseModel = function() {
var modelValue = this.$modelValue; var modelValue = widget.$modelValue;
if (isArray(modelValue) if (isArray(modelValue)
&& (!isString(this.$viewValue) || !equals(parse(this.$viewValue), modelValue))) { && (!isString(widget.$viewValue) || !equals(parse(widget.$viewValue), modelValue))) {
this.$viewValue = modelValue.join(', '); widget.$viewValue = modelValue.join(', ');
} }
}; };
}); });
@ -318,8 +316,8 @@ angularInputType('list', function() {
<doc:example> <doc:example>
<doc:source> <doc:source>
<script> <script>
function Ctrl() { function Ctrl($scope) {
this.value = 12; $scope.value = 12;
} }
</script> </script>
<div ng:controller="Ctrl"> <div ng:controller="Ctrl">
@ -388,8 +386,8 @@ angularInputType('number', numericRegexpInputType(NUMBER_REGEXP, 'NUMBER'));
<doc:example> <doc:example>
<doc:source> <doc:source>
<script> <script>
function Ctrl() { function Ctrl($scope) {
this.value = 12; $scope.value = 12;
} }
</script> </script>
<div ng:controller="Ctrl"> <div ng:controller="Ctrl">
@ -449,9 +447,9 @@ angularInputType('integer', numericRegexpInputType(INTEGER_REGEXP, 'INTEGER'));
<doc:example> <doc:example>
<doc:source> <doc:source>
<script> <script>
function Ctrl() { function Ctrl($scope) {
this.value1 = true; $scope.value1 = true;
this.value2 = 'YES' $scope.value2 = 'YES'
} }
</script> </script>
<div ng:controller="Ctrl"> <div ng:controller="Ctrl">
@ -477,9 +475,8 @@ angularInputType('integer', numericRegexpInputType(INTEGER_REGEXP, 'INTEGER'));
</doc:scenario> </doc:scenario>
</doc:example> </doc:example>
*/ */
angularInputType('checkbox', function(inputElement) { angularInputType('checkbox', function(inputElement, widget) {
var widget = this, var trueValue = inputElement.attr('ng:true-value'),
trueValue = inputElement.attr('ng:true-value'),
falseValue = inputElement.attr('ng:false-value'); falseValue = inputElement.attr('ng:false-value');
if (!isString(trueValue)) trueValue = true; if (!isString(trueValue)) trueValue = true;
@ -496,7 +493,7 @@ angularInputType('checkbox', function(inputElement) {
}; };
widget.$parseModel = function() { widget.$parseModel = function() {
widget.$viewValue = this.$modelValue === trueValue; widget.$viewValue = widget.$modelValue === trueValue;
}; };
widget.$parseView = function() { widget.$parseView = function() {
@ -522,8 +519,8 @@ angularInputType('checkbox', function(inputElement) {
<doc:example> <doc:example>
<doc:source> <doc:source>
<script> <script>
function Ctrl() { function Ctrl($scope) {
this.color = 'blue'; $scope.color = 'blue';
} }
</script> </script>
<div ng:controller="Ctrl"> <div ng:controller="Ctrl">
@ -545,9 +542,7 @@ angularInputType('checkbox', function(inputElement) {
</doc:scenario> </doc:scenario>
</doc:example> </doc:example>
*/ */
angularInputType('radio', function(inputElement) { angularInputType('radio', function(inputElement, widget) {
var widget = this;
//correct the name //correct the name
inputElement.attr('name', widget.$id + '@' + inputElement.attr('name')); inputElement.attr('name', widget.$id + '@' + inputElement.attr('name'));
inputElement.bind('click', function() { inputElement.bind('click', function() {
@ -569,9 +564,8 @@ angularInputType('radio', function(inputElement) {
function numericRegexpInputType(regexp, error) { function numericRegexpInputType(regexp, error) {
return ['$element', function(inputElement) { return function(inputElement, widget) {
var widget = this, var min = 1 * (inputElement.attr('min') || Number.MIN_VALUE),
min = 1 * (inputElement.attr('min') || Number.MIN_VALUE),
max = 1 * (inputElement.attr('max') || Number.MAX_VALUE); max = 1 * (inputElement.attr('max') || Number.MAX_VALUE);
widget.$on('$validate', function(event){ widget.$on('$validate', function(event){
@ -598,7 +592,7 @@ function numericRegexpInputType(regexp, error) {
? '' + widget.$modelValue ? '' + widget.$modelValue
: ''; : '';
}; };
}]; };
} }
@ -640,8 +634,8 @@ var HTML5_INPUTS_TYPES = makeMap(
<doc:example> <doc:example>
<doc:source> <doc:source>
<script> <script>
function Ctrl() { function Ctrl($scope) {
this.user = {name: 'guest', last: 'visitor'}; $scope.user = {name: 'guest', last: 'visitor'};
} }
</script> </script>
<div ng:controller="Ctrl"> <div ng:controller="Ctrl">
@ -713,7 +707,8 @@ angularWidget('input', function(inputElement){
this.descend(true); this.descend(true);
var modelExp = inputElement.attr('ng:model'); var modelExp = inputElement.attr('ng:model');
return modelExp && return modelExp &&
['$defer', '$formFactory', '$element', function($defer, $formFactory, inputElement){ ['$defer', '$formFactory', '$element',
function($defer, $formFactory, inputElement) {
var form = $formFactory.forElement(inputElement), var form = $formFactory.forElement(inputElement),
// We have to use .getAttribute, since jQuery tries to be smart and use the // We have to use .getAttribute, since jQuery tries to be smart and use the
// type property. Trouble is some browser change unknown to text. // type property. Trouble is some browser change unknown to text.
@ -762,7 +757,7 @@ angularWidget('input', function(inputElement){
} }
//TODO(misko): setting $inject is a hack //TODO(misko): setting $inject is a hack
!TypeController.$inject && (TypeController.$inject = ['$element']); !TypeController.$inject && (TypeController.$inject = ['$element', '$scope']);
widget = form.$createWidget({ widget = form.$createWidget({
scope: modelScope, scope: modelScope,
model: modelExp, model: modelExp,
@ -866,7 +861,7 @@ angularWidget('textarea', angularWidget('input'));
function watchElementProperty(modelScope, widget, name, element) { function watchElementProperty(modelScope, widget, name, element) {
var bindAttr = fromJson(element.attr('ng:bind-attr') || '{}'), var bindAttr = fromJson(element.attr('ng:bind-attr') || '{}'),
match = /\s*{{(.*)}}\s*/.exec(bindAttr[name]), match = /\s*\{\{(.*)\}\}\s*/.exec(bindAttr[name]),
isBoolean = BOOLEAN_ATTR[name]; isBoolean = BOOLEAN_ATTR[name];
widget['$' + name] = isBoolean widget['$' + name] = isBoolean
? ( // some browsers return true some '' when required is set without value. ? ( // some browsers return true some '' when required is set without value.

View file

@ -65,15 +65,15 @@
<doc:example> <doc:example>
<doc:source> <doc:source>
<script> <script>
function MyCntrl() { function MyCntrl($scope) {
this.colors = [ $scope.colors = [
{name:'black', shade:'dark'}, {name:'black', shade:'dark'},
{name:'white', shade:'light'}, {name:'white', shade:'light'},
{name:'red', shade:'dark'}, {name:'red', shade:'dark'},
{name:'blue', shade:'dark'}, {name:'blue', shade:'dark'},
{name:'yellow', shade:'light'} {name:'yellow', shade:'light'}
]; ];
this.color = this.colors[2]; // red $scope.color = $scope.colors[2]; // red
} }
</script> </script>
<div ng:controller="MyCntrl"> <div ng:controller="MyCntrl">
@ -140,11 +140,11 @@ angularWidget('select', function(element){
optionsExp = selectElement.attr('ng:options'), optionsExp = selectElement.attr('ng:options'),
modelExp = selectElement.attr('ng:model'), modelExp = selectElement.attr('ng:model'),
widget = form.$createWidget({ widget = form.$createWidget({
scope: this, scope: modelScope,
model: modelExp, model: modelExp,
onChange: selectElement.attr('ng:change'), onChange: selectElement.attr('ng:change'),
alias: selectElement.attr('name'), alias: selectElement.attr('name'),
controller: optionsExp ? Options : (multiple ? Multiple : Single)}); controller: ['$scope', optionsExp ? Options : (multiple ? Multiple : Single)]});
selectElement.bind('$destroy', function() { widget.$destroy(); }); selectElement.bind('$destroy', function() { widget.$destroy(); });
@ -174,11 +174,9 @@ angularWidget('select', function(element){
//////////////////////////// ////////////////////////////
function Multiple() { function Multiple(widget) {
var widget = this; widget.$render = function() {
var items = new HashMap(widget.$viewValue);
this.$render = function() {
var items = new HashMap(this.$viewValue);
forEach(selectElement.children(), function(option){ forEach(selectElement.children(), function(option){
option.selected = isDefined(items.get(option.value)); option.selected = isDefined(items.get(option.value));
}); });
@ -198,9 +196,7 @@ angularWidget('select', function(element){
} }
function Single() { function Single(widget) {
var widget = this;
widget.$render = function() { widget.$render = function() {
selectElement.val(widget.$viewValue); selectElement.val(widget.$viewValue);
}; };
@ -214,9 +210,8 @@ angularWidget('select', function(element){
widget.$viewValue = selectElement.val(); widget.$viewValue = selectElement.val();
} }
function Options() { function Options(widget) {
var widget = this, var match;
match;
if (! (match = optionsExp.match(NG_OPTIONS_REGEXP))) { if (! (match = optionsExp.match(NG_OPTIONS_REGEXP))) {
throw Error( throw Error(
@ -224,8 +219,7 @@ angularWidget('select', function(element){
" but got '" + optionsExp + "'."); " but got '" + optionsExp + "'.");
} }
var widgetScope = this, var displayFn = $parse(match[2] || match[1]),
displayFn = $parse(match[2] || match[1]),
valueName = match[4] || match[6], valueName = match[4] || match[6],
keyName = match[5], keyName = match[5],
groupByFn = $parse(match[3] || ''), groupByFn = $parse(match[3] || ''),
@ -253,7 +247,7 @@ angularWidget('select', function(element){
selectElement.html(''); // clear contents selectElement.html(''); // clear contents
selectElement.bind('change', function() { selectElement.bind('change', function() {
widgetScope.$apply(function() { widget.$apply(function() {
var optionGroup, var optionGroup,
collection = valuesFn(modelScope) || [], collection = valuesFn(modelScope) || [],
key = selectElement.val(), key = selectElement.val(),
@ -288,13 +282,13 @@ angularWidget('select', function(element){
} }
} }
if (isDefined(value) && modelScope.$viewVal !== value) { if (isDefined(value) && modelScope.$viewVal !== value) {
widgetScope.$emit('$viewChange', value); widget.$emit('$viewChange', value);
} }
}); });
}); });
widgetScope.$watch(render); widget.$watch(render);
widgetScope.$render = render; widget.$render = render;
function render() { function render() {
var optionGroups = {'':[]}, // Temporary location for the option groups before we render them var optionGroups = {'':[]}, // Temporary location for the option groups before we render them

View file

@ -54,11 +54,11 @@
<doc:example> <doc:example>
<doc:source jsfiddle="false"> <doc:source jsfiddle="false">
<script> <script>
function Ctrl() { function Ctrl($scope) {
this.templates = $scope.templates =
[ { name: 'template1.html', url: 'examples/ng-include/template1.html'} [ { name: 'template1.html', url: 'examples/ng-include/template1.html'}
, { name: 'template2.html', url: 'examples/ng-include/template2.html'} ]; , { name: 'template2.html', url: 'examples/ng-include/template2.html'} ];
this.template = this.templates[0]; $scope.template = $scope.templates[0];
} }
</script> </script>
<div ng:controller="Ctrl"> <div ng:controller="Ctrl">
@ -171,9 +171,9 @@ angularWidget('ng:include', function(element){
<doc:example> <doc:example>
<doc:source> <doc:source>
<script> <script>
function Ctrl() { function Ctrl($scope) {
this.items = ['settings', 'home', 'other']; $scope.items = ['settings', 'home', 'other'];
this.selection = this.items[0]; $scope.selection = $scope.items[0];
} }
</script> </script>
<div ng:controller="Ctrl"> <div ng:controller="Ctrl">
@ -701,10 +701,10 @@ angularWidget('ng:view', function(element) {
<doc:example> <doc:example>
<doc:source> <doc:source>
<script> <script>
function Ctrl() { function Ctrl($scope) {
this.person1 = 'Igor'; $scope.person1 = 'Igor';
this.person2 = 'Misko'; $scope.person2 = 'Misko';
this.personCount = 1; $scope.personCount = 1;
} }
</script> </script>
<div ng:controller="Ctrl"> <div ng:controller="Ctrl">

View file

@ -460,60 +460,66 @@ describe("directive", function() {
}); });
describe('ng:controller', function() { describe('ng:controller', function() {
var element;
var temp; beforeEach(inject(function($window) {
$window.Greeter = function($scope) {
// private stuff (not exported to scope)
this.prefix = 'Hello ';
beforeEach(function() { // public stuff (exported to scope)
temp = window.temp = {}; var ctrl = this;
temp.Greeter = function() { $scope.name = 'Misko';
this.$root.greeter = this; $scope.greet = function(name) {
this.greeting = 'hello'; return ctrl.prefix + name + ctrl.suffix;
this.suffix = '!'; };
$scope.protoGreet = bind(this, this.protoGreet);
}; };
temp.Greeter.prototype = { $window.Greeter.prototype = {
greet: function(name) { suffix: '!',
return this.greeting + ' ' + name + this.suffix; protoGreet: function(name) {
return this.prefix + name + this.suffix;
} }
}; };
});
$window.Child = function($scope) {
$scope.name = 'Adam';
};
}));
afterEach(function() { afterEach(function() {
window.temp = undefined; dealoc(element);
}); });
it('should bind', inject(function($rootScope, $compile) {
var element = $compile('<div ng:controller="temp.Greeter"></div>')($rootScope);
expect($rootScope.greeter.greeting).toEqual('hello');
expect($rootScope.greeter.greet('misko')).toEqual('hello misko!');
}));
it('should support nested controllers', inject(function($rootScope, $compile) { it('should instantiate controller and bind methods', inject(function($compile, $rootScope) {
temp.ChildGreeter = function() { element = $compile('<div ng:controller="Greeter">{{greet(name)}}</div>')($rootScope);
this.greeting = 'hey';
this.$root.childGreeter = this;
};
temp.ChildGreeter.prototype = {
greet: function() {
return this.greeting + ' dude' + this.suffix;
}
};
var element = $compile('<div ng:controller="temp.Greeter"><div ng:controller="temp.ChildGreeter">{{greet("misko")}}</div></div>')($rootScope);
expect($rootScope.greeting).not.toBeDefined();
expect($rootScope.greeter.greeting).toEqual('hello');
expect($rootScope.greeter.greet('misko')).toEqual('hello misko!');
expect($rootScope.greeter.greeting).toEqual('hello');
expect($rootScope.childGreeter.greeting).toEqual('hey');
expect($rootScope.childGreeter.$parent.greeting).toEqual('hello');
$rootScope.$digest(); $rootScope.$digest();
expect(element.text()).toEqual('hey dude!'); expect(element.text()).toBe('Hello Misko!');
})); }));
it('should infer injection arguments', inject(function($rootScope, $compile, $http) {
temp.MyController = function($http) { it('should allow nested controllers', inject(function($compile, $rootScope) {
this.$root.someService = $http; element = $compile('<div ng:controller="Greeter"><div ng:controller="Child">{{greet(name)}}</div></div>')($rootScope);
$rootScope.$digest();
expect(element.text()).toBe('Hello Adam!');
dealoc(element);
element = $compile('<div ng:controller="Greeter"><div ng:controller="Child">{{protoGreet(name)}}</div></div>')($rootScope);
$rootScope.$digest();
expect(element.text()).toBe('Hello Adam!');
}));
it('should instantiate controller defined on scope', inject(function($compile, $rootScope) {
$rootScope.Greeter = function($scope) {
$scope.name = 'Vojta';
}; };
var element = $compile('<div ng:controller="temp.MyController"></div>')($rootScope);
expect($rootScope.someService).toBe($http); element = $compile('<div ng:controller="Greeter">{{name}}</div>')($rootScope);
$rootScope.$digest();
expect(element.text()).toBe('Vojta');
})); }));
}); });

View file

@ -43,9 +43,6 @@ describe('angular.scenario.Runner', function() {
location: {} location: {}
}; };
runner = new angular.scenario.Runner($window); runner = new angular.scenario.Runner($window);
runner.createSpecRunner_ = function(scope) {
return scope.$new(MockSpecRunner);
};
runner.on('SpecError', angular.mock.rethrow); runner.on('SpecError', angular.mock.rethrow);
runner.on('StepError', angular.mock.rethrow); runner.on('StepError', angular.mock.rethrow);
}); });

View file

@ -40,7 +40,13 @@ describe('angular.scenario.SpecRunner', function() {
}; };
$root.application = new ApplicationMock($window); $root.application = new ApplicationMock($window);
$root.$window = $window; $root.$window = $window;
runner = $root.$new(angular.scenario.SpecRunner); runner = $root.$new();
var Cls = angular.scenario.SpecRunner;
for (var name in Cls.prototype)
runner[name] = angular.bind(runner, Cls.prototype[name]);
Cls.call(runner);
})); }));
it('should bind futures to the spec', function() { it('should bind futures to the spec', function() {

View file

@ -13,23 +13,24 @@ describe('$formFactory', function() {
var scope; var scope;
var log; var log;
function WidgetCtrl($formFactory){ function WidgetCtrl($formFactory, $scope) {
this.$formFactory = $formFactory;
log += '<init>'; log += '<init>';
this.$render = function() { $scope.$render = function() {
log += '$render();'; log += '$render();';
}; };
this.$on('$validate', function(e){ $scope.$on('$validate', function(e){
log += '$validate();'; log += '$validate();';
}); });
this.$formFactory = $formFactory;
} }
WidgetCtrl.$inject = ['$formFactory']; WidgetCtrl.$inject = ['$formFactory', '$scope'];
WidgetCtrl.prototype = { WidgetCtrl.prototype = {
getFormFactory: function() { getFormFactory: function() {
return this.$formFactory; return this.$formFactory;
} }
}; };
beforeEach(inject(function($rootScope, $formFactory) { beforeEach(inject(function($rootScope, $formFactory) {
@ -70,11 +71,6 @@ describe('$formFactory', function() {
expect(widget.$modelValue).toEqual('xyz'); expect(widget.$modelValue).toEqual('xyz');
})); }));
it('should have controller prototype methods', inject(function($rootScope, $formFactory) {
expect(widget.getFormFactory()).toEqual($formFactory);
}));
}); });

View file

@ -112,7 +112,7 @@ describe('$route', function() {
inject(function($route, $location, $rootScope) { inject(function($route, $location, $rootScope) {
var onChangeSpy = jasmine.createSpy('onChange'); var onChangeSpy = jasmine.createSpy('onChange');
function NotFoundCtrl() {this.notFoundProp = 'not found!';} function NotFoundCtrl($scope) {$scope.notFoundProp = 'not found!';}
$route.when('/foo', {template: 'foo.html'}); $route.when('/foo', {template: 'foo.html'});
$route.otherwise({template: '404.html', controller: NotFoundCtrl}); $route.otherwise({template: '404.html', controller: NotFoundCtrl});
@ -169,10 +169,11 @@ describe('$route', function() {
it('should infer arguments in injection', inject(function($route, $location, $rootScope) { it('should infer arguments in injection', inject(function($route, $location, $rootScope) {
$route.when('/test', {controller: function($route){ this.$route = $route; }}); var injectedRoute;
$route.when('/test', {controller: function($route) {injectedRoute = $route;}});
$location.path('/test'); $location.path('/test');
$rootScope.$digest(); $rootScope.$digest();
expect($route.current.scope.$route).toBe($route); expect(injectedRoute).toBe($route);
})); }));
@ -304,9 +305,9 @@ describe('$route', function() {
$route.when('/foo', {controller: FooCtrl, reloadOnSearch: false}); $route.when('/foo', {controller: FooCtrl, reloadOnSearch: false});
$rootScope.$on('$beforeRouteChange', reloaded); $rootScope.$on('$beforeRouteChange', reloaded);
function FooCtrl() { function FooCtrl($scope) {
reloaded(); reloaded();
this.$on('$routeUpdate', routeUpdateEvent); $scope.$on('$routeUpdate', routeUpdateEvent);
} }
expect(reloaded).not.toHaveBeenCalled(); expect(reloaded).not.toHaveBeenCalled();
@ -368,8 +369,8 @@ describe('$route', function() {
$route.when('/foo', {controller: FooCtrl}); $route.when('/foo', {controller: FooCtrl});
$route.when('/bar/:barId', {controller: FooCtrl, reloadOnSearch: false}); $route.when('/bar/:barId', {controller: FooCtrl, reloadOnSearch: false});
function FooCtrl() { function FooCtrl($scope) {
this.$watch(function() { $scope.$watch(function() {
return $route.current.params; return $route.current.params;
}, function(scope, value) { }, function(scope, value) {
routeParams(value); routeParams(value);
@ -414,10 +415,10 @@ describe('$route', function() {
} }
function createController(name) { function createController(name) {
return function() { return function($scope) {
log.push('init-' + name); log.push('init-' + name);
this.$on('$destroy', logger('destroy-' + name)); $scope.$on('$destroy', logger('destroy-' + name));
this.$on('$routeUpdate', logger('route-update')); $scope.$on('$routeUpdate', logger('route-update'));
}; };
} }

View file

@ -53,35 +53,6 @@ describe('Scope', function() {
$rootScope.a = 123; $rootScope.a = 123;
expect(child.a).toEqual(123); expect(child.a).toEqual(123);
})); }));
it('should instantiate controller and bind functions', inject(function($rootScope) {
function Cntl($browser, name) {
this.$browser = $browser;
this.callCount = 0;
this.name = name;
}
Cntl.$inject = ['$browser', 'name'];
Cntl.prototype = {
myFn: function() {
expect(this).toEqual(cntl);
this.callCount++;
}
};
var cntl = $rootScope.$new(Cntl, {name:'misko'});
expect($rootScope.$browser).toBeUndefined();
expect($rootScope.myFn).toBeUndefined();
expect(cntl.$browser).toBeDefined();
expect(cntl.name).toEqual('misko');
cntl.myFn();
cntl.$new().myFn();
expect(cntl.callCount).toEqual(2);
}));
}); });
@ -341,7 +312,7 @@ describe('Scope', function() {
$rootScope.$digest(); $rootScope.$digest();
expect(isNaN(log.shift())).toBe(true); //jasmine's toBe and toEqual don't work well with NaNs expect(isNaN(log.shift())).toBe(true); //jasmine's toBe and toEqual don't work well with NaNs
expect(log).toEqual([undefined, '', false, {}, 23]); expect(log).toEqual([undefined, '', false, {}, 23]);
log = [] log = [];
$rootScope.$digest(); $rootScope.$digest();
expect(log).toEqual([]); expect(log).toEqual([]);
})); }));

View file

@ -713,12 +713,12 @@ describe('widget', function() {
$route.when('/foo', {controller: ParentCtrl, template: 'viewPartial.html'}); $route.when('/foo', {controller: ParentCtrl, template: 'viewPartial.html'});
$rootScope.log = []; $rootScope.log = [];
function ParentCtrl() { function ParentCtrl($scope) {
this.log.push('parent'); $scope.log.push('parent');
} }
$rootScope.ChildCtrl = function() { $rootScope.ChildCtrl = function($scope) {
this.log.push('child'); $scope.log.push('child');
}; };
$location.path('/foo'); $location.path('/foo');