diff --git a/CHANGELOG.md b/CHANGELOG.md
index bb3c47ae..89622356 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,6 +1,22 @@
# 0.9.19 canine-psychokinesis (in-progress) #
+# Breaking Changes
+- Controller constructor functions are now looked up on scope first and then on window.
+- angular.equals now use === which means that things which used to be equal are no longer.
+ Example '0' !== 0 and [] !== ''
+- angular.scope (http://docs.angularjs.org/#!angular.scope) now (providers, cache) instead of
+ (parent, providers, cache)
+- Watch functions (see http://docs.angularjs.org/#!angular.scope.$watch) used to take
+ fn(newValue, oldValue) and be bound to scope, now they take fn(scope, newValue, oldValue)
+- calling $eval() [no args] should be replaced with call to $apply()
+ (http://docs.angularjs.org/#!angular.scope.$apply) ($eval(exp) should remain as is see
+ http://docs.angularjs.org/#!angular.scope.$eval)
+- scope $set/$get have been removed. ($get is same as $eval; no replacement for $set)
+- $route.onChange() callback (http://docs.angularjs.org/#!angular.service.$route)
+ no longer has this bound.
+- Removed undocumented $config in root scope. (You should have not been depending on this.)
+
diff --git a/docs/content/cookbook/mvc.ngdoc b/docs/content/cookbook/mvc.ngdoc
index 6a167469..d757baff 100644
--- a/docs/content/cookbook/mvc.ngdoc
+++ b/docs/content/cookbook/mvc.ngdoc
@@ -64,7 +64,7 @@ no connection between the controller and the view.
});
this.$location.hashSearch.board = rows.join(';') + '/' + this.nextMove;
},
- readUrl: function(value) {
+ readUrl: function(scope, value) {
if (value) {
value = value.split('/');
this.nextMove = value[1];
diff --git a/docs/content/guide/dev_guide.scopes.controlling_scopes.ngdoc b/docs/content/guide/dev_guide.scopes.controlling_scopes.ngdoc
deleted file mode 100644
index cdbad444..00000000
--- a/docs/content/guide/dev_guide.scopes.controlling_scopes.ngdoc
+++ /dev/null
@@ -1,39 +0,0 @@
-@workInProgress
-@ngdoc overview
-@name Developer Guide: Scopes: Applying Controllers to Scopes
-@description
-
-When a controller function is applied to a scope, the scope is augmented with the behavior defined
-in the controller. The end result is that the scope behaves as if it were the controller:
-
-
-
-
-## Related Topics
-
-* {@link dev_guide.scopes Angular Scope Objects}
-* {@link dev_guide.scopes.understanding_scopes Understanding Angular Scopes}
-* {@link dev_guide.scopes.working_scopes Working With Angular Scopes}
-* {@link dev_guide.scopes.updating_scopes Updating Angular Scopes}
-
-## Related API
-
-* {@link api/angular.scope Angular Scope API}
diff --git a/docs/content/guide/dev_guide.scopes.internals.ngdoc b/docs/content/guide/dev_guide.scopes.internals.ngdoc
new file mode 100644
index 00000000..3aed7970
--- /dev/null
+++ b/docs/content/guide/dev_guide.scopes.internals.ngdoc
@@ -0,0 +1,196 @@
+@workInProgress
+@ngdoc overview
+@name Developer Guide: Scopes: Scope Internals
+@description
+
+## What is a scope?
+
+A scope is an execution context for {@link dev_guide.expressions expressions}. You can think of a
+scope as a JavaScript object that has an extra set of APIs for registering change listeners and for
+managing its own life cycle. In Angular's implementation of the model-view-controller design
+pattern, a scope's properties comprise both the model and the controller methods.
+
+
+### Scope characteristics
+- Scopes provide APIs ($watch and $observe) to observe model mutations.
+- Scopes provide APIs ($apply) to propagate any model changes through the system into the view from
+outside of the "Angular realm" (controllers, services, Angular event handlers).
+- Scopes can be nested to isolate application components while providing access to shared model
+properties. A scope (prototypically) inherits properties from its parent scope.
+- In some parts of the system (such as controllers, services and directives), the scope is made
+available as `this` within the given context. (Note: This functionality will change before 1.0 is
+released.)
+
+
+### Root scope
+
+Every application has a root scope, which is the ancestor of all other scopes. The root scope is
+responsible for creating the injector which is assigned to the {@link api/angular.scope.$service
+$service} property, and initializing the services.
+
+### What is scope used for?
+
+{@link dev_guide.expressions Expressions} in the view are evaluated against the current scope. When
+HTML DOM elements are attached to a scope, expressions in those elements are evaluated against the
+attached scope.
+
+There are two kinds of expressions:
+- Binding expressions, which are observations of property changes. Property changes are reflected
+in the view during the {@link api/angular.scope.$flush flush cycle}.
+- Action expressions, which are expressions with side effects. Typically, the side effects cause
+execution of a method in a controller in response to a user action, such as clicking on a button.
+
+
+### Scope inheritance
+
+A scope (prototypically) inherits properties from its parent scope. Since a given property may not
+reside on a child scope, if a property read does not find the property on a scope, the read will
+recursively check the parent scope, grandparent scope, etc. all the way to the root scope before
+defaulting to undefined.
+
+{@link api/angular.directive Directives} associated with elements (ng:controller, ng:repeat,
+ng:include, etc.) create new child scopes that inherit properties from the current parent scope.
+Any code in Angular is free to create a new scope. Whether or not your code does so is an
+implementation detail of the directive, that is, you can decide when or if this happens.
+Inheritance typically mimics HTML DOM element nesting, but does not do so with the same
+granularity.
+
+A property write will always write to the current scope. This means that a write can hide a parent
+property within the scope it writes to, as shown in the following example.
+
+
+
+
+
+## Scopes in Angular applications
+To understand how Angular applications work, you need to understand how scopes work within an
+application. This section describes the typical life cycle of an application so you can see how
+scopes come into play throughout and get a sense of their interactions.
+### How scopes interact in applications
+
+1. At application compile time, a root scope is created and is attached to the root `` DOM
+element.
+ 1. The root scope creates an {@link api/angular.injector injector} which is assigned to the
+{@link api/angular.scope.$service $service} property of the root scope.
+ 2. Any eager {@link api/angular.scope.$service services} are initialized at this point.
+2. During the compilation phase, the {@link dev_guide.compiler compiler} matches {@link
+api/angular.directive directives} against the DOM template. The directives usually fall into one of
+two categories:
+ - Observing {@link api/angular.directive directives}, such as double-curly expressions
+`{{expression}}`, register listeners using the {@link api/angular.scope.$observe $observe()}
+method. This type of directive needs to be notified whenever the expression changes so that it can
+update the view.
+ - Listener directives, such as {@link api/angular.directive.ng:click ng:click}, register a
+listener with the DOM. When the DOM listener fires, the directive executes the associated
+expression and updates the view using the {@link api/angular.scope.$apply $apply()} method.
+3. When an external event (such as a user action, timer or XHR) is received, the associated {@link
+dev_guide.expressions expression} must be applied to the scope through the {@link
+api/angular.scope.$apply $apply()} method so that all listeners are updated correctly.
+
+
+### Directives that create scopes
+In most cases, {@link api/angular.directive directives} and scopes interact but do not create new
+instances of scope. However, some directives, such as {@link api/angular.directive.ng:controller
+ng:controller} and {@link api/angular.widget.@ng:repeat ng:repeat}, create new child scopes using
+the {@link api/angular.scope.$new $new()} method and then attach the child scope to the
+corresponding DOM element. You can retrieve a scope for any DOM element by using an
+`angular.element(aDomElement).scope()` method call.)
+
+
+### Controllers and scopes
+Scopes and controllers interact with each other in the following situations:
+ - Controllers use scopes to expose controller methods to templates (see {@link
+api/angular.directive.ng:controller ng:controller}).
+ - Controllers define methods (behavior) that can mutate the model (properties on the scope).
+ - Controllers may register {@link api/angular.scope.$watch watches} on the model. These watches
+execute immediately after the controller behavior executes, but before the DOM gets updated.
+
+See the {@link dev_guide.mvc.understanding_controller controller docs} for more information.
+
+### Updating scope properties
+You can update a scope by calling its {@link api/angular.scope.$eval $eval()} method, but usually
+you do not have to do this explicitly. In most cases, angular intercepts all external events (such
+as user interactions, XHRs, and timers) and calls the `$eval()` method on the scope object for you
+at the right time. The only time you might need to call `$eval()` explicitly is when you create
+your own custom widget or service.
+
+The reason it is unnecessary to call `$eval()` from within your controller functions when you use
+built-in angular widgets and services is because a change in the data model triggers a call to the
+`$eval()` method on the scope object where the data model changed.
+
+When a user inputs data, angularized widgets copy the data to the appropriate scope and then call
+the `$eval()` method on the root scope to update the view. It works this way because scopes are
+inherited, and a child scope `$eval()` overrides its parent's `$eval()` method. Updating the whole
+page requires a call to `$eval()` on the root scope as `$root.$eval()`. Similarly, when a request
+to fetch data from a server is made and the response comes back, the data is written into the model
+and then `$eval()` is called to push updates through to the view and any other dependents.
+
+A widget that creates scopes (such as {@link api/angular.widget.@ng:repeat ng:repeat}) is
+responsible for forwarding `$eval()` calls from the parent to those child scopes. That way, calling
+`$eval()` on the root scope will update the whole page. This creates a spreadsheet-like behavior
+for your app; the bound views update immediately as the user enters data.
+
+## Scopes in unit-testing
+You can create scopes, including the root scope, in tests using the {@link api/angular.scope} API.
+This allows you to mimic the run-time environment and have full control over the life cycle of the
+scope so that you can assert correct model transitions. Since these scopes are created outside the
+normal compilation process, their life cycles must be managed by the test.
+
+There is a key difference between the way scopes are called in Angular applications and in Angular
+tests. In tests, the {@link api/angular.service.$updateView $updateView} calls the {@link
+api/angular.scope.$flush $flush()} method synchronously.(This is in contrast to the asynchronous
+calls used for applications.) Because test calls to scopes are synchronous, your tests are simpler
+to write.
+
+### Using scopes in unit-testing
+The following example demonstrates how the scope life cycle needs to be manually triggered from
+within the unit-tests.
+
+
+ // example of a test
+ var scope = angular.scope();
+ scope.$watch('name', function(scope, name){
+ scope.greeting = 'Hello ' + name + '!';
+ });
+
+ scope.name = 'angular';
+ // The watch does not fire yet since we have to manually trigger the digest phase.
+ expect(scope.greeting).toEqual(undefined);
+
+ // manually trigger digest phase from the test
+ scope.$digest();
+ expect(scope.greeting).toEqual('Hello Angular!');
+
+
+
+### Dependency injection in Tests
+
+When you find it necessary to inject your own mocks in your tests, use a scope to override the
+service instances, as shown in the following example.
+
+
+
+## Related Topics
+
+* {@link dev_guide.scopes Angular Scope Objects}
+* {@link dev_guide.scopes.understanding_scopes Understanding Scopes}
+
+## Related API
+
+* {@link api/angular.scope Angular Scope API}
+
diff --git a/docs/content/guide/dev_guide.scopes.ngdoc b/docs/content/guide/dev_guide.scopes.ngdoc
index e9706e2f..6ebd5501 100644
--- a/docs/content/guide/dev_guide.scopes.ngdoc
+++ b/docs/content/guide/dev_guide.scopes.ngdoc
@@ -1,36 +1,34 @@
@workInProgress
@ngdoc overview
-@name Developer Guide: Angular Scopes
+@name Developer Guide: Scopes
@description
-An angular scope is a JavaScript type defined by angular. Instances of this type are objects that
-serve as the context within which all model and controller methods live and get evaluated.
+An Angular scope is a JavaScript object with additional APIs useful for watching property changes,
+Angular scope is the model in Model-View-Controller paradigm. Instances of scope serve as the
+context within which all {@link dev_guide.expressions expressions} get evaluated.
-Angular links scope objects to specific points in a compiled (processed) template. This linkage
-provides the contexts in which angular creates data-bindings between the model and the view. You
-can think of angular scope objects as the medium through which the model, view, and controller
-communicate.
+You can think of Angular scope objects as the medium through which the model, view, and controller
+communicate. Scopes are linked during the compilation process with the view. This linkage provides
+the contexts in which Angular creates data-bindings between the model and the view.
-In addition to providing the context in which data is evaluated, angular scope objects watch for
+In addition to providing the context in which data is evaluated, Angular scope objects watch for
model changes. The scope objects also notify all components interested in any model changes (for
example, functions registered through {@link api/angular.scope.$watch $watch}, bindings created by
{@link api/angular.directive.ng:bind ng:bind}, or HTML input elements).
-Angular scope objects are responsible for:
+Angular scope objects:
-* Gluing the model, controller and view template together.
-* Providing the mechanism to watch for model changes ({@link api/angular.scope.$watch}).
-* Notifying interested components when the model changes ({@link api/angular.scope.$eval}).
-* Providing the context in which all controller functions and angular expressions are evaluated.
+* Link the model, controller and view template together.
+* Provide the mechanism to watch for model changes ({@link api/angular.scope.$watch}).
+* Notify interested components when the model changes ({@link api/angular.scope.$eval}).
+* Provide the context in which expressions are evaluated.
## Related Topics
* {@link dev_guide.scopes.understanding_scopes Understanding Scopes}
-* {@link dev_guide.scopes.working_scopes Working With Scopes}
-* {@link dev_guide.scopes.controlling_scopes Applying Controllers to Scopes}
-* {@link dev_guide.scopes.updating_scopes Updating Scopes}
+* {@link dev_guide.scopes.internals Scopes Internals}
## Related API
diff --git a/docs/content/guide/dev_guide.scopes.understanding_scopes.ngdoc b/docs/content/guide/dev_guide.scopes.understanding_scopes.ngdoc
index 704c9241..57804462 100644
--- a/docs/content/guide/dev_guide.scopes.understanding_scopes.ngdoc
+++ b/docs/content/guide/dev_guide.scopes.understanding_scopes.ngdoc
@@ -60,9 +60,7 @@ The following illustration shows the DOM and angular scopes for the example abov
## Related Topics
* {@link dev_guide.scopes Angular Scope Objects}
-* {@link dev_guide.scopes.working_scopes Working With Scopes}
-* {@link dev_guide.scopes.controlling_scopes Applying Controllers to Scopes}
-* {@link dev_guide.scopes.updating_scopes Updating Scopes}
+* {@link dev_guide.scopes.internals Scopes Internals}
## Related API
diff --git a/docs/content/guide/dev_guide.scopes.updating_scopes.ngdoc b/docs/content/guide/dev_guide.scopes.updating_scopes.ngdoc
deleted file mode 100644
index 2d5f1725..00000000
--- a/docs/content/guide/dev_guide.scopes.updating_scopes.ngdoc
+++ /dev/null
@@ -1,38 +0,0 @@
-@workInProgress
-@ngdoc overview
-@name Developer Guide: Scopes: Updating Scope Properties
-@description
-
-You can update a scope by calling its {@link api/angular.scope.$eval $eval()} method, but usually
-you do not have to do this explicitly. In most cases, angular intercepts all external events (such
-as user interactions, XHRs, and timers) and calls the `$eval()` method on the scope object for you
-at the right time. The only time you might need to call `$eval()` explicitly is when you create
-your own custom widget or service.
-
-The reason it is unnecessary to call `$eval()` from within your controller functions when you use
-built-in angular widgets and services is because a change in the data model triggers a call to the
-`$eval()` method on the scope object where the data model changed.
-
-When a user inputs data, angularized widgets copy the data to the appropriate scope and then call
-the `$eval()` method on the root scope to update the view. It works this way because scopes are
-inherited, and a child scope `$eval()` overrides its parent's `$eval()` method. Updating the whole
-page requires a call to `$eval()` on the root scope as `$root.$eval()`. Similarly, when a request
-to fetch data from a server is made and the response comes back, the data is written into the model
-and then `$eval()` is called to push updates through to the view and any other dependents.
-
-A widget that creates scopes (such as {@link api/angular.widget.@ng:repeat ng:repeat}) is
-responsible for forwarding `$eval()` calls from the parent to those child scopes. That way, calling
-`$eval()` on the root scope will update the whole page. This creates a spreadsheet-like behavior
-for your app; the bound views update immediately as the user enters data.
-
-
-## Related Documents
-
-* {@link dev_guide.scopes Angular Scope Objects}
-* {@link dev_guide.scopes.understanding_scopes Understanding Angular Scope Objects}
-* {@link dev_guide.scopes.working_scopes Working With Angular Scopes}
-* {@link dev_guide.scopes.controlling_scopes Applying Controllers to Scopes}
-
-## Related API
-
-* {@link api/angular.scope Angular Scope API}
diff --git a/docs/content/guide/dev_guide.scopes.working_scopes.ngdoc b/docs/content/guide/dev_guide.scopes.working_scopes.ngdoc
deleted file mode 100644
index 8e4503a5..00000000
--- a/docs/content/guide/dev_guide.scopes.working_scopes.ngdoc
+++ /dev/null
@@ -1,52 +0,0 @@
-@workInProgress
-@ngdoc overview
-@name Developer Guide: Scopes: Working With Angular Scopes
-@description
-
-When you use {@link api/angular.directive.ng:autobind ng:autobind} to bootstrap your application,
-angular creates the root scope automatically for you. If you need more control over the
-bootstrapping process, or if you need to create a root scope for a test, you can do so using the
-{@link api/angular.scope angular.scope()} API.
-
-Here is a simple code snippet that demonstrates how to create a scope object, assign model
-properties to it, and register listeners to watch for changes to the model properties:
-
-
-var scope = angular.scope();
-scope.salutation = 'Hello';
-scope.name = 'World';
-
-// Verify that greeting is undefined
-expect(scope.greeting).toEqual(undefined);
-
-// Set up the watcher...
-scope.$watch('name', function(){
-// when 'name' changes, set 'greeting'...
-this.greeting = this.salutation + ' ' + this.name + '!';
-}
-);
-
-// verify that 'greeting' was set...
-expect(scope.greeting).toEqual('Hello World!');
-
-// 'name' changed!
-scope.name = 'Misko';
-
-// scope.$eval() will propagate the change to listeners
-expect(scope.greeting).toEqual('Hello World!');
-
-scope.$eval();
-// verify that '$eval' propagated the change
-expect(scope.greeting).toEqual('Hello Misko!');
-
-
-## Related Topics
-
-* {@link dev_guide.scopes Angular Scope Objects}
-* {@link dev_guide.scopes.understanding_scopes Understanding Scopes}
-* {@link dev_guide.scopes.controlling_scopes Applying Controllers to Scopes}
-* {@link dev_guide.scopes.updating_scopes Updating Scopes}
-
-## Related API
-
-* {@link api/angular.scope Angular Scope API}
diff --git a/docs/content/guide/index.ngdoc b/docs/content/guide/index.ngdoc
index c40bb1be..b2aab161 100644
--- a/docs/content/guide/index.ngdoc
+++ b/docs/content/guide/index.ngdoc
@@ -30,9 +30,7 @@ of the following documents before returning here to the Developer Guide:
## {@link dev_guide.scopes Angular Scope Objects}
* {@link dev_guide.scopes.understanding_scopes Understanding Angular Scope Objects}
-* {@link dev_guide.scopes.working_scopes Working With Angular Scopes}
-* {@link dev_guide.scopes.controlling_scopes Applying Controllers to Scopes}
-* {@link dev_guide.scopes.updating_scopes Updating Scope Properties}
+* {@link dev_guide.scopes.internals Angular Scope Internals}
## {@link dev_guide.compiler Angular HTML Compiler}
diff --git a/docs/src/templates/docs.css b/docs/src/templates/docs.css
index 4baea33c..3f53b3dd 100644
--- a/docs/src/templates/docs.css
+++ b/docs/src/templates/docs.css
@@ -398,3 +398,25 @@ li {
margin: 0em 2em 1em 0em;
float:right;
}
+
+.table {
+ border-collapse: collapse;
+}
+
+.table th:first-child {
+ text-align: right;
+}
+
+.table th,
+.table td {
+ border: 1px solid black;
+ padding: .5em 1em;
+}
+.table th {
+ white-space: nowrap;
+}
+
+.table th.section {
+ text-align: left;
+ background-color: lightgray;
+}
diff --git a/docs/src/templates/docs.js b/docs/src/templates/docs.js
index 7efb2a5e..de6130dc 100644
--- a/docs/src/templates/docs.js
+++ b/docs/src/templates/docs.js
@@ -17,7 +17,7 @@ function DocsController($location, $browser, $window, $cookies) {
$location.hashPath = '!/api';
}
- this.$watch('$location.hashPath', function(hashPath) {
+ this.$watch('$location.hashPath', function(scope, hashPath) {
if (hashPath.match(/^!/)) {
var parts = hashPath.substring(1).split('/');
self.sectionId = parts[1];
@@ -36,7 +36,7 @@ function DocsController($location, $browser, $window, $cookies) {
delete self.partialId;
}
}
- });
+ })();
this.getUrl = function(page){
return '#!/' + page.section + '/' + page.id;
diff --git a/perf/MiscPerf.js b/perf/MiscPerf.js
new file mode 100644
index 00000000..c1d71cbd
--- /dev/null
+++ b/perf/MiscPerf.js
@@ -0,0 +1,21 @@
+describe('perf misc', function(){
+ it('operation speeds', function(){
+ perf(
+ function typeByTypeof(){ return typeof noop == 'function'; }, // WINNER
+ function typeByProperty() { return noop.apply && noop.call; },
+ function typeByConstructor() { return noop.constructor == Function; }
+ );
+ });
+
+ it('property access', function(){
+ var name = 'value';
+ var none = 'x';
+ var scope = {};
+ perf(
+ function direct(){ return scope.value; }, // WINNER
+ function byName() { return scope[name]; },
+ function undefinedDirect(){ return scope.x; },
+ function undefiendByName() { return scope[none]; }
+ );
+ });
+});
diff --git a/src/Angular.js b/src/Angular.js
index c26b799a..63182ecd 100644
--- a/src/Angular.js
+++ b/src/Angular.js
@@ -56,7 +56,6 @@ function fromCharCode(code) { return String.fromCharCode(code); }
var _undefined = undefined,
_null = null,
- $$element = '$element',
$$scope = '$scope',
$$validate = '$validate',
$angular = 'angular',
@@ -65,7 +64,6 @@ var _undefined = undefined,
$console = 'console',
$date = 'date',
$display = 'display',
- $element = 'element',
$function = 'function',
$length = 'length',
$name = 'name',
@@ -573,6 +571,16 @@ function isLeafNode (node) {
return false;
}
+/**
+ * @workInProgress
+ * @ngdoc function
+ * @name angular.copy
+ * @function
+ *
+ * @description
+ * Alias for {@link angular.Object.copy}
+ */
+
/**
* @ngdoc function
* @name angular.Object.copy
@@ -657,6 +665,15 @@ function copy(source, destination){
return destination;
}
+/**
+ * @workInProgress
+ * @ngdoc function
+ * @name angular.equals
+ * @function
+ *
+ * @description
+ * Alias for {@link angular.Object.equals}
+ */
/**
* @ngdoc function
@@ -666,8 +683,8 @@ function copy(source, destination){
* @description
* Determines if two objects or value are equivalent.
*
- * To be equivalent, they must pass `==` comparison or be of the same type and have all their
- * properties pass `==` comparison. During property comparision properties of `function` type and
+ * To be equivalent, they must pass `===` comparison or be of the same type and have all their
+ * properties pass `===` comparison. During property comparision properties of `function` type and
* properties with name starting with `$` are ignored.
*
* Supports values types, arrays and objects.
@@ -707,7 +724,7 @@ function copy(source, destination){
*
*/
function equals(o1, o2) {
- if (o1 == o2) return true;
+ if (o1 === o2) return true;
if (o1 === null || o2 === null) return false;
var t1 = typeof o1, t2 = typeof o2, length, key, keySet;
if (t1 == t2 && t1 == 'object') {
@@ -779,6 +796,10 @@ function concat(array1, array2, index) {
return array1.concat(slice.call(array2, index, array2.length));
}
+function sliceArgs(args, startIndex) {
+ return slice.call(args, startIndex || 0, args.length);
+}
+
/**
* @workInProgress
@@ -797,9 +818,7 @@ function concat(array1, array2, index) {
* @returns {function()} Function that wraps the `fn` with all the specified bindings.
*/
function bind(self, fn) {
- var curryArgs = arguments.length > 2
- ? slice.call(arguments, 2, arguments.length)
- : [];
+ var curryArgs = arguments.length > 2 ? sliceArgs(arguments, 2) : [];
if (typeof fn == $function && !(fn instanceof RegExp)) {
return curryArgs.length
? function() {
@@ -939,13 +958,14 @@ function angularInit(config, document){
if (autobind) {
var element = isString(autobind) ? document.getElementById(autobind) : document,
- scope = compile(element)(createScope({'$config':config})),
+ scope = compile(element)(createScope()),
$browser = scope.$service('$browser');
if (config.css)
$browser.addCss(config.base_url + config.css);
else if(msie<8)
$browser.addJs(config.ie_compat, config.ie_compat_id);
+ scope.$apply();
}
}
@@ -1001,7 +1021,8 @@ function assertArg(arg, name, reason) {
}
function assertArgFn(arg, name) {
- assertArg(isFunction(arg, name, 'not a function'));
+ assertArg(isFunction(arg), name, 'not a function, got ' +
+ (typeof arg == 'object' ? arg.constructor.name : typeof arg));
}
diff --git a/src/Browser.js b/src/Browser.js
index 815b6b24..562b137d 100644
--- a/src/Browser.js
+++ b/src/Browser.js
@@ -60,7 +60,7 @@ function Browser(window, document, body, XHR, $log) {
*/
function completeOutstandingRequest(fn) {
try {
- fn.apply(null, slice.call(arguments, 1));
+ fn.apply(null, sliceArgs(arguments, 1));
} finally {
outstandingRequestCount--;
if (outstandingRequestCount === 0) {
diff --git a/src/Compiler.js b/src/Compiler.js
index 730d175e..8512f0c3 100644
--- a/src/Compiler.js
+++ b/src/Compiler.js
@@ -29,15 +29,20 @@ Template.prototype = {
inits[this.priority] = queue = [];
}
if (this.newScope) {
- childScope = createScope(scope);
- scope.$onEval(childScope.$eval);
+ childScope = isFunction(this.newScope) ? scope.$new(this.newScope(scope)) : scope.$new();
element.data($$scope, childScope);
}
+ // TODO(misko): refactor this!!!
+ // Why are inits even here?
forEach(this.inits, function(fn) {
queue.push(function() {
- childScope.$tryEval(function(){
- return childScope.$service.invoke(childScope, fn, [element]);
- }, element);
+ childScope.$eval(function(){
+ try {
+ return childScope.$service.invoke(childScope, fn, [element]);
+ } catch (e) {
+ childScope.$service('$exceptionHandler')(e);
+ }
+ });
});
});
var i,
@@ -218,7 +223,6 @@ Compiler.prototype = {
scope.$element = element;
(cloneConnectFn||noop)(element, scope);
template.attach(element, scope);
- scope.$eval();
return scope;
};
},
@@ -228,6 +232,7 @@ Compiler.prototype = {
* @workInProgress
* @ngdoc directive
* @name angular.directive.ng:eval-order
+ * @deprecated
*
* @description
* Normally the view is updated from top to bottom. This usually is
@@ -244,9 +249,9 @@ Compiler.prototype = {
* @example
-
TOTAL: without ng:eval-order {{ items.$sum('total') | currency }}
-
TOTAL: with ng:eval-order {{ items.$sum('total') | currency }}
-
+
TOTAL: without ng:eval-order {{ total | currency }}
it('should check ng:format', function(){
- expect(using('.doc-example-live div:first').binding("items.$sum('total')")).toBe('$9.99');
- expect(using('.doc-example-live div:last').binding("items.$sum('total')")).toBe('$9.99');
+ expect(using('.doc-example-live div:first').binding("total")).toBe('$0.00');
+ expect(using('.doc-example-live div:last').binding("total")).toBe('$9.99');
input('item.qty').enter('2');
- expect(using('.doc-example-live div:first').binding("items.$sum('total')")).toBe('$9.99');
- expect(using('.doc-example-live div:last').binding("items.$sum('total')")).toBe('$19.98');
+ expect(using('.doc-example-live div:first').binding("total")).toBe('$9.99');
+ expect(using('.doc-example-live div:last').binding("total")).toBe('$19.98');
});
diff --git a/src/JSON.js b/src/JSON.js
index 0a826e0e..b0f72a1b 100644
--- a/src/JSON.js
+++ b/src/JSON.js
@@ -116,6 +116,9 @@ function toJsonArray(buf, obj, pretty, stack) {
sep = true;
}
buf.push("]");
+ } else if (isElement(obj)) {
+ // TODO(misko): maybe in dev mode have a better error reporting?
+ buf.push('DOM_ELEMENT');
} else if (isDate(obj)) {
buf.push(angular.String.quoteUnicode(angular.Date.toString(obj)));
} else {
diff --git a/src/Scope.js b/src/Scope.js
index b9fab638..572e9760 100644
--- a/src/Scope.js
+++ b/src/Scope.js
@@ -1,537 +1,788 @@
'use strict';
-function getter(instance, path, unboundFn) {
- 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 accessing 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(lastInstance, fn, lastInstance);
- return instance;
- }
- }
- }
- if (!unboundFn && isFunction(instance)) {
- return bind(lastInstance, instance);
- }
- return instance;
-}
+/**
+ * DESIGN NOTES
+ *
+ * The design decisions behind the scope ware heavily favored for speed and memory consumption.
+ *
+ * The typical use of scope is to watch the expressions, which most of the time return the same
+ * value as last time so we optimize the operation.
+ *
+ * Closures construction is expensive from speed as well as memory:
+ * - no closures, instead ups prototypical inheritance for API
+ * - Internal state needs to be stored on scope directly, which means that private state is
+ * exposed as $$____ properties
+ *
+ * Loop operations are optimized by using while(count--) { ... }
+ * - this means that in order to keep the same order of execution as addition we have to add
+ * items to the array at the begging (shift) instead of at the end (push)
+ *
+ * Child scopes are created and removed often
+ * - Using array would be slow since inserts in meddle are expensive so we use linked list
+ *
+ * There are few watches then a lot of observers. This is why you don't want the observer to be
+ * implemented in the same way as watch. Watch requires return of initialization function which
+ * are expensive to construct.
+ */
-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 scopeId = 0,
- getterFnCache = {},
- compileCache = {},
- JS_KEYWORDS = {};
-forEach(
- ("abstract,boolean,break,byte,case,catch,char,class,const,continue,debugger,default," +
- "delete,do,double,else,enum,export,extends,false,final,finally,float,for,function,goto," +
- "if,implements,import,ininstanceof,intinterface,long,native,new,null,package,private," +
- "protected,public,return,short,static,super,switch,synchronized,this,throw,throws," +
- "transient,true,try,typeof,var,volatile,void,undefined,while,with").split(/,/),
- function(key){ JS_KEYWORDS[key] = true;}
-);
-function getterFn(path){
- var fn = getterFnCache[path];
- if (fn) return fn;
-
- var code = 'var l, fn, t;\n';
- forEach(path.split('.'), function(key) {
- key = (JS_KEYWORDS[key]) ? '["' + key + '"]' : '.' + key;
- code += 'if(!s) return s;\n' +
- 'l=s;\n' +
- 's=s' + key + ';\n' +
- 'if(typeof s=="function" && !(s instanceof RegExp)) s = function(){ return l'+key+'.apply(l, arguments); };\n';
- if (key.charAt(1) == '$') {
- // special code for super-imposed functions
- var name = key.substr(2);
- code += 'if(!s) {\n' +
- ' t = angular.Global.typeOf(l);\n' +
- ' fn = (angular[t.charAt(0).toUpperCase() + t.substring(1)]||{})["' + name + '"];\n' +
- ' if (fn) s = function(){ return fn.apply(l, [l].concat(Array.prototype.slice.call(arguments, 0, arguments.length))); };\n' +
- '}\n';
- }
- });
- code += 'return s;';
- fn = Function('s', code);
- fn["toString"] = function(){ return code; };
-
- return getterFnCache[path] = fn;
-}
-
-///////////////////////////////////
-
-function expressionCompile(exp){
- if (typeof exp === $function) return exp;
- var fn = compileCache[exp];
- if (!fn) {
- var p = parser(exp);
- var fnSelf = p.statements();
- fn = compileCache[exp] = extend(
- function(){ return fnSelf(this);},
- {fnSelf: fnSelf});
- }
- return fn;
-}
-
-function errorHandlerFor(element, error) {
- elementError(element, NG_EXCEPTION, isDefined(error) ? formatError(error) : error);
-}
+function createScope(providers, instanceCache) {
+ var scope = new Scope();
+ (scope.$service = createInjector(scope, providers, instanceCache)).eager();
+ return scope;
+};
/**
* @workInProgress
- * @ngdoc overview
+ * @ngdoc function
* @name angular.scope
*
* @description
- * Scope is a JavaScript object and the execution context for expressions. You can think about
- * scopes as JavaScript objects that have extra APIs for registering watchers. A scope is the
- * context in which model (from the model-view-controller design pattern) exists.
+ * A root scope can be created by calling {@link angular.scope angular.scope()}. Child scopes
+ * are created using the {@link angular.scope.$new $new()} method.
+ * (Most scopes are created automatically when compiled HTML template is executed.)
*
- * Angular scope objects provide the following methods:
+ * Here is a simple scope snippet to show how you can interact with the scope.
+ *
+ var scope = angular.scope();
+ scope.salutation = 'Hello';
+ scope.name = 'World';
+
+ expect(scope.greeting).toEqual(undefined);
+
+ scope.$watch('name', function(){
+ this.greeting = this.salutation + ' ' + this.name + '!';
+ }); // initialize the watch
+
+ expect(scope.greeting).toEqual(undefined);
+ scope.name = 'Misko';
+ // still old value, since watches have not been called yet
+ expect(scope.greeting).toEqual(undefined);
+
+ scope.$digest(); // fire all the watches
+ expect(scope.greeting).toEqual('Hello Misko!');
+ *
+ *
+ * # Dependency Injection
+ * See {@link guide/dev_guide.di dependency injection}.
+ *
+ *
+ * @param {Object.=} providers Map of service factory which need to be provided
+ * for the current scope. Defaults to {@link angular.service}.
+ * @param {Object.=} instanceCache Provides pre-instantiated services which should
+ * append/override services provided by `providers`. This is handy when unit-testing and having
+ * the need to override a default service.
+ * @returns {Object} Newly created scope.
*
- * For more information about how angular scope objects work, see {@link guide/dev_guide.scopes
- * Angular Scope Objects} in the angular Developer Guide.
*/
-function createScope(parent, providers, instanceCache) {
- function Parent(){}
- parent = Parent.prototype = (parent || {});
- var instance = new Parent();
- var evalLists = {sorted:[]};
- var $log, $exceptionHandler;
+function Scope() {
+ this.$id = nextUid();
+ this.$$phase = this.$parent = this.$$watchers = this.$$observers =
+ this.$$nextSibling = this.$$childHead = this.$$childTail = null;
+ this['this'] = this.$root = this;
+}
- extend(instance, {
- 'this': instance,
- $id: (scopeId++),
- $parent: parent,
+/**
+ * @workInProgress
+ * @ngdoc property
+ * @name angular.scope.$id
+ * @returns {number} Unique scope ID (monotonically increasing alphanumeric sequence) useful for
+ * debugging.
+ */
- /**
- * @workInProgress
- * @ngdoc function
- * @name angular.scope.$bind
- * @function
- *
- * @description
- * Binds a function `fn` to the current scope. See: {@link angular.bind}.
+/**
+ * @workInProgress
+ * @ngdoc property
+ * @name angular.scope.$service
+ * @function
+ *
+ * @description
+ * Provides reference to an instance of {@link angular.injector injector} which can be used to
+ * retrieve {@link angular.service services}. In general the use of this api is discouraged,
+ * in favor of proper {@link guide/dev_guide.di dependency injection}.
+ *
+ * @returns {function} {@link angular.injector injector}
+ */
-
- var scope = angular.scope();
- var fn = scope.$bind(function(){
- return this;
- });
- expect(fn()).toEqual(scope);
-
- *
- * @param {function()} fn Function to be bound.
- */
- $bind: bind(instance, bind, instance),
+/**
+ * @workInProgress
+ * @ngdoc property
+ * @name angular.scope.$root
+ * @returns {Scope} The root scope of the current scope hierarchy.
+ */
+
+/**
+ * @workInProgress
+ * @ngdoc property
+ * @name angular.scope.$parent
+ * @returns {Scope} The parent scope of the current scope.
+ */
- /**
- * @workInProgress
- * @ngdoc function
- * @name angular.scope.$get
- * @function
- *
- * @description
- * Returns the value for `property_chain` on the current scope. Unlike in JavaScript, if there
- * are any `undefined` intermediary properties, `undefined` is returned instead of throwing an
- * exception.
- *
-
- *
- * @param {string} property_chain String representing name of a scope property. Optionally
- * properties can be chained with `.` (dot), e.g. `'person.name.first'`
- * @returns {*} Value for the (nested) property.
- */
- $get: bind(instance, getter, instance),
+Scope.prototype = {
+ /**
+ * @workInProgress
+ * @ngdoc function
+ * @name angular.scope.$new
+ * @function
+ *
+ * @description
+ * Creates a new child {@link angular.scope scope}. The new scope can optionally behave as a
+ * controller. The parent scope will propagate the {@link angular.scope.$digest $digest()} and
+ * {@link angular.scope.$flush $flush()} events. The scope can be removed from the scope
+ * hierarchy using {@link angular.scope.$destroy $destroy()}.
+ *
+ * {@link angular.scope.$destroy $destroy()} must be called on a scope when it is desired for
+ * 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.
+ *
+ * @param {function()=} constructor Constructor function which the scope should behave as.
+ * @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.
+ *
+ */
+ $new: function(Class, curryArguments) {
+ 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
+ // name in the debugger.
+ var child;
+ Child.prototype = this;
+ child = new Child();
+ child['this'] = child;
+ child.$parent = this;
+ child.$id = nextUid();
+ child.$$phase = child.$$watchers = child.$$observers =
+ child.$$nextSibling = child.$$childHead = child.$$childTail = null;
+ if (this.$$childHead) {
+ this.$$childTail.$$nextSibling = child;
+ this.$$childTail = child;
+ } else {
+ 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]);
+ }
+ this.$service.invoke(child, Class, curryArguments);
+ }
+ return child;
+ },
+ /**
+ * @workInProgress
+ * @ngdoc function
+ * @name angular.scope.$watch
+ * @function
+ *
+ * @description
+ * Registers a `listener` callback to be executed whenever the `watchExpression` changes.
+ *
+ * - The `watchExpression` is called on every call to {@link angular.scope.$digest $digest()} and
+ * should return the value which will be watched. (Since {@link angular.scope.$digest $digest()}
+ * reruns when it detects changes the `watchExpression` can execute multiple times per
+ * {@link angular.scope.$digest $digest()} and should be idempotent.)
+ * - The `listener` is called only when the value from the current `watchExpression` and the
+ * previous call to `watchExpression' are not equal. The inequality is determined according to
+ * {@link angular.equals} function. To save the value of the object for later comparison
+ * {@link angular.copy} function is used. It also means that watching complex options will
+ * have adverse memory and performance implications.
+ * - The watch `listener` may change the model, which may trigger other `listener`s to fire. This
+ * is achieving my rerunning the watchers until no changes are detected. The rerun iteration
+ * limit is 100 to prevent infinity loop deadlock.
+ *
+ * # When to use `$watch`?
+ *
+ * The `$watch` should be used from within controllers to listen on properties *immediately* after
+ * a stimulus is applied to the system (see {@link angular.scope.$apply $apply()}). This is in
+ * contrast to {@link angular.scope.$observe $observe()} which is used from within the directives
+ * and which gets applied at some later point in time. In addition
+ * {@link angular.scope.$observe $observe()} must not modify the model.
+ *
+ * If you want to be notified whenever {@link angular.scope.$digest $digest} is called,
+ * you can register an `watchExpression` function with no `listener`. (Since `watchExpression`,
+ * can execute multiple times per {@link angular.scope.$digest $digest} cycle when a change is
+ * detected, be prepared for multiple calls to your listener.)
+ *
+ * # `$watch` vs `$observe`
+ *
+ *
+ *
+ *
+ *
{@link angular.scope.$watch $watch()}
+ *
{@link angular.scope.$observe $observe()}
+ *
+ *
When to use it?
+ *
+ *
Purpose
+ *
Application behavior (including further model mutation) in response to a model
+ * mutation.
{@link angular.scope.$apply $apply} schedules
+ * {@link angular.scope.$flush $flush()} at some future time via
+ * {@link angular.service.$updateView $updateView}
+ *
+ *
API contract
+ *
+ *
Model mutation
+ *
allowed: detecting mutations requires one or mare calls to `watchExpression' per
+ * {@link angular.scope.$digest $digest()} cycle
+ *
not allowed: called once per {@link angular.scope.$flush $flush()} must be
+ * {@link http://en.wikipedia.org/wiki/Idempotence idempotent}
+ * (function without side-effects which can be called multiple times.)
+ *
+ *
+ *
Initial Value
+ *
uses the current value of `watchExpression` as the initial value. Does not fire on
+ * initial call to {@link angular.scope.$digest $digest()}, unless `watchExpression` has
+ * changed form the initial value.
+ *
fires on first run of {@link angular.scope.$flush $flush()} regardless of value of
+ * `observeExpression`
+ *
+ *
+ *
+ *
+ *
+ * # Example
+
+ var scope = angular.scope();
+ scope.name = 'misko';
+ scope.counter = 0;
- /**
- * @workInProgress
- * @ngdoc function
- * @name angular.scope.$set
- * @function
- *
- * @description
- * Assigns a value to a property of the current scope specified via `property_chain`. Unlike in
- * JavaScript, if there are any `undefined` intermediary properties, empty objects are created
- * and assigned to them instead of throwing an exception.
- *
-
- *
- * @param {string} property_chain String representing name of a scope property. Optionally
- * properties can be chained with `.` (dot), e.g. `'person.name.first'`
- * @param {*} value Value to assign to the scope property.
- */
- $set: bind(instance, setter, instance),
+ expect(scope.counter).toEqual(0);
+ scope.$watch('name', function(scope, newValue, oldValue) { counter = counter + 1; });
+ expect(scope.counter).toEqual(0);
+ scope.$digest();
+ // no variable change
+ expect(scope.counter).toEqual(0);
- /**
- * @workInProgress
- * @ngdoc function
- * @name angular.scope.$eval
- * @function
- *
- * @description
- * Without the `exp` parameter triggers an eval cycle for this scope and its child scopes.
- *
- * With the `exp` parameter, compiles the expression to a function and calls it with `this` set
- * to the current scope and returns the result. In other words, evaluates `exp` as angular
- * expression in the context of the current scope.
- *
- * # Example
-
+ *
+ *
+ *
+ * @param {(function()|string)} watchExpression Expression that is evaluated on each
+ * {@link angular.scope.$digest $digest} cycle. A change in the return value triggers a
+ * call to the `listener`.
+ *
+ * - `string`: Evaluated as {@link guide/dev_guide.expressions expression}
+ * - `function(scope)`: called with current `scope` as a parameter.
+ * @param {(function()|string)=} listener Callback called whenever the return value of
+ * the `watchExpression` changes.
+ *
+ * - `string`: Evaluated as {@link guide/dev_guide.expressions expression}
+ * - `function(scope, newValue, oldValue)`: called with current `scope` an previous and
+ * current values as parameters.
+ * @returns {function()} a function which will call the `listener` with apprariate arguments.
+ * Useful for forcing initialization of listener.
+ */
+ $watch: function(watchExp, listener) {
+ var scope = this;
+ var get = compileToFn(watchExp, 'watch');
+ var listenFn = compileToFn(listener || noop, 'listener');
+ var array = scope.$$watchers;
+ if (!array) {
+ array = scope.$$watchers = [];
+ }
+ // we use unshift since we use a while loop in $digest for speed.
+ // the while loop reads in reverse order.
+ array.unshift({
+ fn: listenFn,
+ last: copy(get(scope)),
+ get: get
+ });
+ // we only return the initialization function for $watch (not for $observe), since creating
+ // function cost time and memory, and $observe functions do not need it.
+ return function() {
+ var value = get(scope);
+ listenFn(scope, value, value);
+ };
+ },
- expect(scope.$eval('a+b')).toEqual(3);
- expect(scope.$eval(function(){ return this.a + this.b; })).toEqual(3);
+ /**
+ * @workInProgress
+ * @ngdoc function
+ * @name angular.scope.$digest
+ * @function
+ *
+ * @description
+ * Process all of the {@link angular.scope.$watch watchers} of the current scope and its children.
+ * Because a {@link angular.scope.$watch watcher}'s listener can change the model, the
+ * `$digest()` keeps calling the {@link angular.scope.$watch watchers} until no more listeners are
+ * firing. This means that it is possible to get into an infinite loop. This function will throw
+ * `'Maximum iteration limit exceeded.'` if the number of iterations exceeds 100.
+ *
+ * Usually you don't call `$digest()` directly in
+ * {@link angular.directive.ng:controller controllers} or in {@link angular.directive directives}.
+ * Instead a call to {@link angular.scope.$apply $apply()} (typically from within a
+ * {@link angular.directive directive}) will force a `$digest()`.
+ *
+ * If you want to be notified whenever `$digest()` is called,
+ * you can register a `watchExpression` function with {@link angular.scope.$watch $watch()}
+ * with no `listener`.
+ *
+ * You may have a need to call `$digest()` from within unit-tests, to simulate the scope
+ * life-cycle.
+ *
+ * # Example
+
- *
- * @param {(string|function())=} exp An angular expression to be compiled to a function or a js
- * function.
- *
- * @returns {*} The result of calling compiled `exp` with `this` set to the current scope.
- */
- $eval: function(exp) {
- var type = typeof exp;
- var i, iSize;
- var j, jSize;
- var queue;
- var fn;
- if (type == $undefined) {
- for ( i = 0, iSize = evalLists.sorted.length; i < iSize; i++) {
- for ( queue = evalLists.sorted[i],
- jSize = queue.length,
- j= 0; j < jSize; j++) {
- instance.$tryEval(queue[j].fn, queue[j].handler);
+ expect(scope.counter).toEqual(0);
+ scope.$flush('name', function(scope, newValue, oldValue) { counter = counter + 1; });
+ expect(scope.counter).toEqual(0);
+
+ scope.$flush();
+ // no variable change
+ expect(scope.counter).toEqual(0);
+
+ scope.name = 'adam';
+ scope.$flush();
+ expect(scope.counter).toEqual(1);
+
+ *
+ * @returns {number} number of {@link angular.scope.$watch listeners} which fired.
+ *
+ */
+ $digest: function() {
+ var child,
+ watch, value, last,
+ watchers = this.$$watchers,
+ length, count = 0,
+ iterationCount, ttl = 100;
+
+ if (this.$$phase) {
+ throw Error(this.$$phase + ' already in progress');
+ }
+ this.$$phase = '$digest';
+ do {
+ iterationCount = 0;
+ if (watchers) {
+ // process our watches
+ length = watchers.length;
+ while (length--) {
+ try {
+ watch = watchers[length];
+ // Most common watches are on primitives, in which case we can short
+ // circuit it with === operator, only when === fails do we use .equals
+ if ((value = watch.get(this)) !== (last = watch.last) && !equals(value, last)) {
+ iterationCount++;
+ watch.fn(this, watch.last = copy(value), last);
+ }
+ } catch (e) {
+ this.$service('$exceptionHandler')(e);
}
}
- } else if (type === $function) {
- return exp.call(instance);
- } else if (type === 'string') {
- return expressionCompile(exp).call(instance);
}
- },
-
-
- /**
- * @workInProgress
- * @ngdoc function
- * @name angular.scope.$tryEval
- * @function
- *
- * @description
- * Evaluates the expression in the context of the current scope just like
- * {@link angular.scope.$eval} with expression parameter, but also wraps it in a try/catch
- * block.
- *
- * If an exception is thrown then `exceptionHandler` is used to handle the exception.
- *
- * # Example
-
- *
- * @param {string|function()} expression Angular expression to evaluate.
- * @param {(function()|DOMElement)=} exceptionHandler Function to be called or DOMElement to be
- * decorated.
- * @returns {*} The result of `expression` evaluation.
- */
- $tryEval: function (expression, exceptionHandler) {
- var type = typeof expression;
- try {
- if (type == $function) {
- return expression.call(instance);
- } else if (type == 'string'){
- return expressionCompile(expression).call(instance);
- }
- } catch (e) {
- if ($log) $log.error(e);
- if (isFunction(exceptionHandler)) {
- exceptionHandler(e);
- } else if (exceptionHandler) {
- errorHandlerFor(exceptionHandler, e);
- } else if (isFunction($exceptionHandler)) {
- $exceptionHandler(e);
- }
+ child = this.$$childHead;
+ while(child) {
+ iterationCount += child.$digest();
+ child = child.$$nextSibling;
}
- },
-
-
- /**
- * @workInProgress
- * @ngdoc function
- * @name angular.scope.$watch
- * @function
- *
- * @description
- * Registers `listener` as a callback to be executed every time the `watchExp` changes. Be aware
- * that the callback gets, by default, called upon registration, this can be prevented via the
- * `initRun` parameter.
- *
- * # Example
-
- *
- * @param {function()|string} watchExp Expression that should be evaluated and checked for
- * change during each eval cycle. Can be an angular string expression or a function.
- * @param {function()|string} listener Function (or angular string expression) that gets called
- * every time the value of the `watchExp` changes. The function will be called with two
- * parameters, `newValue` and `oldValue`.
- * @param {(function()|DOMElement)=} [exceptionHanlder=angular.service.$exceptionHandler] Handler
- * that gets called when `watchExp` or `listener` throws an exception. If a DOMElement is
- * specified as a handler, the element gets decorated by angular with the information about the
- * exception.
- * @param {boolean=} [initRun=true] Flag that prevents the first execution of the listener upon
- * registration.
- *
- */
- $watch: function(watchExp, listener, exceptionHandler, initRun) {
- var watch = expressionCompile(watchExp),
- last = watch.call(instance);
- listener = expressionCompile(listener);
- function watcher(firstRun){
- var value = watch.call(instance),
- // we have to save the value because listener can call ourselves => inf loop
- lastValue = last;
- if (firstRun || lastValue !== value) {
- last = value;
- instance.$tryEval(function(){
- return listener.call(instance, value, lastValue);
- }, exceptionHandler);
- }
+ count += iterationCount;
+ if(!(ttl--)) {
+ throw Error('100 $digest() iterations reached. Aborting!');
}
- instance.$onEval(PRIORITY_WATCH, watcher);
- if (isUndefined(initRun)) initRun = true;
- if (initRun) watcher(true);
- },
+ } while (iterationCount);
+ this.$$phase = null;
+ return count;
+ },
- /**
- * @workInProgress
- * @ngdoc function
- * @name angular.scope.$onEval
- * @function
- *
- * @description
- * Evaluates the `expr` expression in the context of the current scope during each
- * {@link angular.scope.$eval eval cycle}.
- *
- * # Example
-
- *
- * @param {number} [priority=0] Execution priority. Lower priority numbers get executed first.
- * @param {string|function()} expr Angular expression or function to be executed.
- * @param {(function()|DOMElement)=} [exceptionHandler=angular.service.$exceptionHandler] Handler
- * function to call or DOM element to decorate when an exception occurs.
- *
- */
- $onEval: function(priority, expr, exceptionHandler){
- if (!isNumber(priority)) {
- exceptionHandler = expr;
- expr = priority;
- priority = 0;
- }
- var evalList = evalLists[priority];
- if (!evalList) {
- evalList = evalLists[priority] = [];
- evalList.priority = priority;
- evalLists.sorted.push(evalList);
- evalLists.sorted.sort(function(a,b){return a.priority-b.priority;});
- }
- evalList.push({
- fn: expressionCompile(expr),
- handler: exceptionHandler
- });
- },
+ /**
+ * @workInProgress
+ * @ngdoc function
+ * @name angular.scope.$observe
+ * @function
+ *
+ * @description
+ * Registers a `listener` callback to be executed during the {@link angular.scope.$flush $flush()}
+ * phase when the `observeExpression` changes..
+ *
+ * - The `observeExpression` is called on every call to {@link angular.scope.$flush $flush()} and
+ * should return the value which will be observed.
+ * - The `listener` is called only when the value from the current `observeExpression` and the
+ * previous call to `observeExpression' are not equal. The inequality is determined according to
+ * {@link angular.equals} function. To save the value of the object for later comparison
+ * {@link angular.copy} function is used. It also means that watching complex options will
+ * have adverse memory and performance implications.
+ *
+ * # When to use `$observe`?
+ *
+ * {@link angular.scope.$observe $observe()} is used from within directives and gets applied at
+ * some later point in time. Addition {@link angular.scope.$observe $observe()} must not
+ * modify the model. This is in contrast to {@link angular.scope.$watch $watch()} which should be
+ * used from within controllers to trigger a callback *immediately* after a stimulus is applied
+ * to the system (see {@link angular.scope.$apply $apply()}).
+ *
+ * If you want to be notified whenever {@link angular.scope.$flush $flush} is called,
+ * you can register an `observeExpression` function with no `listener`.
+ *
+ *
+ * # `$watch` vs `$observe`
+ *
+ *
+ *
+ *
+ *
{@link angular.scope.$watch $watch()}
+ *
{@link angular.scope.$observe $observe()}
+ *
+ *
When to use it?
+ *
+ *
Purpose
+ *
Application behavior (including further model mutation) in response to a model
+ * mutation.
{@link angular.scope.$apply $apply} schedules
+ * {@link angular.scope.$flush $flush()} at some future time via
+ * {@link angular.service.$updateView $updateView}
+ *
+ *
API contract
+ *
+ *
Model mutation
+ *
allowed: detecting mutations requires one or mare calls to `watchExpression' per
+ * {@link angular.scope.$digest $digest()} cycle
+ *
not allowed: called once per {@link angular.scope.$flush $flush()} must be
+ * {@link http://en.wikipedia.org/wiki/Idempotence idempotent}
+ * (function without side-effects which can be called multiple times.)
+ *
+ *
+ *
Initial Value
+ *
uses the current value of `watchExpression` as the initial value. Does not fire on
+ * initial call to {@link angular.scope.$digest $digest()}, unless `watchExpression` has
+ * changed form the initial value.
+ *
fires on first run of {@link angular.scope.$flush $flush()} regardless of value of
+ * `observeExpression`
+ *
+ *
+ *
+ * # Example
+
+ var scope = angular.scope();
+ scope.name = 'misko';
+ scope.counter = 0;
- /**
- * @workInProgress
- * @ngdoc function
- * @name angular.scope.$become
- * @function
- * @deprecated This method will be removed before 1.0
- *
- * @description
- * Modifies the scope to act like an instance of the given class by:
- *
- * - copying the class's prototype methods
- * - applying the class's initialization function to the scope instance (without using the new
- * operator)
- *
- * That makes the scope be a `this` for the given class's methods — effectively an instance of
- * the given class with additional (scope) stuff. A scope can later `$become` another class.
- *
- * `$become` gets used to make the current scope act like an instance of a controller class.
- * This allows for use of a controller class in two ways.
- *
- * - as an ordinary JavaScript class for standalone testing, instantiated using the new
- * operator, with no attached view.
- * - as a controller for an angular model stored in a scope, "instantiated" by
- * `scope.$become(ControllerClass)`.
- *
- * Either way, the controller's methods refer to the model variables like `this.name`. When
- * stored in a scope, the model supports data binding. When bound to a view, {{name}} in the
- * HTML template refers to the same variable.
- */
- $become: function(Class) {
- if (isFunction(Class)) {
- instance.constructor = Class;
- forEach(Class.prototype, function(fn, name){
- instance[name] = bind(instance, fn);
- });
- instance.$service.invoke(instance, Class, slice.call(arguments, 1, arguments.length));
+ expect(scope.counter).toEqual(0);
+ scope.$flush('name', function(scope, newValue, oldValue) { counter = counter + 1; });
+ expect(scope.counter).toEqual(0);
- //TODO: backwards compatibility hack, remove when we don't depend on init methods
- if (isFunction(Class.prototype.init)) {
- instance.init();
- }
- }
- },
+ scope.$flush();
+ // no variable change
+ expect(scope.counter).toEqual(0);
- /**
- * @workInProgress
- * @ngdoc function
- * @name angular.scope.$new
- * @function
- *
- * @description
- * Creates a new {@link angular.scope scope}, that:
- *
- * - is a child of the current scope
- * - will {@link angular.scope.$become $become} of type specified via `constructor`
- *
- * @param {function()} constructor Constructor function of the type the new scope should assume.
- * @returns {Object} The newly created child scope.
- *
- */
- $new: function(constructor) {
- var child = createScope(instance);
- child.$become.apply(instance, concat([constructor], arguments, 1));
- instance.$onEval(child.$eval);
- return child;
+ scope.name = 'adam';
+ scope.$flush();
+ expect(scope.counter).toEqual(1);
+
+ *
+ * @param {(function()|string)} observeExpression Expression that is evaluated on each
+ * {@link angular.scope.$flush $flush} cycle. A change in the return value triggers a
+ * call to the `listener`.
+ *
+ * - `string`: Evaluated as {@link guide/dev_guide.expressions expression}
+ * - `function(scope)`: called with current `scope` as a parameter.
+ * @param {(function()|string)=} listener Callback called whenever the return value of
+ * the `observeExpression` changes.
+ *
+ * - `string`: Evaluated as {@link guide/dev_guide.expressions expression}
+ * - `function(scope, newValue, oldValue)`: called with current `scope` an previous and
+ * current values as parameters.
+ */
+ $observe: function(watchExp, listener) {
+ var array = this.$$observers;
+
+ if (!array) {
+ array = this.$$observers = [];
}
+ // we use unshift since we use a while loop in $flush for speed.
+ // the while loop reads in reverse order.
+ array.unshift({
+ fn: compileToFn(listener || noop, 'listener'),
+ last: NaN,
+ get: compileToFn(watchExp, 'watch')
+ });
+ },
- });
+ /**
+ * @workInProgress
+ * @ngdoc function
+ * @name angular.scope.$flush
+ * @function
+ *
+ * @description
+ * Process all of the {@link angular.scope.$observe observers} of the current scope
+ * and its children.
+ *
+ * Usually you don't call `$flush()` directly in
+ * {@link angular.directive.ng:controller controllers} or in {@link angular.directive directives}.
+ * Instead a call to {@link angular.scope.$apply $apply()} (typically from within a
+ * {@link angular.directive directive}) will scheduled a call to `$flush()` (with the
+ * help of the {@link angular.service.$updateView $updateView} service).
+ *
+ * If you want to be notified whenever `$flush()` is called,
+ * you can register a `observeExpression` function with {@link angular.scope.$observe $observe()}
+ * with no `listener`.
+ *
+ * You may have a need to call `$flush()` from within unit-tests, to simulate the scope
+ * life-cycle.
+ *
+ * # Example
+
+ var scope = angular.scope();
+ scope.name = 'misko';
+ scope.counter = 0;
- if (!parent.$root) {
- instance.$root = instance;
- instance.$parent = instance;
+ expect(scope.counter).toEqual(0);
+ scope.$flush('name', function(scope, newValue, oldValue) { counter = counter + 1; });
+ expect(scope.counter).toEqual(0);
- /**
- * @workInProgress
- * @ngdoc function
- * @name angular.scope.$service
- * @function
- *
- * @description
- * Provides access to angular's dependency injector and
- * {@link angular.service registered services}. In general the use of this api is discouraged,
- * except for tests and components that currently don't support dependency injection (widgets,
- * filters, etc).
- *
- * @param {string} serviceId String ID of the service to return.
- * @returns {*} Value, object or function returned by the service factory function if any.
- */
- (instance.$service = createInjector(instance, providers, instanceCache)).eager();
+ scope.$flush();
+ // no variable change
+ expect(scope.counter).toEqual(0);
+
+ scope.name = 'adam';
+ scope.$flush();
+ expect(scope.counter).toEqual(1);
+
+ *
+ */
+ $flush: function() {
+ var observers = this.$$observers,
+ child,
+ length,
+ observer, value, last;
+
+ if (this.$$phase) {
+ throw Error(this.$$phase + ' already in progress');
+ }
+ this.$$phase = '$flush';
+ if (observers) {
+ // process our watches
+ length = observers.length;
+ while (length--) {
+ try {
+ observer = observers[length];
+ // Most common watches are on primitives, in which case we can short
+ // circuit it with === operator, only when === fails do we use .equals
+ if ((value = observer.get(this)) !== (last = observer.last) && !equals(value, last)) {
+ observer.fn(this, observer.last = copy(value), last);
+ }
+ } catch (e){
+ this.$service('$exceptionHandler')(e);
+ }
+ }
+ }
+ // observers can create new children
+ child = this.$$childHead;
+ while(child) {
+ child.$flush();
+ child = child.$$nextSibling;
+ }
+ this.$$phase = null;
+ },
+
+ /**
+ * @workInProgress
+ * @ngdoc function
+ * @name angular.scope.$destroy
+ * @function
+ *
+ * @description
+ * Remove the current scope (and all of its children) from the parent scope. Removal implies
+ * that calls to {@link angular.scope.$digest $digest()} and
+ * {@link angular.scope.$flush $flush()} will no longer propagate to the current scope and its
+ * children. Removal also implies that the current scope is eligible for garbage collection.
+ *
+ * The `$destroy()` is usually used by directives such as
+ * {@link angular.widget.@ng:repeat ng:repeat} for managing the unrolling of the loop.
+ *
+ */
+ $destroy: function() {
+ if (this.$root == this) return; // we can't remove the root node;
+ var parent = this.$parent;
+ var child = parent.$$childHead;
+ var lastChild = null;
+ var nextChild = null;
+ // We have to do a linear search, since we don't have doubly link list.
+ // But this is intentional since removals are rare, and doubly link list is not free.
+ while(child) {
+ if (child == this) {
+ nextChild = child.$$nextSibling;
+ if (parent.$$childHead == child) {
+ parent.$$childHead = nextChild;
+ }
+ if (lastChild) {
+ lastChild.$$nextSibling = nextChild;
+ }
+ if (parent.$$childTail == child) {
+ parent.$$childTail = lastChild;
+ }
+ return; // stop iterating we found it
+ } else {
+ lastChild = child;
+ child = child.$$nextSibling;
+ }
+ }
+ },
+
+ /**
+ * @workInProgress
+ * @ngdoc function
+ * @name angular.scope.$eval
+ * @function
+ *
+ * @description
+ * Executes the expression on the current scope returning the result. Any exceptions in the
+ * expression are propagated (uncaught). This is useful when evaluating engular expressions.
+ *
+ * # Example
+