app/assets/javascripts/angular-scenario.js in angularjs-on-rails-0.1.1 vs app/assets/javascripts/angular-scenario.js in angularjs-on-rails-0.1.2
- old
+ new
@@ -9788,11 +9788,11 @@
}
})( window );
/**
- * @license AngularJS v1.2.18
+ * @license AngularJS v1.2.21
* (c) 2010-2014 Google, Inc. http://angularjs.org
* License: MIT
*/
(function(window, document){
var _jQuery = window.jQuery.noConflict(true);
@@ -9858,11 +9858,11 @@
return arg;
}
return match;
});
- message = message + '\nhttp://errors.angularjs.org/1.2.18/' +
+ message = message + '\nhttp://errors.angularjs.org/1.2.21/' +
(module ? module + '/' : '') + code;
for (i = 2; i < arguments.length; i++) {
message = message + (i == 2 ? '?' : '&') + 'p' + (i-2) + '=' +
encodeURIComponent(stringify(arguments[i]));
}
@@ -9870,92 +9870,92 @@
return new Error(message);
};
}
/* We need to tell jshint what variables are being exported */
-/* global
- -angular,
- -msie,
- -jqLite,
- -jQuery,
- -slice,
- -push,
- -toString,
- -ngMinErr,
- -angularModule,
- -nodeName_,
- -uid,
+/* global angular: true,
+ msie: true,
+ jqLite: true,
+ jQuery: true,
+ slice: true,
+ push: true,
+ toString: true,
+ ngMinErr: true,
+ angularModule: true,
+ nodeName_: true,
+ uid: true,
+ VALIDITY_STATE_PROPERTY: true,
- -lowercase,
- -uppercase,
- -manualLowercase,
- -manualUppercase,
- -nodeName_,
- -isArrayLike,
- -forEach,
- -sortedKeys,
- -forEachSorted,
- -reverseParams,
- -nextUid,
- -setHashKey,
- -extend,
- -int,
- -inherit,
- -noop,
- -identity,
- -valueFn,
- -isUndefined,
- -isDefined,
- -isObject,
- -isString,
- -isNumber,
- -isDate,
- -isArray,
- -isFunction,
- -isRegExp,
- -isWindow,
- -isScope,
- -isFile,
- -isBlob,
- -isBoolean,
- -trim,
- -isElement,
- -makeMap,
- -map,
- -size,
- -includes,
- -indexOf,
- -arrayRemove,
- -isLeafNode,
- -copy,
- -shallowCopy,
- -equals,
- -csp,
- -concat,
- -sliceArgs,
- -bind,
- -toJsonReplacer,
- -toJson,
- -fromJson,
- -toBoolean,
- -startingTag,
- -tryDecodeURIComponent,
- -parseKeyValue,
- -toKeyValue,
- -encodeUriSegment,
- -encodeUriQuery,
- -angularInit,
- -bootstrap,
- -snake_case,
- -bindJQuery,
- -assertArg,
- -assertArgFn,
- -assertNotHasOwnProperty,
- -getter,
- -getBlockElements,
- -hasOwnProperty,
-
+ lowercase: true,
+ uppercase: true,
+ manualLowercase: true,
+ manualUppercase: true,
+ nodeName_: true,
+ isArrayLike: true,
+ forEach: true,
+ sortedKeys: true,
+ forEachSorted: true,
+ reverseParams: true,
+ nextUid: true,
+ setHashKey: true,
+ extend: true,
+ int: true,
+ inherit: true,
+ noop: true,
+ identity: true,
+ valueFn: true,
+ isUndefined: true,
+ isDefined: true,
+ isObject: true,
+ isString: true,
+ isNumber: true,
+ isDate: true,
+ isArray: true,
+ isFunction: true,
+ isRegExp: true,
+ isWindow: true,
+ isScope: true,
+ isFile: true,
+ isBlob: true,
+ isBoolean: true,
+ isPromiseLike: true,
+ trim: true,
+ isElement: true,
+ makeMap: true,
+ map: true,
+ size: true,
+ includes: true,
+ indexOf: true,
+ arrayRemove: true,
+ isLeafNode: true,
+ copy: true,
+ shallowCopy: true,
+ equals: true,
+ csp: true,
+ concat: true,
+ sliceArgs: true,
+ bind: true,
+ toJsonReplacer: true,
+ toJson: true,
+ fromJson: true,
+ toBoolean: true,
+ startingTag: true,
+ tryDecodeURIComponent: true,
+ parseKeyValue: true,
+ toKeyValue: true,
+ encodeUriSegment: true,
+ encodeUriQuery: true,
+ angularInit: true,
+ bootstrap: true,
+ snake_case: true,
+ bindJQuery: true,
+ assertArg: true,
+ assertArgFn: true,
+ assertNotHasOwnProperty: true,
+ getter: true,
+ getBlockElements: true,
+ hasOwnProperty: true,
*/
////////////////////////////////////
/**
@@ -9971,10 +9971,14 @@
* components available within this core module.
*
* <div doc-module-components="ng"></div>
*/
+// The name of a form control's ValidityState property.
+// This is used so that it's possible for internal tests to create mock ValidityStates.
+var VALIDITY_STATE_PROPERTY = 'validity';
+
/**
* @ngdoc function
* @name angular.lowercase
* @module ng
* @kind function
@@ -10106,15 +10110,16 @@
// as on IE8 the result of querySelectorAll is an object without a hasOwnProperty function
if (key != 'prototype' && key != 'length' && key != 'name' && (!obj.hasOwnProperty || obj.hasOwnProperty(key))) {
iterator.call(context, obj[key], key);
}
}
- } else if (obj.forEach && obj.forEach !== forEach) {
- obj.forEach(iterator, context);
- } else if (isArrayLike(obj)) {
- for (key = 0; key < obj.length; key++)
+ } else if (isArray(obj) || isArrayLike(obj)) {
+ for (key = 0; key < obj.length; key++) {
iterator.call(context, obj[key], key);
+ }
+ } else if (obj.forEach && obj.forEach !== forEach) {
+ obj.forEach(iterator, context);
} else {
for (key in obj) {
if (obj.hasOwnProperty(key)) {
iterator.call(context, obj[key], key);
}
@@ -10447,10 +10452,15 @@
function isBoolean(value) {
return typeof value === 'boolean';
}
+function isPromiseLike(obj) {
+ return obj && isFunction(obj.then);
+}
+
+
var trim = (function() {
// native trim is way faster: http://jsperf.com/angular-trim-test
// but IE doesn't have it... :-(
// TODO: we should move this into IE/ES5 polyfill
if (!String.prototype.trim) {
@@ -10595,13 +10605,13 @@
* @param {(Object|Array)=} destination Destination into which the source is copied. If
* provided, must be of the same type as `source`.
* @returns {*} The copy or updated `destination`, if `destination` was specified.
*
* @example
- <example>
+ <example module="copyExample">
<file name="index.html">
- <div ng-controller="Controller">
+ <div ng-controller="ExampleController">
<form novalidate class="simple-form">
Name: <input type="text" ng-model="user.name" /><br />
E-mail: <input type="email" ng-model="user.email" /><br />
Gender: <input type="radio" ng-model="user.gender" value="male" />male
<input type="radio" ng-model="user.gender" value="female" />female<br />
@@ -10611,25 +10621,26 @@
<pre>form = {{user | json}}</pre>
<pre>master = {{master | json}}</pre>
</div>
<script>
- function Controller($scope) {
- $scope.master= {};
+ angular.module('copyExample', [])
+ .controller('ExampleController', ['$scope', function($scope) {
+ $scope.master= {};
- $scope.update = function(user) {
- // Example with 1 argument
- $scope.master= angular.copy(user);
- };
+ $scope.update = function(user) {
+ // Example with 1 argument
+ $scope.master= angular.copy(user);
+ };
- $scope.reset = function() {
- // Example with 2 arguments
- angular.copy($scope.master, $scope.user);
- };
+ $scope.reset = function() {
+ // Example with 2 arguments
+ angular.copy($scope.master, $scope.user);
+ };
- $scope.reset();
- }
+ $scope.reset();
+ }]);
</script>
</file>
</example>
*/
function copy(source, destination, stackSource, stackDest) {
@@ -10644,11 +10655,12 @@
if (isArray(source)) {
destination = copy(source, [], stackSource, stackDest);
} else if (isDate(source)) {
destination = new Date(source.getTime());
} else if (isRegExp(source)) {
- destination = new RegExp(source.source);
+ destination = new RegExp(source.source, source.toString().match(/[^\/]*$/)[0]);
+ destination.lastIndex = source.lastIndex;
} else if (isObject(source)) {
destination = copy(source, {}, stackSource, stackDest);
}
}
} else {
@@ -10788,18 +10800,31 @@
}
}
return false;
}
+var csp = function() {
+ if (isDefined(csp.isActive_)) return csp.isActive_;
-function csp() {
- return (document.securityPolicy && document.securityPolicy.isActive) ||
- (document.querySelector &&
- !!(document.querySelector('[ng-csp]') || document.querySelector('[data-ng-csp]')));
-}
+ var active = !!(document.querySelector('[ng-csp]') ||
+ document.querySelector('[data-ng-csp]'));
+ if (!active) {
+ try {
+ /* jshint -W031, -W054 */
+ new Function('');
+ /* jshint +W031, +W054 */
+ } catch (e) {
+ active = true;
+ }
+ }
+ return (csp.isActive_ = active);
+};
+
+
+
function concat(array1, array2, index) {
return array1.concat(slice.call(array2, index));
}
function sliceArgs(args, startIndex) {
@@ -10965,15 +10990,15 @@
*/
function parseKeyValue(/**string*/keyValue) {
var obj = {}, key_value, key;
forEach((keyValue || "").split('&'), function(keyValue) {
if ( keyValue ) {
- key_value = keyValue.split('=');
+ key_value = keyValue.replace(/\+/g,'%20').split('=');
key = tryDecodeURIComponent(key_value[0]);
if ( isDefined(key) ) {
var val = isDefined(key_value[1]) ? tryDecodeURIComponent(key_value[1]) : true;
- if (!obj[key]) {
+ if (!hasOwnProperty.call(obj, key)) {
obj[key] = val;
} else if(isArray(obj[key])) {
obj[key].push(val);
} else {
obj[key] = [obj[key],val];
@@ -11143,11 +11168,11 @@
* Note that ngScenario-based end-to-end tests cannot use this function to bootstrap manually.
* They must use {@link ng.directive:ngApp ngApp}.
*
* Angular will detect if it has been loaded into the browser more than once and only allow the
* first loaded script to be bootstrapped and will report a warning to the browser console for
- * each of the subsequent scripts. This prevents strange results in applications, where otherwise
+ * each of the subsequent scripts. This prevents strange results in applications, where otherwise
* multiple instances of Angular try to work on the DOM.
*
* <example name="multi-bootstrap" module="multi-bootstrap">
* <file name="index.html">
* <script src="../../../angular.js"></script>
@@ -11273,11 +11298,11 @@
if (acceptArrayAnnotation && isArray(arg)) {
arg = arg[arg.length - 1];
}
assertArg(isFunction(arg), name, 'not a function, got ' +
- (arg && typeof arg == 'object' ? arg.constructor.name || 'Object' : typeof arg));
+ (arg && typeof arg === 'object' ? arg.constructor.name || 'Object' : typeof arg));
return arg;
}
/**
* throw error if the name given is hasOwnProperty
@@ -11650,16 +11675,15 @@
};
});
}
-/* global
- angularModule: true,
- version: true,
+/* global angularModule: true,
+ version: true,
- $LocaleProvider,
- $CompileProvider,
+ $LocaleProvider,
+ $CompileProvider,
htmlAnchorDirective,
inputDirective,
inputDirective,
formDirective,
@@ -11743,15 +11767,15 @@
* - `minor` – `{number}` – Minor version number, such as "9".
* - `dot` – `{number}` – Dot version number, such as "18".
* - `codeName` – `{string}` – Code name of the release, such as "jiggling-armfat".
*/
var version = {
- full: '1.2.18', // all of these placeholder strings will be replaced by grunt's
+ full: '1.2.21', // all of these placeholder strings will be replaced by grunt's
major: 1, // package task
minor: 2,
- dot: 18,
- codeName: 'ear-extendability'
+ dot: 21,
+ codeName: 'wizard-props'
};
function publishExternalAPI(angular){
extend(angular, {
@@ -11871,16 +11895,14 @@
});
}
]);
}
-/* global
-
- -JQLitePrototype,
- -addEventListenerFn,
- -removeEventListenerFn,
- -BOOLEAN_ATTR
+/* global JQLitePrototype: true,
+ addEventListenerFn: true,
+ removeEventListenerFn: true,
+ BOOLEAN_ATTR: true
*/
//////////////////////////////////
//JQLite
//////////////////////////////////
@@ -11969,12 +11991,13 @@
*
* @param {string|DOMElement} element HTML string or DOMElement to be wrapped into jQuery.
* @returns {Object} jQuery object.
*/
+JQLite.expando = 'ng339';
+
var jqCache = JQLite.cache = {},
- jqName = JQLite.expando = 'ng' + new Date().getTime(),
jqId = 1,
addEventListenerFn = (window.document.addEventListener
? function(element, type, fn) {element.addEventListener(type, fn, false);}
: function(element, type, fn) {element.attachEvent('on' + type, fn);}),
removeEventListenerFn = (window.document.removeEventListener
@@ -12180,11 +12203,11 @@
});
}
}
function jqLiteRemoveData(element, name) {
- var expandoId = element[jqName],
+ var expandoId = element.ng339,
expandoStore = jqCache[expandoId];
if (expandoStore) {
if (name) {
delete jqCache[expandoId].data[name];
@@ -12194,21 +12217,21 @@
if (expandoStore.handle) {
expandoStore.events.$destroy && expandoStore.handle({}, '$destroy');
jqLiteOff(element);
}
delete jqCache[expandoId];
- element[jqName] = undefined; // ie does not allow deletion of attributes on elements.
+ element.ng339 = undefined; // don't delete DOM expandos. IE and Chrome don't like it
}
}
function jqLiteExpandoStore(element, key, value) {
- var expandoId = element[jqName],
+ var expandoId = element.ng339,
expandoStore = jqCache[expandoId || -1];
if (isDefined(value)) {
if (!expandoStore) {
- element[jqName] = expandoId = jqNextId();
+ element.ng339 = expandoId = jqNextId();
expandoStore = jqCache[expandoId] = {};
}
expandoStore[key] = value;
} else {
return expandoStore && expandoStore[key];
@@ -12289,29 +12312,26 @@
function jqLiteController(element, name) {
return jqLiteInheritedData(element, '$' + (name || 'ngController' ) + 'Controller');
}
function jqLiteInheritedData(element, name, value) {
- element = jqLite(element);
-
// if element is the document object work with the html element instead
// this makes $(document).scope() possible
- if(element[0].nodeType == 9) {
- element = element.find('html');
+ if(element.nodeType == 9) {
+ element = element.documentElement;
}
var names = isArray(name) ? name : [name];
- while (element.length) {
- var node = element[0];
+ while (element) {
for (var i = 0, ii = names.length; i < ii; i++) {
- if ((value = element.data(names[i])) !== undefined) return value;
+ if ((value = jqLite.data(element, names[i])) !== undefined) return value;
}
// If dealing with a document fragment node with a host element, and no parent, use the host
// element as the parent. This enables directives within a Shadow DOM or polyfilled Shadow DOM
// to lookup parent controllers.
- element = jqLite(node.parentNode || (node.nodeType === 11 && node.host));
+ element = element.parentNode || (element.nodeType === 11 && element.host);
}
}
function jqLiteEmpty(element) {
for (var i = 0, childNodes = element.childNodes; i < childNodes.length; i++) {
@@ -12384,20 +12404,27 @@
return booleanAttr && BOOLEAN_ELEMENTS[element.nodeName] && booleanAttr;
}
forEach({
data: jqLiteData,
+ removeData: jqLiteRemoveData
+}, function(fn, name) {
+ JQLite[name] = fn;
+});
+
+forEach({
+ data: jqLiteData,
inheritedData: jqLiteInheritedData,
scope: function(element) {
// Can't use jqLiteData here directly so we stay compatible with jQuery!
- return jqLite(element).data('$scope') || jqLiteInheritedData(element.parentNode || element, ['$isolateScope', '$scope']);
+ return jqLite.data(element, '$scope') || jqLiteInheritedData(element.parentNode || element, ['$isolateScope', '$scope']);
},
isolateScope: function(element) {
// Can't use jqLiteData here directly so we stay compatible with jQuery!
- return jqLite(element).data('$isolateScope') || jqLite(element).data('$isolateScopeNoTemplate');
+ return jqLite.data(element, '$isolateScope') || jqLite.data(element, '$isolateScopeNoTemplate');
},
controller: jqLiteController,
injector: function(element) {
@@ -12821,20 +12848,22 @@
},
clone: jqLiteClone,
triggerHandler: function(element, eventName, eventData) {
- var eventFns = (jqLiteExpandoStore(element, 'events') || {})[eventName];
+ // Copy event handlers in case event handlers array is modified during execution.
+ var eventFns = (jqLiteExpandoStore(element, 'events') || {})[eventName],
+ eventFnsCopy = shallowCopy(eventFns || []);
eventData = eventData || [];
var event = [{
preventDefault: noop,
stopPropagation: noop
}];
- forEach(eventFns, function(fn) {
+ forEach(eventFnsCopy, function(fn) {
fn.apply(element, event.concat(eventData));
});
}
}, function(fn, name){
/**
@@ -12871,20 +12900,20 @@
*
* @param obj
* @returns {string} hash string such that the same input will have the same hash string.
* The resulting string key is in 'type:hashKey' format.
*/
-function hashKey(obj) {
+function hashKey(obj, nextUidFn) {
var objType = typeof obj,
key;
- if (objType == 'object' && obj !== null) {
+ if (objType == 'function' || (objType == 'object' && obj !== null)) {
if (typeof (key = obj.$$hashKey) == 'function') {
// must invoke on object to keep the right this
key = obj.$$hashKey();
} else if (key === undefined) {
- key = obj.$$hashKey = nextUid();
+ key = obj.$$hashKey = (nextUidFn || nextUid)();
}
} else {
key = obj;
}
@@ -12892,37 +12921,43 @@
}
/**
* HashMap which can use objects as keys
*/
-function HashMap(array){
+function HashMap(array, isolatedUid) {
+ if (isolatedUid) {
+ var uid = 0;
+ this.nextUid = function() {
+ return ++uid;
+ };
+ }
forEach(array, this.put, this);
}
HashMap.prototype = {
/**
* Store key value pair
* @param key key to store can be any type
* @param value value to store can be any type
*/
put: function(key, value) {
- this[hashKey(key)] = value;
+ this[hashKey(key, this.nextUid)] = value;
},
/**
* @param key
* @returns {Object} the value for the key
*/
get: function(key) {
- return this[hashKey(key)];
+ return this[hashKey(key, this.nextUid)];
},
/**
* Remove the key/value pair
* @param key
*/
remove: function(key) {
- var value = this[key = hashKey(key)];
+ var value = this[key = hashKey(key, this.nextUid)];
delete this[key];
return value;
}
};
@@ -12996,11 +13031,11 @@
var $inject,
fnText,
argDecl,
last;
- if (typeof fn == 'function') {
+ if (typeof fn === 'function') {
if (!($inject = fn.$inject)) {
$inject = [];
if (fn.length) {
fnText = fn.toString().replace(STRIP_COMMENTS, '');
argDecl = fnText.match(FN_ARGS);
@@ -13209,11 +13244,11 @@
/**
- * @ngdoc object
+ * @ngdoc service
* @name $provide
*
* @description
*
* The {@link auto.$provide $provide} service has a number of methods for registering components
@@ -13515,11 +13550,11 @@
function createInjector(modulesToLoad) {
var INSTANTIATING = {},
providerSuffix = 'Provider',
path = [],
- loadedModules = new HashMap(),
+ loadedModules = new HashMap([], true),
providerCache = {
$provide: {
provider: supportObject(provider),
factory: supportObject(factory),
service: supportObject(service),
@@ -13686,12 +13721,11 @@
locals && locals.hasOwnProperty(key)
? locals[key]
: getService(key)
);
}
- if (!fn.$inject) {
- // this means that we must be an array.
+ if (isArray(fn)) {
fn = fn[length];
}
// http://jsperf.com/angularjs-invoke-apply-vs-switch
// #5388
@@ -15020,11 +15054,11 @@
* * `&` or `&attr` - provides a way to execute an expression in the context of the parent scope.
* If no `attr` name is specified then the attribute name is assumed to be the same as the
* local name. Given `<widget my-attr="count = count + value">` and widget definition of
* `scope: { localFn:'&myAttr' }`, then isolate scope property `localFn` will point to
* a function wrapper for the `count = count + value` expression. Often it's desirable to
- * pass data from the isolated scope via an expression and to the parent scope, this can be
+ * pass data from the isolated scope via an expression to the parent scope, this can be
* done by passing a map of local variable names and values into the expression wrapper fn.
* For example, if the expression is `increment(amount)` then we can specify the amount value
* by calling the `localFn` as `localFn({amount: 22})`.
*
*
@@ -15071,20 +15105,22 @@
* * `C` - Class: `<div class="my-directive: exp;"></div>`
* * `M` - Comment: `<!-- directive: my-directive exp -->`
*
*
* #### `template`
- * replace the current element with the contents of the HTML. The replacement process
- * migrates all of the attributes / classes from the old element to the new one. See the
- * {@link guide/directive#creating-custom-directives_creating-directives_template-expanding-directive
- * Directives Guide} for an example.
+ * HTML markup that may:
+ * * Replace the contents of the directive's element (defualt).
+ * * Replace the directive's element itself (if `replace` is true - DEPRECATED).
+ * * Wrap the contents of the directive's element (if `transclude` is true).
*
- * You can specify `template` as a string representing the template or as a function which takes
- * two arguments `tElement` and `tAttrs` (described in the `compile` function api below) and
- * returns a string value representing the template.
+ * Value may be:
*
+ * * A string. For example `<div red-on-hover>{{delete_str}}</div>`.
+ * * A function which takes two arguments `tElement` and `tAttrs` (described in the `compile`
+ * function api below) and returns a string value.
*
+ *
* #### `templateUrl`
* Same as `template` but the template is loaded from the specified URL. Because
* the template loading is asynchronous the compilation/linking is suspended until the template
* is loaded.
*
@@ -15093,15 +15129,18 @@
* a string value representing the url. In either case, the template URL is passed through {@link
* api/ng.$sce#getTrustedResourceUrl $sce.getTrustedResourceUrl}.
*
*
* #### `replace` ([*DEPRECATED*!], will be removed in next major release)
- * specify where the template should be inserted. Defaults to `false`.
+ * specify what the template should replace. Defaults to `false`.
*
- * * `true` - the template will replace the current element.
- * * `false` - the template will replace the contents of the current element.
+ * * `true` - the template will replace the directive's element.
+ * * `false` - the template will replace the contents of the directive's element.
*
+ * The replacement process migrates all of the attributes / classes from the old element to the new
+ * one. See the {@link guide/directive#creating-custom-directives_creating-directives_template-expanding-directive
+ * Directives Guide} for an example.
*
* #### `transclude`
* compile the content of the element and make it available to the directive.
* Typically used with {@link ng.directive:ngTransclude
* ngTransclude}. The advantage of transclusion is that the linking function receives a
@@ -15111,10 +15150,15 @@
* be bound to the parent (pre-`isolate`) scope.
*
* * `true` - transclude the content of the directive.
* * `'element'` - transclude the whole element including any directives defined at lower priority.
*
+ * <div class="alert alert-warning">
+ * **Note:** When testing an element transclude directive you must not place the directive at the root of the
+ * DOM fragment that is being compiled. See {@link guide/unit-testing#testing-transclusion-directives
+ * Testing Transclusion Directives}.
+ * </div>
*
* #### `compile`
*
* ```js
* function compile(tElement, tAttrs, transclude) { ... }
@@ -15247,14 +15291,14 @@
* <div class="alert alert-warning">
* **Note**: Typically directives are registered with `module.directive`. The example below is
* to illustrate how `$compile` works.
* </div>
*
- <example module="compile">
+ <example module="compileExample">
<file name="index.html">
<script>
- angular.module('compile', [], function($compileProvider) {
+ angular.module('compileExample', [], function($compileProvider) {
// configure new 'compile' directive by passing a directive
// factory function. The factory function injects the '$compile'
$compileProvider.directive('compile', function($compile) {
// directive factory creates a link function
return function(scope, element, attrs) {
@@ -15274,19 +15318,18 @@
// we don't get into infinite loop compiling ourselves
$compile(element.contents())(scope);
}
);
};
- })
- });
-
- function Ctrl($scope) {
+ });
+ })
+ .controller('GreeterController', ['$scope', function($scope) {
$scope.name = 'Angular';
$scope.html = 'Hello {{name}}';
- }
+ }]);
</script>
- <div ng-controller="Ctrl">
+ <div ng-controller="GreeterController">
<input ng-model="name"> <br>
<textarea ng-model="html"></textarea> <br>
<div compile="html"></div>
</div>
</file>
@@ -15757,11 +15800,11 @@
? applyDirectivesToNode(directives, nodeList[i], attrs, transcludeFn, $rootElement,
null, [], [], previousCompileContext)
: null;
if (nodeLinkFn && nodeLinkFn.scope) {
- safeAddClass(jqLite(nodeList[i]), 'ng-scope');
+ safeAddClass(attrs.$$element, 'ng-scope');
}
childLinkFn = (nodeLinkFn && nodeLinkFn.terminal ||
!(childNodes = nodeList[i].childNodes) ||
!childNodes.length)
@@ -15779,11 +15822,11 @@
// return a linking function if we have found anything, null otherwise
return linkFnFound ? compositeLinkFn : null;
function compositeLinkFn(scope, nodeList, $rootElement, parentBoundTranscludeFn) {
- var nodeLinkFn, childLinkFn, node, $node, childScope, i, ii, n, childBoundTranscludeFn;
+ var nodeLinkFn, childLinkFn, node, childScope, i, ii, n, childBoundTranscludeFn;
// copy nodeList so that linking doesn't break due to live list updates.
var nodeListLength = nodeList.length,
stableNodeList = new Array(nodeListLength);
for (i = 0; i < nodeListLength; i++) {
@@ -15792,16 +15835,15 @@
for(i = 0, n = 0, ii = linkFns.length; i < ii; n++) {
node = stableNodeList[n];
nodeLinkFn = linkFns[i++];
childLinkFn = linkFns[i++];
- $node = jqLite(node);
if (nodeLinkFn) {
if (nodeLinkFn.scope) {
childScope = scope.$new();
- $node.data('$scope', childScope);
+ jqLite.data(node, '$scope', childScope);
} else {
childScope = scope;
}
if ( nodeLinkFn.transcludeOnThisElement ) {
@@ -15868,21 +15910,23 @@
// use the node name: <directive>
addDirective(directives,
directiveNormalize(nodeName_(node).toLowerCase()), 'E', maxPriority, ignoreDirective);
// iterate over the attributes
- for (var attr, name, nName, ngAttrName, value, nAttrs = node.attributes,
+ for (var attr, name, nName, ngAttrName, value, isNgAttr, nAttrs = node.attributes,
j = 0, jj = nAttrs && nAttrs.length; j < jj; j++) {
var attrStartName = false;
var attrEndName = false;
attr = nAttrs[j];
if (!msie || msie >= 8 || attr.specified) {
name = attr.name;
+ value = trim(attr.value);
+
// support ngAttr attribute binding
ngAttrName = directiveNormalize(name);
- if (NG_ATTR_BINDING.test(ngAttrName)) {
+ if (isNgAttr = NG_ATTR_BINDING.test(ngAttrName)) {
name = snake_case(ngAttrName.substr(6), '-');
}
var directiveNName = ngAttrName.replace(/(Start|End)$/, '');
if (ngAttrName === directiveNName + 'Start') {
@@ -15891,13 +15935,15 @@
name = name.substr(0, name.length - 6);
}
nName = directiveNormalize(name.toLowerCase());
attrsMap[nName] = name;
- attrs[nName] = value = trim(attr.value);
- if (getBooleanAttrName(node, nName)) {
- attrs[nName] = true; // presence means true
+ if (isNgAttr || !attrs.hasOwnProperty(nName)) {
+ attrs[nName] = value;
+ if (getBooleanAttrName(node, nName)) {
+ attrs[nName] = true; // presence means true
+ }
}
addAttrInterpolateDirective(node, directives, value, nName);
addDirective(directives, nName, 'A', maxPriority, ignoreDirective, attrStartName,
attrEndName);
}
@@ -16085,16 +16131,16 @@
}
if (directiveValue == 'element') {
hasElementTranscludeDirective = true;
terminalPriority = directive.priority;
- $template = groupScan(compileNode, attrStart, attrEnd);
+ $template = $compileNode;
$compileNode = templateAttrs.$$element =
jqLite(document.createComment(' ' + directiveName + ': ' +
templateAttrs[directiveName] + ' '));
compileNode = $compileNode[0];
- replaceWith(jqCollection, jqLite(sliceArgs($template)), compileNode);
+ replaceWith(jqCollection, sliceArgs($template), compileNode);
childTranscludeFn = compile($template, transcludeFn, terminalPriority,
replaceDirective && replaceDirective.name, {
// Don't pass in:
// - controllerDirectives - otherwise we'll create duplicates controllers
@@ -16267,33 +16313,30 @@
function nodeLinkFn(childLinkFn, scope, linkNode, $rootElement, boundTranscludeFn) {
var attrs, $element, i, ii, linkFn, controller, isolateScope, elementControllers = {}, transcludeFn;
- if (compileNode === linkNode) {
- attrs = templateAttrs;
- } else {
- attrs = shallowCopy(templateAttrs, new Attributes(jqLite(linkNode), templateAttrs.$attr));
- }
+ attrs = (compileNode === linkNode)
+ ? templateAttrs
+ : shallowCopy(templateAttrs, new Attributes(jqLite(linkNode), templateAttrs.$attr));
$element = attrs.$$element;
if (newIsolateScopeDirective) {
var LOCAL_REGEXP = /^\s*([@=&])(\??)\s*(\w*)\s*$/;
- var $linkNode = jqLite(linkNode);
isolateScope = scope.$new(true);
if (templateDirective && (templateDirective === newIsolateScopeDirective ||
templateDirective === newIsolateScopeDirective.$$originalDirective)) {
- $linkNode.data('$isolateScope', isolateScope) ;
+ $element.data('$isolateScope', isolateScope);
} else {
- $linkNode.data('$isolateScopeNoTemplate', isolateScope);
+ $element.data('$isolateScopeNoTemplate', isolateScope);
}
- safeAddClass($linkNode, 'ng-isolate-scope');
+ safeAddClass($element, 'ng-isolate-scope');
forEach(newIsolateScopeDirective.scope, function(definition, scopeName) {
var match = definition.match(LOCAL_REGEXP) || [],
attrName = match[3] || scopeName,
optional = (match[2] == '?'),
@@ -16991,11 +17034,11 @@
}
instance = $injector.instantiate(expression, locals);
if (identifier) {
- if (!(locals && typeof locals.$scope == 'object')) {
+ if (!(locals && typeof locals.$scope === 'object')) {
throw minErr('$controller')('noscp',
"Cannot export controller '{0}' as '{1}'! No $scope object provided via `locals`.",
constructor || expression.name, identifier);
}
@@ -17014,22 +17057,23 @@
*
* @description
* A {@link angular.element jQuery or jqLite} wrapper for the browser's `window.document` object.
*
* @example
- <example>
+ <example module="documentExample">
<file name="index.html">
- <div ng-controller="MainCtrl">
+ <div ng-controller="ExampleController">
<p>$document title: <b ng-bind="title"></b></p>
<p>window.document title: <b ng-bind="windowTitle"></b></p>
</div>
</file>
<file name="script.js">
- function MainCtrl($scope, $document) {
- $scope.title = $document[0].title;
- $scope.windowTitle = angular.element(window.document)[0].title;
- }
+ angular.module('documentExample', [])
+ .controller('ExampleController', ['$scope', '$document', function($scope, $document) {
+ $scope.title = $document[0].title;
+ $scope.windowTitle = angular.element(window.document)[0].title;
+ }]);
</file>
</example>
*/
function $DocumentProvider(){
this.$get = ['$window', function(window){
@@ -17092,15 +17136,11 @@
i = line.indexOf(':');
key = lowercase(trim(line.substr(0, i)));
val = trim(line.substr(i + 1));
if (key) {
- if (parsed[key]) {
- parsed[key] += ', ' + val;
- } else {
- parsed[key] = val;
- }
+ parsed[key] = parsed[key] ? parsed[key] + ', ' + val : val;
}
});
return parsed;
}
@@ -17158,16 +17198,43 @@
function isSuccess(status) {
return 200 <= status && status < 300;
}
+/**
+ * @ngdoc provider
+ * @name $httpProvider
+ * @description
+ * Use `$httpProvider` to change the default behavior of the {@link ng.$http $http} service.
+ * */
function $HttpProvider() {
var JSON_START = /^\s*(\[|\{[^\{])/,
JSON_END = /[\}\]]\s*$/,
PROTECTION_PREFIX = /^\)\]\}',?\n/,
CONTENT_TYPE_APPLICATION_JSON = {'Content-Type': 'application/json;charset=utf-8'};
+ /**
+ * @ngdoc property
+ * @name $httpProvider#defaults
+ * @description
+ *
+ * Object containing default values for all {@link ng.$http $http} requests.
+ *
+ * - **`defaults.xsrfCookieName`** - {string} - Name of cookie containing the XSRF token.
+ * Defaults value is `'XSRF-TOKEN'`.
+ *
+ * - **`defaults.xsrfHeaderName`** - {string} - Name of HTTP header to populate with the
+ * XSRF token. Defaults value is `'X-XSRF-TOKEN'`.
+ *
+ * - **`defaults.headers`** - {Object} - Default headers for all $http requests.
+ * Refer to {@link ng.$http#setting-http-headers $http} for documentation on
+ * setting default headers.
+ * - **`defaults.headers.common`**
+ * - **`defaults.headers.post`**
+ * - **`defaults.headers.put`**
+ * - **`defaults.headers.patch`**
+ **/
var defaults = this.defaults = {
// transform incoming response data
transformResponse: [function(data) {
if (isString(data)) {
// strip json vulnerability protection prefix
@@ -17653,13 +17720,13 @@
* @property {Array.<Object>} pendingRequests Array of config objects for currently pending
* requests. This is primarily meant to be used for debugging purposes.
*
*
* @example
-<example>
+<example module="httpExample">
<file name="index.html">
- <div ng-controller="FetchCtrl">
+ <div ng-controller="FetchController">
<select ng-model="method">
<option>GET</option>
<option>JSONP</option>
</select>
<input type="text" ng-model="url" size="80"/>
@@ -17677,34 +17744,36 @@
<pre>http status code: {{status}}</pre>
<pre>http response data: {{data}}</pre>
</div>
</file>
<file name="script.js">
- function FetchCtrl($scope, $http, $templateCache) {
- $scope.method = 'GET';
- $scope.url = 'http-hello.html';
+ angular.module('httpExample', [])
+ .controller('FetchController', ['$scope', '$http', '$templateCache',
+ function($scope, $http, $templateCache) {
+ $scope.method = 'GET';
+ $scope.url = 'http-hello.html';
- $scope.fetch = function() {
- $scope.code = null;
- $scope.response = null;
+ $scope.fetch = function() {
+ $scope.code = null;
+ $scope.response = null;
- $http({method: $scope.method, url: $scope.url, cache: $templateCache}).
- success(function(data, status) {
- $scope.status = status;
- $scope.data = data;
- }).
- error(function(data, status) {
- $scope.data = data || "Request failed";
- $scope.status = status;
- });
- };
+ $http({method: $scope.method, url: $scope.url, cache: $templateCache}).
+ success(function(data, status) {
+ $scope.status = status;
+ $scope.data = data;
+ }).
+ error(function(data, status) {
+ $scope.data = data || "Request failed";
+ $scope.status = status;
+ });
+ };
- $scope.updateModel = function(method, url) {
- $scope.method = method;
- $scope.url = url;
- };
- }
+ $scope.updateModel = function(method, url) {
+ $scope.method = method;
+ $scope.url = url;
+ };
+ }]);
</file>
<file name="http-hello.html">
Hello, $http!
</file>
<file name="protractor.js" type="protractor">
@@ -17754,11 +17823,11 @@
var serverRequest = function(config) {
headers = config.headers;
var reqData = transformData(config.data, headersGetter(headers), config.transformRequest);
// strip content-type if data is undefined
- if (isUndefined(config.data)) {
+ if (isUndefined(reqData)) {
forEach(headers, function(value, header) {
if (lowercase(header) === 'content-type') {
delete headers[header];
}
});
@@ -17823,14 +17892,10 @@
reqHeaders = extend({}, config.headers),
defHeaderName, lowercaseDefHeaderName, reqHeaderName;
defHeaders = extend({}, defHeaders.common, defHeaders[lowercase(config.method)]);
- // execute if header value is function
- execHeaders(defHeaders);
- execHeaders(reqHeaders);
-
// using for-in instead of forEach to avoid unecessary iteration after header has been found
defaultHeadersIteration:
for (defHeaderName in defHeaders) {
lowercaseDefHeaderName = lowercase(defHeaderName);
@@ -17841,10 +17906,12 @@
}
reqHeaders[defHeaderName] = defHeaders[defHeaderName];
}
+ // execute if header value is a function for merged headers
+ execHeaders(reqHeaders);
return reqHeaders;
function execHeaders(headers) {
var headerContent;
@@ -17906,11 +17973,11 @@
*
* @description
* Shortcut method to perform `JSONP` request.
*
* @param {string} url Relative or absolute URL specifying the destination of the request.
- * Should contain `JSON_CALLBACK` string.
+ * The name of the callback should be the string `JSON_CALLBACK`.
* @param {Object=} config Optional configuration object
* @returns {HttpPromise} Future object
*/
createShortMethods('get', 'delete', 'head', 'jsonp');
@@ -18006,11 +18073,11 @@
}
if (cache) {
cachedResp = cache.get(url);
if (isDefined(cachedResp)) {
- if (cachedResp.then) {
+ if (isPromiseLike(cachedResp)) {
// cached request has already been sent, but there is no response yet
cachedResp.then(removePendingReq, removePendingReq);
return cachedResp;
} else {
// serving from cache
@@ -18088,31 +18155,33 @@
}
}
function buildUrl(url, params) {
- if (!params) return url;
- var parts = [];
- forEachSorted(params, function(value, key) {
- if (value === null || isUndefined(value)) return;
- if (!isArray(value)) value = [value];
+ if (!params) return url;
+ var parts = [];
+ forEachSorted(params, function(value, key) {
+ if (value === null || isUndefined(value)) return;
+ if (!isArray(value)) value = [value];
- forEach(value, function(v) {
- if (isObject(v)) {
- v = toJson(v);
- }
- parts.push(encodeUriQuery(key) + '=' +
- encodeUriQuery(v));
- });
- });
- if(parts.length > 0) {
- url += ((url.indexOf('?') == -1) ? '?' : '&') + parts.join('&');
+ forEach(value, function(v) {
+ if (isObject(v)) {
+ if (isDate(v)){
+ v = v.toISOString();
+ } else if (isObject(v)) {
+ v = toJson(v);
+ }
}
- return url;
- }
-
-
+ parts.push(encodeUriQuery(key) + '=' +
+ encodeUriQuery(v));
+ });
+ });
+ if(parts.length > 0) {
+ url += ((url.indexOf('?') == -1) ? '?' : '&') + parts.join('&');
+ }
+ return url;
+ }
}];
}
function createXhr(method) {
//if IE and the method is not RFC2616 compliant, or if XMLHttpRequest
@@ -18193,25 +18262,32 @@
//
// we can't set xhr.onreadystatechange to undefined or delete it because that breaks IE8 (method=PATCH) and
// Safari respectively.
if (xhr && xhr.readyState == 4) {
var responseHeaders = null,
- response = null;
+ response = null,
+ statusText = '';
if(status !== ABORTED) {
responseHeaders = xhr.getAllResponseHeaders();
// responseText is the old-school way of retrieving response (supported by IE8 & 9)
// response/responseType properties were introduced in XHR Level2 spec (supported by IE10)
response = ('response' in xhr) ? xhr.response : xhr.responseText;
}
+ // Accessing statusText on an aborted xhr object will
+ // throw an 'c00c023f error' in IE9 and lower, don't touch it.
+ if (!(status === ABORTED && msie < 10)) {
+ statusText = xhr.statusText;
+ }
+
completeRequest(callback,
status || xhr.status,
response,
responseHeaders,
- xhr.statusText || '');
+ statusText);
}
};
if (withCredentials) {
xhr.withCredentials = true;
@@ -18237,11 +18313,11 @@
xhr.send(post || null);
}
if (timeout > 0) {
var timeoutId = $browserDefer(timeoutRequest, timeout);
- } else if (timeout && timeout.then) {
+ } else if (isPromiseLike(timeout)) {
timeout.then(timeoutRequest);
}
function timeoutRequest() {
@@ -18609,29 +18685,31 @@
* @param {boolean=} [invokeApply=true] If set to `false` skips model dirty checking, otherwise
* will invoke `fn` within the {@link ng.$rootScope.Scope#$apply $apply} block.
* @returns {promise} A promise which will be notified on each iteration.
*
* @example
- * <example module="time">
- * <file name="index.html">
- * <script>
- * function Ctrl2($scope,$interval) {
- * $scope.format = 'M/d/yy h:mm:ss a';
- * $scope.blood_1 = 100;
- * $scope.blood_2 = 120;
+ * <example module="intervalExample">
+ * <file name="index.html">
+ * <script>
+ * angular.module('intervalExample', [])
+ * .controller('ExampleController', ['$scope', '$interval',
+ * function($scope, $interval) {
+ * $scope.format = 'M/d/yy h:mm:ss a';
+ * $scope.blood_1 = 100;
+ * $scope.blood_2 = 120;
*
- * var stop;
- * $scope.fight = function() {
- * // Don't start a new fight if we are already fighting
- * if ( angular.isDefined(stop) ) return;
+ * var stop;
+ * $scope.fight = function() {
+ * // Don't start a new fight if we are already fighting
+ * if ( angular.isDefined(stop) ) return;
*
* stop = $interval(function() {
* if ($scope.blood_1 > 0 && $scope.blood_2 > 0) {
- * $scope.blood_1 = $scope.blood_1 - 3;
- * $scope.blood_2 = $scope.blood_2 - 4;
+ * $scope.blood_1 = $scope.blood_1 - 3;
+ * $scope.blood_2 = $scope.blood_2 - 4;
* } else {
- * $scope.stopFight();
+ * $scope.stopFight();
* }
* }, 100);
* };
*
* $scope.stopFight = function() {
@@ -18642,26 +18720,25 @@
* };
*
* $scope.resetFight = function() {
* $scope.blood_1 = 100;
* $scope.blood_2 = 120;
- * }
+ * };
*
* $scope.$on('$destroy', function() {
- * // Make sure that the interval is destroyed too
+ * // Make sure that the interval nis destroyed too
* $scope.stopFight();
* });
- * }
- *
- * angular.module('time', [])
- * // Register the 'myCurrentTime' directive factory method.
- * // We inject $interval and dateFilter service since the factory method is DI.
- * .directive('myCurrentTime', function($interval, dateFilter) {
+ * }])
+ * // Register the 'myCurrentTime' directive factory method.
+ * // We inject $interval and dateFilter service since the factory method is DI.
+ * .directive('myCurrentTime', ['$interval', 'dateFilter',
+ * function($interval, dateFilter) {
* // return the directive link function. (compile function not needed)
* return function(scope, element, attrs) {
* var format, // date format
- * stopTime; // so that we can cancel the time updates
+ * stopTime; // so that we can cancel the time updates
*
* // used to update the UI
* function updateTime() {
* element.text(dateFilter(new Date(), format));
* }
@@ -18673,32 +18750,32 @@
* });
*
* stopTime = $interval(updateTime, 1000);
*
* // listen on DOM destroy (removal) event, and cancel the next UI update
- * // to prevent updating time ofter the DOM element was removed.
+ * // to prevent updating time after the DOM element was removed.
* element.bind('$destroy', function() {
* $interval.cancel(stopTime);
* });
* }
- * });
- * </script>
+ * }]);
+ * </script>
*
- * <div>
- * <div ng-controller="Ctrl2">
- * Date format: <input ng-model="format"> <hr/>
- * Current time is: <span my-current-time="format"></span>
- * <hr/>
- * Blood 1 : <font color='red'>{{blood_1}}</font>
- * Blood 2 : <font color='red'>{{blood_2}}</font>
- * <button type="button" data-ng-click="fight()">Fight</button>
- * <button type="button" data-ng-click="stopFight()">StopFight</button>
- * <button type="button" data-ng-click="resetFight()">resetFight</button>
- * </div>
+ * <div>
+ * <div ng-controller="ExampleController">
+ * Date format: <input ng-model="format"> <hr/>
+ * Current time is: <span my-current-time="format"></span>
+ * <hr/>
+ * Blood 1 : <font color='red'>{{blood_1}}</font>
+ * Blood 2 : <font color='red'>{{blood_2}}</font>
+ * <button type="button" data-ng-click="fight()">Fight</button>
+ * <button type="button" data-ng-click="stopFight()">StopFight</button>
+ * <button type="button" data-ng-click="resetFight()">resetFight</button>
* </div>
+ * </div>
*
- * </file>
+ * </file>
* </example>
*/
function interval(fn, delay, count, invokeApply) {
var setInterval = $window.setInterval,
clearInterval = $window.clearInterval,
@@ -18741,11 +18818,11 @@
* @returns {boolean} Returns `true` if the task was successfully canceled.
*/
interval.cancel = function(promise) {
if (promise && promise.$$intervalId in intervals) {
intervals[promise.$$intervalId].reject('canceled');
- clearInterval(promise.$$intervalId);
+ $window.clearInterval(promise.$$intervalId);
delete intervals[promise.$$intervalId];
return true;
}
return false;
};
@@ -19251,18 +19328,21 @@
* of `$location` to the specified value.
*
* If the argument is a hash object containing an array of values, these values will be encoded
* as duplicate search parameters in the url.
*
- * @param {(string|Array<string>)=} paramValue If `search` is a string, then `paramValue` will
- * override only a single search property.
+ * @param {(string|Array<string>|boolean)=} paramValue If `search` is a string, then `paramValue`
+ * will override only a single search property.
*
* If `paramValue` is an array, it will override the property of the `search` component of
* `$location` specified via the first argument.
*
* If `paramValue` is `null`, the property specified via the first argument will be deleted.
*
+ * If `paramValue` is `true`, the property specified via the first argument will be added with no
+ * value nor trailing equal sign.
+ *
* @return {Object} If called with no arguments returns the parsed `search` object. If called with
* one or more arguments returns `$location` object itself.
*/
search: function(search, paramValue) {
switch (arguments.length) {
@@ -19270,10 +19350,15 @@
return this.$$search;
case 1:
if (isString(search)) {
this.$$search = parseKeyValue(search);
} else if (isObject(search)) {
+ // remove object undefined or null properties
+ forEach(search, function(value, key) {
+ if (value == null) delete search[key];
+ });
+
this.$$search = search;
} else {
throw $locationMinErr('isrcharg',
'The first argument of the `$location#search()` call must be a string or an object.');
}
@@ -19375,11 +19460,11 @@
function $LocationProvider(){
var hashPrefix = '',
html5Mode = false;
/**
- * @ngdoc property
+ * @ngdoc method
* @name $locationProvider#hashPrefix
* @description
* @param {string=} prefix Prefix for hash part (containing path and search)
* @returns {*} current value if used as getter or itself (chaining) if used as setter
*/
@@ -19391,11 +19476,11 @@
return hashPrefix;
}
};
/**
- * @ngdoc property
+ * @ngdoc method
* @name $locationProvider#html5Mode
* @description
* @param {boolean=} mode Use HTML5 strategy if available.
* @returns {*} current value if used as getter or itself (chaining) if used as setter
*/
@@ -19591,19 +19676,20 @@
*
* The default is to log `debug` messages. You can use
* {@link ng.$logProvider ng.$logProvider#debugEnabled} to change this.
*
* @example
- <example>
+ <example module="logExample">
<file name="script.js">
- function LogCtrl($scope, $log) {
- $scope.$log = $log;
- $scope.message = 'Hello World!';
- }
+ angular.module('logExample', [])
+ .controller('LogController', ['$scope', '$log', function($scope, $log) {
+ $scope.$log = $log;
+ $scope.message = 'Hello World!';
+ }]);
</file>
<file name="index.html">
- <div ng-controller="LogCtrl">
+ <div ng-controller="LogController">
<p>Reload this page with open console, enter text and hit the log button...</p>
Message:
<input type="text" ng-model="message"/>
<button ng-click="$log.log(message)">log</button>
<button ng-click="$log.warn(message)">warn</button>
@@ -19623,11 +19709,11 @@
function $LogProvider(){
var debug = true,
self = this;
/**
- * @ngdoc property
+ * @ngdoc method
* @name $logProvider#debugEnabled
* @description
* @param {boolean=} flag enable or disable debug level messages
* @returns {*} current value if used as getter or itself (chaining) if used as setter
*/
@@ -19749,36 +19835,31 @@
// access to $scope and locals. However, one can obtain the ability to execute arbitrary JS code by
// obtaining a reference to native JS functions such as the Function constructor.
//
// As an example, consider the following Angular expression:
//
-// {}.toString.constructor(alert("evil JS code"))
+// {}.toString.constructor('alert("evil JS code")')
//
-// We want to prevent this type of access. For the sake of performance, during the lexing phase we
-// disallow any "dotted" access to any member named "constructor".
-//
-// For reflective calls (a[b]) we check that the value of the lookup is not the Function constructor
-// while evaluating the expression, which is a stronger but more expensive test. Since reflective
-// calls are expensive anyway, this is not such a big deal compared to static dereferencing.
-//
// This sandboxing technique is not perfect and doesn't aim to be. The goal is to prevent exploits
// against the expression language, but not to prevent exploits that were enabled by exposing
// sensitive JavaScript or browser apis on Scope. Exposing such objects on a Scope is never a good
// practice and therefore we are not even trying to protect against interaction with an object
// explicitly exposed in this way.
//
-// A developer could foil the name check by aliasing the Function constructor under a different
-// name on the scope.
-//
// In general, it is not possible to access a Window object from an angular expression unless a
// window or some DOM object that has a reference to window is published onto a Scope.
+// Similarly we prevent invocations of function known to be dangerous, as well as assignments to
+// native objects.
+
function ensureSafeMemberName(name, fullExpression) {
- if (name === "constructor") {
+ if (name === "__defineGetter__" || name === "__defineSetter__"
+ || name === "__lookupGetter__" || name === "__lookupSetter__"
+ || name === "__proto__") {
throw $parseMinErr('isecfld',
- 'Referencing "constructor" field in Angular expressions is disallowed! Expression: {0}',
- fullExpression);
+ 'Attempting to access a disallowed field in Angular expressions! '
+ +'Expression: {0}', fullExpression);
}
return name;
}
function ensureSafeObject(obj, fullExpression) {
@@ -19796,15 +19877,38 @@
} else if (// isElement(obj)
obj.children && (obj.nodeName || (obj.prop && obj.attr && obj.find))) {
throw $parseMinErr('isecdom',
'Referencing DOM nodes in Angular expressions is disallowed! Expression: {0}',
fullExpression);
+ } else if (// block Object so that we can't get hold of dangerous Object.* methods
+ obj === Object) {
+ throw $parseMinErr('isecobj',
+ 'Referencing Object in Angular expressions is disallowed! Expression: {0}',
+ fullExpression);
}
}
return obj;
}
+var CALL = Function.prototype.call;
+var APPLY = Function.prototype.apply;
+var BIND = Function.prototype.bind;
+
+function ensureSafeFunction(obj, fullExpression) {
+ if (obj) {
+ if (obj.constructor === obj) {
+ throw $parseMinErr('isecfn',
+ 'Referencing Function in Angular expressions is disallowed! Expression: {0}',
+ fullExpression);
+ } else if (obj === CALL || obj === APPLY || (BIND && obj === BIND)) {
+ throw $parseMinErr('isecff',
+ 'Referencing call, apply or bind in Angular expressions is disallowed! Expression: {0}',
+ fullExpression);
+ }
+ }
+}
+
var OPERATORS = {
/* jshint bitwise : false */
'null':function(){return null;},
'true':function(){return true;},
'false':function(){return false;},
@@ -20080,15 +20184,11 @@
this.throwError('Invalid unicode escape [\\u' + hex + ']');
this.index += 4;
string += String.fromCharCode(parseInt(hex, 16));
} else {
var rep = ESCAPE[ch];
- if (rep) {
- string += rep;
- } else {
- string += ch;
- }
+ string = string + (rep || ch);
}
escape = false;
} else if (ch === '\\') {
escape = true;
} else if (ch === quote) {
@@ -20435,10 +20535,11 @@
return extend(function(self, locals) {
var o = obj(self, locals),
i = indexFn(self, locals),
v, p;
+ ensureSafeMemberName(i, parser.text);
if (!o) return undefined;
v = ensureSafeObject(o[i], parser.text);
if (v && v.then && parser.options.unwrapPromises) {
p = v;
if (!('$$v' in v)) {
@@ -20477,11 +20578,11 @@
args.push(argsFn[i](scope, locals));
}
var fnPtr = fn(scope, locals, context) || noop;
ensureSafeObject(context, parser.text);
- ensureSafeObject(fnPtr, parser.text);
+ ensureSafeFunction(fnPtr, parser.text);
// IE stupidity! (IE doesn't have apply for some native functions)
var v = fnPtr.apply
? fnPtr.apply(context, args)
: fnPtr(args[0], args[1], args[2], args[3], args[4]);
@@ -20586,10 +20687,12 @@
}
obj = obj.$$v;
}
}
key = ensureSafeMemberName(element.shift(), fullExp);
+ ensureSafeObject(obj, fullExp);
+ ensureSafeObject(obj[key], fullExp);
obj[key] = setValue;
return setValue;
}
var getterFnCache = {};
@@ -20701,30 +20804,10 @@
}
return pathVal;
};
}
-function simpleGetterFn1(key0, fullExp) {
- ensureSafeMemberName(key0, fullExp);
-
- return function simpleGetterFn1(scope, locals) {
- if (scope == null) return undefined;
- return ((locals && locals.hasOwnProperty(key0)) ? locals : scope)[key0];
- };
-}
-
-function simpleGetterFn2(key0, key1, fullExp) {
- ensureSafeMemberName(key0, fullExp);
- ensureSafeMemberName(key1, fullExp);
-
- return function simpleGetterFn2(scope, locals) {
- if (scope == null) return undefined;
- scope = ((locals && locals.hasOwnProperty(key0)) ? locals : scope)[key0];
- return scope == null ? undefined : scope[key1];
- };
-}
-
function getterFn(path, options, fullExp) {
// Check whether the cache has this getter already.
// We can use hasOwnProperty directly on the cache because we ensure,
// see below, that the cache never stores a path called 'hasOwnProperty'
if (getterFnCache.hasOwnProperty(path)) {
@@ -20733,17 +20816,12 @@
var pathKeys = path.split('.'),
pathKeysLength = pathKeys.length,
fn;
- // When we have only 1 or 2 tokens, use optimized special case closures.
// http://jsperf.com/angularjs-parse-getter/6
- if (!options.unwrapPromises && pathKeysLength === 1) {
- fn = simpleGetterFn1(pathKeys[0], fullExp);
- } else if (!options.unwrapPromises && pathKeysLength === 2) {
- fn = simpleGetterFn2(pathKeys[0], pathKeys[1], fullExp);
- } else if (options.csp) {
+ if (options.csp) {
if (pathKeysLength < 6) {
fn = cspSafeGetterFn(pathKeys[0], pathKeys[1], pathKeys[2], pathKeys[3], pathKeys[4], fullExp,
options);
} else {
fn = function(scope, locals) {
@@ -21005,21 +21083,17 @@
*
* function asyncGreet(name) {
* var deferred = $q.defer();
*
* setTimeout(function() {
- * // since this fn executes async in a future turn of the event loop, we need to wrap
- * // our code into an $apply call so that the model changes are properly observed.
- * scope.$apply(function() {
- * deferred.notify('About to greet ' + name + '.');
+ * deferred.notify('About to greet ' + name + '.');
*
- * if (okToGreet(name)) {
- * deferred.resolve('Hello, ' + name + '!');
- * } else {
- * deferred.reject('Greeting ' + name + ' is not allowed.');
- * }
- * });
+ * if (okToGreet(name)) {
+ * deferred.resolve('Hello, ' + name + '!');
+ * } else {
+ * deferred.reject('Greeting ' + name + ' is not allowed.');
+ * }
* }, 1000);
*
* return deferred.promise;
* }
*
@@ -21289,11 +21363,11 @@
try {
callbackOutput = (callback ||defaultCallback)();
} catch(e) {
return makePromise(e, false);
}
- if (callbackOutput && isFunction(callbackOutput.then)) {
+ if (isPromiseLike(callbackOutput)) {
return callbackOutput.then(function() {
return makePromise(value, isResolved);
}, function(error) {
return makePromise(error, false);
});
@@ -21314,11 +21388,11 @@
return deferred;
};
var ref = function(value) {
- if (value && isFunction(value.then)) return value;
+ if (isPromiseLike(value)) return value;
return {
then: function(callback) {
var result = defer();
nextTick(function() {
result.resolve(callback(value));
@@ -21981,11 +22055,11 @@
var initRun = true;
var oldLength = 0;
function $watchCollectionWatch() {
newValue = objGetter(self);
- var newLength, key;
+ var newLength, key, bothNaN;
if (!isObject(newValue)) { // if primitive
if (oldValue !== newValue) {
oldValue = newValue;
changeDetected++;
@@ -22005,11 +22079,11 @@
changeDetected++;
oldValue.length = oldLength = newLength;
}
// copy the items to oldValue and look for changes.
for (var i = 0; i < newLength; i++) {
- var bothNaN = (oldValue[i] !== oldValue[i]) &&
+ bothNaN = (oldValue[i] !== oldValue[i]) &&
(newValue[i] !== newValue[i]);
if (!bothNaN && (oldValue[i] !== newValue[i])) {
changeDetected++;
oldValue[i] = newValue[i];
}
@@ -22025,11 +22099,13 @@
newLength = 0;
for (key in newValue) {
if (newValue.hasOwnProperty(key)) {
newLength++;
if (oldValue.hasOwnProperty(key)) {
- if (oldValue[key] !== newValue[key]) {
+ bothNaN = (oldValue[key] !== oldValue[key]) &&
+ (newValue[key] !== newValue[key]);
+ if (!bothNaN && (oldValue[key] !== newValue[key])) {
changeDetected++;
oldValue[key] = newValue[key];
}
} else {
oldLength++;
@@ -22177,11 +22253,11 @@
// circuit it with === operator, only when === fails do we use .equals
if (watch) {
if ((value = watch.get(current)) !== (last = watch.last) &&
!(watch.eq
? equals(value, last)
- : (typeof value == 'number' && typeof last == 'number'
+ : (typeof value === 'number' && typeof last === 'number'
&& isNaN(value) && isNaN(last)))) {
dirty = true;
lastDirtyWatch = watch;
watch.last = watch.eq ? copy(value, null) : value;
watch.fn(value, ((last === initWatchVal) ? value : last), current);
@@ -22870,23 +22946,25 @@
* `http://srv01.assets.example.com/`, `http://srv02.assets.example.com/`, etc.
* - and you have an open redirect at `http://myapp.example.com/clickThru?...`.
*
* Here is what a secure configuration for this scenario might look like:
*
- * <pre class="prettyprint">
- * angular.module('myApp', []).config(function($sceDelegateProvider) {
- * $sceDelegateProvider.resourceUrlWhitelist([
- * // Allow same origin resource loads.
- * 'self',
- * // Allow loading from our assets domain. Notice the difference between * and **.
- * 'http://srv*.assets.example.com/**']);
+ * ```
+ * angular.module('myApp', []).config(function($sceDelegateProvider) {
+ * $sceDelegateProvider.resourceUrlWhitelist([
+ * // Allow same origin resource loads.
+ * 'self',
+ * // Allow loading from our assets domain. Notice the difference between * and **.
+ * 'http://srv*.assets.example.com/**'
+ * ]);
*
- * // The blacklist overrides the whitelist so the open redirect here is blocked.
- * $sceDelegateProvider.resourceUrlBlacklist([
- * 'http://myapp.example.com/clickThru**']);
- * });
- * </pre>
+ * // The blacklist overrides the whitelist so the open redirect here is blocked.
+ * $sceDelegateProvider.resourceUrlBlacklist([
+ * 'http://myapp.example.com/clickThru**'
+ * ]);
+ * });
+ * ```
*/
function $SceDelegateProvider() {
this.SCE_CONTEXTS = SCE_CONTEXTS;
@@ -23177,14 +23255,14 @@
* SCE assists in writing code in way that (a) is secure by default and (b) makes auditing for
* security vulnerabilities such as XSS, clickjacking, etc. a lot easier.
*
* Here's an example of a binding in a privileged context:
*
- * <pre class="prettyprint">
- * <input ng-model="userHtml">
- * <div ng-bind-html="userHtml">
- * </pre>
+ * ```
+ * <input ng-model="userHtml">
+ * <div ng-bind-html="userHtml"></div>
+ * ```
*
* Notice that `ng-bind-html` is bound to `userHtml` controlled by the user. With SCE
* disabled, this application allows the user to render arbitrary HTML into the DIV.
* In a more realistic example, one may be rendering user comments, blog articles, etc. via
* bindings. (HTML is just one example of a context where rendering user controlled input creates
@@ -23220,19 +23298,19 @@
*
* As an example, {@link ng.directive:ngBindHtml ngBindHtml} uses {@link
* ng.$sce#parseAsHtml $sce.parseAsHtml(binding expression)}. Here's the actual code (slightly
* simplified):
*
- * <pre class="prettyprint">
- * var ngBindHtmlDirective = ['$sce', function($sce) {
- * return function(scope, element, attr) {
- * scope.$watch($sce.parseAsHtml(attr.ngBindHtml), function(value) {
- * element.html(value || '');
- * });
- * };
- * }];
- * </pre>
+ * ```
+ * var ngBindHtmlDirective = ['$sce', function($sce) {
+ * return function(scope, element, attr) {
+ * scope.$watch($sce.parseAsHtml(attr.ngBindHtml), function(value) {
+ * element.html(value || '');
+ * });
+ * };
+ * }];
+ * ```
*
* ## Impact on loading templates
*
* This applies both to the {@link ng.directive:ngInclude `ng-include`} directive as well as
* `templateUrl`'s specified by {@link guide/directive directives}.
@@ -23332,90 +23410,89 @@
*
* Refer {@link ng.$sceDelegateProvider $sceDelegateProvider} for an example.
*
* ## Show me an example using SCE.
*
- * @example
-<example module="mySceApp" deps="angular-sanitize.js">
-<file name="index.html">
- <div ng-controller="myAppController as myCtrl">
- <i ng-bind-html="myCtrl.explicitlyTrustedHtml" id="explicitlyTrustedHtml"></i><br><br>
- <b>User comments</b><br>
- By default, HTML that isn't explicitly trusted (e.g. Alice's comment) is sanitized when
- $sanitize is available. If $sanitize isn't available, this results in an error instead of an
- exploit.
- <div class="well">
- <div ng-repeat="userComment in myCtrl.userComments">
- <b>{{userComment.name}}</b>:
- <span ng-bind-html="userComment.htmlComment" class="htmlComment"></span>
- <br>
- </div>
- </div>
- </div>
-</file>
-
-<file name="script.js">
- var mySceApp = angular.module('mySceApp', ['ngSanitize']);
-
- mySceApp.controller("myAppController", function myAppController($http, $templateCache, $sce) {
- var self = this;
- $http.get("test_data.json", {cache: $templateCache}).success(function(userComments) {
- self.userComments = userComments;
- });
- self.explicitlyTrustedHtml = $sce.trustAsHtml(
- '<span onmouseover="this.textContent="Explicitly trusted HTML bypasses ' +
- 'sanitization."">Hover over this text.</span>');
- });
-</file>
-
-<file name="test_data.json">
-[
- { "name": "Alice",
- "htmlComment":
- "<span onmouseover='this.textContent=\"PWN3D!\"'>Is <i>anyone</i> reading this?</span>"
- },
- { "name": "Bob",
- "htmlComment": "<i>Yes!</i> Am I the only other one?"
- }
-]
-</file>
-
-<file name="protractor.js" type="protractor">
- describe('SCE doc demo', function() {
- it('should sanitize untrusted values', function() {
- expect(element(by.css('.htmlComment')).getInnerHtml())
- .toBe('<span>Is <i>anyone</i> reading this?</span>');
- });
-
- it('should NOT sanitize explicitly trusted values', function() {
- expect(element(by.id('explicitlyTrustedHtml')).getInnerHtml()).toBe(
- '<span onmouseover="this.textContent="Explicitly trusted HTML bypasses ' +
- 'sanitization."">Hover over this text.</span>');
- });
- });
-</file>
-</example>
+ * <example module="mySceApp" deps="angular-sanitize.js">
+ * <file name="index.html">
+ * <div ng-controller="myAppController as myCtrl">
+ * <i ng-bind-html="myCtrl.explicitlyTrustedHtml" id="explicitlyTrustedHtml"></i><br><br>
+ * <b>User comments</b><br>
+ * By default, HTML that isn't explicitly trusted (e.g. Alice's comment) is sanitized when
+ * $sanitize is available. If $sanitize isn't available, this results in an error instead of an
+ * exploit.
+ * <div class="well">
+ * <div ng-repeat="userComment in myCtrl.userComments">
+ * <b>{{userComment.name}}</b>:
+ * <span ng-bind-html="userComment.htmlComment" class="htmlComment"></span>
+ * <br>
+ * </div>
+ * </div>
+ * </div>
+ * </file>
*
+ * <file name="script.js">
+ * var mySceApp = angular.module('mySceApp', ['ngSanitize']);
*
+ * mySceApp.controller("myAppController", function myAppController($http, $templateCache, $sce) {
+ * var self = this;
+ * $http.get("test_data.json", {cache: $templateCache}).success(function(userComments) {
+ * self.userComments = userComments;
+ * });
+ * self.explicitlyTrustedHtml = $sce.trustAsHtml(
+ * '<span onmouseover="this.textContent="Explicitly trusted HTML bypasses ' +
+ * 'sanitization."">Hover over this text.</span>');
+ * });
+ * </file>
*
+ * <file name="test_data.json">
+ * [
+ * { "name": "Alice",
+ * "htmlComment":
+ * "<span onmouseover='this.textContent=\"PWN3D!\"'>Is <i>anyone</i> reading this?</span>"
+ * },
+ * { "name": "Bob",
+ * "htmlComment": "<i>Yes!</i> Am I the only other one?"
+ * }
+ * ]
+ * </file>
+ *
+ * <file name="protractor.js" type="protractor">
+ * describe('SCE doc demo', function() {
+ * it('should sanitize untrusted values', function() {
+ * expect(element.all(by.css('.htmlComment')).first().getInnerHtml())
+ * .toBe('<span>Is <i>anyone</i> reading this?</span>');
+ * });
+ *
+ * it('should NOT sanitize explicitly trusted values', function() {
+ * expect(element(by.id('explicitlyTrustedHtml')).getInnerHtml()).toBe(
+ * '<span onmouseover="this.textContent="Explicitly trusted HTML bypasses ' +
+ * 'sanitization."">Hover over this text.</span>');
+ * });
+ * });
+ * </file>
+ * </example>
+ *
+ *
+ *
* ## Can I disable SCE completely?
*
* Yes, you can. However, this is strongly discouraged. SCE gives you a lot of security benefits
* for little coding overhead. It will be much harder to take an SCE disabled application and
* either secure it on your own or enable SCE at a later stage. It might make sense to disable SCE
* for cases where you have a lot of existing code that was written before SCE was introduced and
* you're migrating them a module at a time.
*
* That said, here's how you can completely disable SCE:
*
- * <pre class="prettyprint">
- * angular.module('myAppWithSceDisabledmyApp', []).config(function($sceProvider) {
- * // Completely disable SCE. For demonstration purposes only!
- * // Do not use in new projects.
- * $sceProvider.enabled(false);
- * });
- * </pre>
+ * ```
+ * angular.module('myAppWithSceDisabledmyApp', []).config(function($sceProvider) {
+ * // Completely disable SCE. For demonstration purposes only!
+ * // Do not use in new projects.
+ * $sceProvider.enabled(false);
+ * });
+ * ```
*
*/
/* jshint maxlen: 100 */
function $SceProvider() {
@@ -23522,11 +23599,11 @@
sce.valueOf = identity;
}
/**
* @ngdoc method
- * @name $sce#parse
+ * @name $sce#parseAs
*
* @description
* Converts Angular {@link guide/expression expression} into a function. This is like {@link
* ng.$parse $parse} and is identical when the expression is a literal constant. Otherwise, it
* wraps the expression in a call to {@link ng.$sce#getTrusted $sce.getTrusted(*type*,
@@ -24108,21 +24185,22 @@
* below, are evaluated with respect to the current scope. Therefore, there is
* no risk of inadvertently coding in a dependency on a global value in such an
* expression.
*
* @example
- <example>
+ <example module="windowExample">
<file name="index.html">
<script>
- function Ctrl($scope, $window) {
- $scope.greeting = 'Hello, World!';
- $scope.doGreeting = function(greeting) {
+ angular.module('windowExample', [])
+ .controller('ExampleController', ['$scope', '$window', function ($scope, $window) {
+ $scope.greeting = 'Hello, World!';
+ $scope.doGreeting = function(greeting) {
$window.alert(greeting);
- };
- }
+ };
+ }]);
</script>
- <div ng-controller="Ctrl">
+ <div ng-controller="ExampleController">
<input type="text" ng-model="greeting" />
<button ng-click="doGreeting(greeting)">ALERT</button>
</div>
</file>
<file name="protractor.js" type="protractor">
@@ -24136,10 +24214,21 @@
*/
function $WindowProvider(){
this.$get = valueFn(window);
}
+/* global currencyFilter: true,
+ dateFilter: true,
+ filterFilter: true,
+ jsonFilter: true,
+ limitToFilter: true,
+ lowercaseFilter: true,
+ numberFilter: true,
+ orderByFilter: true,
+ uppercaseFilter: true,
+ */
+
/**
* @ngdoc provider
* @name $filterProvider
* @description
*
@@ -24478,11 +24567,11 @@
// jshint -W086
case "object":
// jshint +W086
for (var key in expression) {
(function(path) {
- if (typeof expression[path] == 'undefined') return;
+ if (typeof expression[path] === 'undefined') return;
predicates.push(function(value) {
return search(path == '$' ? value : (value && value[path]), expression[path]);
});
})(key);
}
@@ -24517,18 +24606,19 @@
* @param {string=} symbol Currency symbol or identifier to be displayed.
* @returns {string} Formatted number.
*
*
* @example
- <example>
+ <example module="currencyExample">
<file name="index.html">
<script>
- function Ctrl($scope) {
- $scope.amount = 1234.56;
- }
+ angular.module('currencyExample', [])
+ .controller('ExampleController', ['$scope', function($scope) {
+ $scope.amount = 1234.56;
+ }]);
</script>
- <div ng-controller="Ctrl">
+ <div ng-controller="ExampleController">
<input type="number" ng-model="amount"> <br>
default currency symbol ($): <span id="currency-default">{{amount | currency}}</span><br>
custom currency identifier (USD$): <span>{{amount | currency:"USD$"}}</span>
</div>
</file>
@@ -24576,18 +24666,19 @@
* If this is not provided then the fraction size is computed from the current locale's number
* formatting pattern. In the case of the default locale, it will be 3.
* @returns {string} Number rounded to decimalPlaces and places a “,” after each third digit.
*
* @example
- <example>
+ <example module="numberFilterExample">
<file name="index.html">
<script>
- function Ctrl($scope) {
- $scope.val = 1234.56789;
- }
+ angular.module('numberFilterExample', [])
+ .controller('ExampleController', ['$scope', function($scope) {
+ $scope.val = 1234.56789;
+ }]);
</script>
- <div ng-controller="Ctrl">
+ <div ng-controller="ExampleController">
Enter number: <input ng-model='val'><br>
Default formatting: <span id='number-default'>{{val | number}}</span><br>
No fractions: <span>{{val | number:0}}</span><br>
Negative number: <span>{{-val | number:4}}</span>
</div>
@@ -24633,10 +24724,11 @@
var hasExponent = false;
if (numStr.indexOf('e') !== -1) {
var match = numStr.match(/([\d\.]+)e(-?)(\d+)/);
if (match && match[2] == '-' && match[3] > fractionSize + 1) {
numStr = '0';
+ number = 0;
} else {
formatedText = numStr;
hasExponent = true;
}
}
@@ -24647,12 +24739,15 @@
// determine fractionSize if it is not specified
if (isUndefined(fractionSize)) {
fractionSize = Math.min(Math.max(pattern.minFrac, fractionLen), pattern.maxFrac);
}
- var pow = Math.pow(10, fractionSize + 1);
- number = Math.floor(number * pow + 5) / pow;
+ // safely round numbers in JS without hitting imprecisions of floating-point arithmetics
+ // inspired by:
+ // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/round
+ number = +(Math.round(+(number.toString() + 'e' + fractionSize)).toString() + 'e' + -fractionSize);
+
var fraction = ('' + number).split(DECIMAL_SEP);
var whole = fraction[0];
fraction = fraction[1] || '';
var i, pos = 0,
@@ -24891,15 +24986,11 @@
fn, match;
format = format || 'mediumDate';
format = $locale.DATETIME_FORMATS[format] || format;
if (isString(date)) {
- if (NUMBER_STRING.test(date)) {
- date = int(date);
- } else {
- date = jsonStringToDate(date);
- }
+ date = NUMBER_STRING.test(date) ? int(date) : jsonStringToDate(date);
}
if (isNumber(date)) {
date = new Date(date);
}
@@ -25003,21 +25094,22 @@
* are copied. The `limit` will be trimmed if it exceeds `array.length`
* @returns {Array|string} A new sub-array or substring of length `limit` or less if input array
* had less than `limit` elements.
*
* @example
- <example>
+ <example module="limitToExample">
<file name="index.html">
<script>
- function Ctrl($scope) {
- $scope.numbers = [1,2,3,4,5,6,7,8,9];
- $scope.letters = "abcdefghi";
- $scope.numLimit = 3;
- $scope.letterLimit = 3;
- }
+ angular.module('limitToExample', [])
+ .controller('ExampleController', ['$scope', function($scope) {
+ $scope.numbers = [1,2,3,4,5,6,7,8,9];
+ $scope.letters = "abcdefghi";
+ $scope.numLimit = 3;
+ $scope.letterLimit = 3;
+ }]);
</script>
- <div ng-controller="Ctrl">
+ <div ng-controller="ExampleController">
Limit {{numbers}} to: <input type="integer" ng-model="numLimit">
<p>Output numbers: {{ numbers | limitTo:numLimit }}</p>
Limit {{letters}} to: <input type="integer" ng-model="letterLimit">
<p>Output letters: {{ letters | limitTo:letterLimit }}</p>
</div>
@@ -25125,24 +25217,25 @@
*
* @param {boolean=} reverse Reverse the order of the array.
* @returns {Array} Sorted copy of the source array.
*
* @example
- <example>
+ <example module="orderByExample">
<file name="index.html">
<script>
- function Ctrl($scope) {
- $scope.friends =
- [{name:'John', phone:'555-1212', age:10},
- {name:'Mary', phone:'555-9876', age:19},
- {name:'Mike', phone:'555-4321', age:21},
- {name:'Adam', phone:'555-5678', age:35},
- {name:'Julie', phone:'555-8765', age:29}]
- $scope.predicate = '-age';
- }
+ angular.module('orderByExample', [])
+ .controller('ExampleController', ['$scope', function($scope) {
+ $scope.friends =
+ [{name:'John', phone:'555-1212', age:10},
+ {name:'Mary', phone:'555-9876', age:19},
+ {name:'Mike', phone:'555-4321', age:21},
+ {name:'Adam', phone:'555-5678', age:35},
+ {name:'Julie', phone:'555-8765', age:29}];
+ $scope.predicate = '-age';
+ }]);
</script>
- <div ng-controller="Ctrl">
+ <div ng-controller="ExampleController">
<pre>Sorting predicate = {{predicate}}; reverse = {{reverse}}</pre>
<hr/>
[ <a href="" ng-click="predicate=''">unsorted</a> ]
<table class="friend">
<tr>
@@ -25166,13 +25259,13 @@
* desired parameters.
*
* Example:
*
* @example
- <example>
+ <example module="orderByExample">
<file name="index.html">
- <div ng-controller="Ctrl">
+ <div ng-controller="ExampleController">
<table class="friend">
<tr>
<th><a href="" ng-click="reverse=false;order('name', false)">Name</a>
(<a href="" ng-click="order('-name',false)">^</a>)</th>
<th><a href="" ng-click="reverse=!reverse;order('phone', reverse)">Phone Number</a></th>
@@ -25186,25 +25279,25 @@
</table>
</div>
</file>
<file name="script.js">
- function Ctrl($scope, $filter) {
- var orderBy = $filter('orderBy');
- $scope.friends = [
- { name: 'John', phone: '555-1212', age: 10 },
- { name: 'Mary', phone: '555-9876', age: 19 },
- { name: 'Mike', phone: '555-4321', age: 21 },
- { name: 'Adam', phone: '555-5678', age: 35 },
- { name: 'Julie', phone: '555-8765', age: 29 }
- ];
-
- $scope.order = function(predicate, reverse) {
- $scope.friends = orderBy($scope.friends, predicate, reverse);
- };
- $scope.order('-age',false);
- }
+ angular.module('orderByExample', [])
+ .controller('ExampleController', ['$scope', '$filter', function($scope, $filter) {
+ var orderBy = $filter('orderBy');
+ $scope.friends = [
+ { name: 'John', phone: '555-1212', age: 10 },
+ { name: 'Mary', phone: '555-9876', age: 19 },
+ { name: 'Mike', phone: '555-4321', age: 21 },
+ { name: 'Adam', phone: '555-5678', age: 35 },
+ { name: 'Julie', phone: '555-8765', age: 29 }
+ ];
+ $scope.order = function(predicate, reverse) {
+ $scope.friends = orderBy($scope.friends, predicate, reverse);
+ };
+ $scope.order('-age',false);
+ }]);
</file>
</example>
*/
orderByFilter.$inject = ['$parse'];
function orderByFilter($parse){
@@ -25249,10 +25342,14 @@
}
function compare(v1, v2){
var t1 = typeof v1;
var t2 = typeof v2;
if (t1 == t2) {
+ if (isDate(v1) && isDate(v2)) {
+ v1 = v1.valueOf();
+ v2 = v2.valueOf();
+ }
if (t1 == "string") {
v1 = v1.toLowerCase();
v2 = v2.toLowerCase();
}
if (v1 === v2) return 0;
@@ -25386,11 +25483,11 @@
browser.wait(function() {
return browser.driver.getCurrentUrl().then(function(url) {
return url.match(/\/123$/);
});
- }, 1000, 'page should navigate to /123');
+ }, 5000, 'page should navigate to /123');
});
xit('should execute ng-click but not reload when href empty string and name specified', function() {
element(by.id('link-4')).click();
expect(element(by.model('value')).getAttribute('value')).toEqual('4');
@@ -25414,11 +25511,11 @@
// to use browser.driver to get the base webdriver.
browser.wait(function() {
return browser.driver.getCurrentUrl().then(function(url) {
return url.match(/\/6$/);
});
- }, 1000, 'page should navigate to /6');
+ }, 5000, 'page should navigate to /6');
});
</file>
</example>
*/
@@ -26030,16 +26127,17 @@
* color:white;
* }
* </pre>
*
* @example
- <example deps="angular-animate.js" animations="true" fixBase="true">
+ <example deps="angular-animate.js" animations="true" fixBase="true" module="formExample">
<file name="index.html">
<script>
- function Ctrl($scope) {
- $scope.userType = 'guest';
- }
+ angular.module('formExample', [])
+ .controller('FormController', ['$scope', function($scope) {
+ $scope.userType = 'guest';
+ }]);
</script>
<style>
.my-form {
-webkit-transition:all linear 0.5s;
transition:all linear 0.5s;
@@ -26047,11 +26145,11 @@
}
.my-form.ng-invalid {
background: red;
}
</style>
- <form name="myForm" ng-controller="Ctrl" class="my-form">
+ <form name="myForm" ng-controller="FormController" class="my-form">
userType: <input name="input" ng-model="userType" required>
<span class="error" ng-show="myForm.input.$error.required">Required!</span><br>
<tt>userType = {{userType}}</tt><br>
<tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br>
<tt>myForm.input.$error = {{myForm.input.$error}}</tt><br>
@@ -26141,20 +26239,18 @@
};
var formDirective = formDirectiveFactory();
var ngFormDirective = formDirectiveFactory(true);
-/* global
-
- -VALID_CLASS,
- -INVALID_CLASS,
- -PRISTINE_CLASS,
- -DIRTY_CLASS
+/* global VALID_CLASS: true,
+ INVALID_CLASS: true,
+ PRISTINE_CLASS: true,
+ DIRTY_CLASS: true
*/
var URL_REGEXP = /^(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?$/;
-var EMAIL_REGEXP = /^[a-z0-9!#$%&'*+/=?^_`{|}~.-]+@[a-z0-9-]+(\.[a-z0-9-]+)*$/i;
+var EMAIL_REGEXP = /^[a-z0-9!#$%&'*+\/=?^_`{|}~.-]+@[a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)*$/i;
var NUMBER_REGEXP = /^\s*(\-|\+)?(\d+|(\d*(\.\d*)))\s*$/;
var inputType = {
/**
@@ -26180,19 +26276,20 @@
* @param {string=} ngChange Angular expression to be executed when input changes due to user
* interaction with the input element.
* @param {boolean=} [ngTrim=true] If set to false Angular will not automatically trim the input.
*
* @example
- <example name="text-input-directive">
+ <example name="text-input-directive" module="textInputExample">
<file name="index.html">
<script>
- function Ctrl($scope) {
- $scope.text = 'guest';
- $scope.word = /^\s*\w*\s*$/;
- }
+ angular.module('textInputExample', [])
+ .controller('ExampleController', ['$scope', function($scope) {
+ $scope.text = 'guest';
+ $scope.word = /^\s*\w*\s*$/;
+ }]);
</script>
- <form name="myForm" ng-controller="Ctrl">
+ <form name="myForm" ng-controller="ExampleController">
Single word: <input type="text" name="input" ng-model="text"
ng-pattern="word" required ng-trim="false">
<span class="error" ng-show="myForm.input.$error.required">
Required!</span>
<span class="error" ng-show="myForm.input.$error.pattern">
@@ -26260,18 +26357,19 @@
* patterns defined as scope expressions.
* @param {string=} ngChange Angular expression to be executed when input changes due to user
* interaction with the input element.
*
* @example
- <example name="number-input-directive">
+ <example name="number-input-directive" module="numberExample">
<file name="index.html">
<script>
- function Ctrl($scope) {
- $scope.value = 12;
- }
+ angular.module('numberExample', [])
+ .controller('ExampleController', ['$scope', function($scope) {
+ $scope.value = 12;
+ }]);
</script>
- <form name="myForm" ng-controller="Ctrl">
+ <form name="myForm" ng-controller="ExampleController">
Number: <input type="number" name="input" ng-model="value"
min="0" max="99" required>
<span class="error" ng-show="myForm.input.$error.required">
Required!</span>
<span class="error" ng-show="myForm.input.$error.number">
@@ -26335,18 +26433,19 @@
* patterns defined as scope expressions.
* @param {string=} ngChange Angular expression to be executed when input changes due to user
* interaction with the input element.
*
* @example
- <example name="url-input-directive">
+ <example name="url-input-directive" module="urlExample">
<file name="index.html">
<script>
- function Ctrl($scope) {
- $scope.text = 'http://google.com';
- }
+ angular.module('urlExample', [])
+ .controller('ExampleController', ['$scope', function($scope) {
+ $scope.text = 'http://google.com';
+ }]);
</script>
- <form name="myForm" ng-controller="Ctrl">
+ <form name="myForm" ng-controller="ExampleController">
URL: <input type="url" name="input" ng-model="text" required>
<span class="error" ng-show="myForm.input.$error.required">
Required!</span>
<span class="error" ng-show="myForm.input.$error.url">
Not valid url!</span>
@@ -26411,18 +26510,19 @@
* patterns defined as scope expressions.
* @param {string=} ngChange Angular expression to be executed when input changes due to user
* interaction with the input element.
*
* @example
- <example name="email-input-directive">
+ <example name="email-input-directive" module="emailExample">
<file name="index.html">
<script>
- function Ctrl($scope) {
- $scope.text = 'me@example.com';
- }
+ angular.module('emailExample', [])
+ .controller('ExampleController', ['$scope', function($scope) {
+ $scope.text = 'me@example.com';
+ }]);
</script>
- <form name="myForm" ng-controller="Ctrl">
+ <form name="myForm" ng-controller="ExampleController">
Email: <input type="email" name="input" ng-model="text" required>
<span class="error" ng-show="myForm.input.$error.required">
Required!</span>
<span class="error" ng-show="myForm.input.$error.email">
Not valid email!</span>
@@ -26477,22 +26577,23 @@
* interaction with the input element.
* @param {string} ngValue Angular expression which sets the value to which the expression should
* be set when selected.
*
* @example
- <example name="radio-input-directive">
+ <example name="radio-input-directive" module="radioExample">
<file name="index.html">
<script>
- function Ctrl($scope) {
- $scope.color = 'blue';
- $scope.specialValue = {
- "id": "12345",
- "value": "green"
- };
- }
+ angular.module('radioExample', [])
+ .controller('ExampleController', ['$scope', function($scope) {
+ $scope.color = 'blue';
+ $scope.specialValue = {
+ "id": "12345",
+ "value": "green"
+ };
+ }]);
</script>
- <form name="myForm" ng-controller="Ctrl">
+ <form name="myForm" ng-controller="ExampleController">
<input type="radio" ng-model="color" value="red"> Red <br/>
<input type="radio" ng-model="color" ng-value="specialValue"> Green <br/>
<input type="radio" ng-model="color" value="blue"> Blue <br/>
<tt>color = {{color | json}}</tt><br/>
</form>
@@ -26527,19 +26628,20 @@
* @param {string=} ngFalseValue The value to which the expression should be set when not selected.
* @param {string=} ngChange Angular expression to be executed when input changes due to user
* interaction with the input element.
*
* @example
- <example name="checkbox-input-directive">
+ <example name="checkbox-input-directive" module="checkboxExample">
<file name="index.html">
<script>
- function Ctrl($scope) {
- $scope.value1 = true;
- $scope.value2 = 'YES'
- }
+ angular.module('checkboxExample', [])
+ .controller('ExampleController', ['$scope', function($scope) {
+ $scope.value1 = true;
+ $scope.value2 = 'YES'
+ }]);
</script>
- <form name="myForm" ng-controller="Ctrl">
+ <form name="myForm" ng-controller="ExampleController">
Value1: <input type="checkbox" ng-model="value1"> <br/>
Value2: <input type="checkbox" ng-model="value2"
ng-true-value="YES" ng-false-value="NO"> <br/>
<tt>value1 = {{value1}}</tt><br/>
<tt>value2 = {{value2}}</tt><br/>
@@ -26576,31 +26678,46 @@
function validate(ctrl, validatorName, validity, value){
ctrl.$setValidity(validatorName, validity);
return validity ? value : undefined;
}
+function testFlags(validity, flags) {
+ var i, flag;
+ if (flags) {
+ for (i=0; i<flags.length; ++i) {
+ flag = flags[i];
+ if (validity[flag]) {
+ return true;
+ }
+ }
+ }
+ return false;
+}
-function addNativeHtml5Validators(ctrl, validatorName, element) {
- var validity = element.prop('validity');
+// Pass validity so that behaviour can be mocked easier.
+function addNativeHtml5Validators(ctrl, validatorName, badFlags, ignoreFlags, validity) {
if (isObject(validity)) {
+ ctrl.$$hasNativeValidators = true;
var validator = function(value) {
// Don't overwrite previous validation, don't consider valueMissing to apply (ng-required can
// perform the required validation)
- if (!ctrl.$error[validatorName] && (validity.badInput || validity.customError ||
- validity.typeMismatch) && !validity.valueMissing) {
+ if (!ctrl.$error[validatorName] &&
+ !testFlags(validity, ignoreFlags) &&
+ testFlags(validity, badFlags)) {
ctrl.$setValidity(validatorName, false);
return;
}
return value;
};
ctrl.$parsers.push(validator);
}
}
function textInputType(scope, element, attr, ctrl, $sniffer, $browser) {
- var validity = element.prop('validity');
+ var validity = element.prop(VALIDITY_STATE_PROPERTY);
var placeholder = element[0].placeholder, noevent = {};
+ ctrl.$$validityState = validity;
// In composition mode, users are still inputing intermediate text buffer,
// hold the listener until composition is done.
// More about composition events: https://developer.mozilla.org/en-US/docs/Web/API/CompositionEvent
if (!$sniffer.android) {
@@ -26634,15 +26751,15 @@
// e.g. <input ng-model="foo" ng-trim="false">
if (toBoolean(attr.ngTrim || 'T')) {
value = trim(value);
}
- if (ctrl.$viewValue !== value ||
- // If the value is still empty/falsy, and there is no `required` error, run validators
- // again. This enables HTML5 constraint validation errors to affect Angular validation
- // even when the first character entered causes an error.
- (validity && value === '' && !validity.valueMissing)) {
+ // If a control is suffering from bad input, browsers discard its value, so it may be
+ // necessary to revalidate even if the control's value is the same empty value twice in
+ // a row.
+ var revalidate = validity && ctrl.$$hasNativeValidators;
+ if (ctrl.$viewValue !== value || (value === '' && revalidate)) {
if (scope.$$phase) {
ctrl.$setViewValue(value);
} else {
scope.$apply(function() {
ctrl.$setViewValue(value);
@@ -26744,10 +26861,12 @@
ctrl.$parsers.push(maxLengthValidator);
ctrl.$formatters.push(maxLengthValidator);
}
}
+var numberBadFlags = ['badInput'];
+
function numberInputType(scope, element, attr, ctrl, $sniffer, $browser) {
textInputType(scope, element, attr, ctrl, $sniffer, $browser);
ctrl.$parsers.push(function(value) {
var empty = ctrl.$isEmpty(value);
@@ -26758,11 +26877,11 @@
ctrl.$setValidity('number', false);
return undefined;
}
});
- addNativeHtml5Validators(ctrl, 'number', element);
+ addNativeHtml5Validators(ctrl, 'number', numberBadFlags, null, ctrl.$$validityState);
ctrl.$formatters.push(function(value) {
return ctrl.$isEmpty(value) ? '' : '' + value;
});
@@ -26918,18 +27037,19 @@
* patterns defined as scope expressions.
* @param {string=} ngChange Angular expression to be executed when input changes due to user
* interaction with the input element.
*
* @example
- <example name="input-directive">
+ <example name="input-directive" module="inputExample">
<file name="index.html">
<script>
- function Ctrl($scope) {
- $scope.user = {name: 'guest', last: 'visitor'};
- }
+ angular.module('inputExample', [])
+ .controller('ExampleController', ['$scope', function($scope) {
+ $scope.user = {name: 'guest', last: 'visitor'};
+ }]);
</script>
- <div ng-controller="Ctrl">
+ <div ng-controller="ExampleController">
<form name="myForm">
User name: <input type="text" name="userName" ng-model="user.name" required>
<span class="error" ng-show="myForm.userName.$error.required">
Required!</span><br>
Last name: <input type="text" name="lastName" ng-model="user.last"
@@ -27240,11 +27360,11 @@
* does not notify form if given validator is already marked as invalid).
*
* This method should be called by validators - i.e. the parser or formatter functions.
*
* @param {string} validationErrorKey Name of the validator. the `validationErrorKey` will assign
- * to `$error[validationErrorKey]=isValid` so that it is available for data-binding.
+ * to `$error[validationErrorKey]=!isValid` so that it is available for data-binding.
* The `validationErrorKey` should be in camelCase and will get converted into dash-case
* for class name. Example: `myError` will result in `ng-valid-my-error` and `ng-invalid-my-error`
* class and can be bound to as `{{someForm.someControl.$error.myError}}` .
* @param {boolean} isValid Whether the current state is valid (true) or invalid (false).
*/
@@ -27443,16 +27563,17 @@
* color:white;
* }
* </pre>
*
* @example
- * <example deps="angular-animate.js" animations="true" fixBase="true">
+ * <example deps="angular-animate.js" animations="true" fixBase="true" module="inputExample">
<file name="index.html">
<script>
- function Ctrl($scope) {
- $scope.val = '1';
- }
+ angular.module('inputExample', [])
+ .controller('ExampleController', ['$scope', function($scope) {
+ $scope.val = '1';
+ }]);
</script>
<style>
.my-input {
-webkit-transition:all linear 0.5s;
transition:all linear 0.5s;
@@ -27463,11 +27584,11 @@
background: red;
}
</style>
Update input to see transitions when valid/invalid.
Integer is a valid value.
- <form name="testForm" ng-controller="Ctrl">
+ <form name="testForm" ng-controller="ExampleController">
<input ng-model="val" ng-pattern="/^\d+$/" name="anim" class="my-input" />
</form>
</file>
* </example>
*/
@@ -27507,21 +27628,22 @@
* @element input
* @param {expression} ngChange {@link guide/expression Expression} to evaluate upon change
* in input value.
*
* @example
- * <example name="ngChange-directive">
+ * <example name="ngChange-directive" module="changeExample">
* <file name="index.html">
* <script>
- * function Controller($scope) {
- * $scope.counter = 0;
- * $scope.change = function() {
- * $scope.counter++;
- * };
- * }
+ * angular.module('changeExample', [])
+ * .controller('ExampleController', ['$scope', function($scope) {
+ * $scope.counter = 0;
+ * $scope.change = function() {
+ * $scope.counter++;
+ * };
+ * }]);
* </script>
- * <div ng-controller="Controller">
+ * <div ng-controller="ExampleController">
* <input type="checkbox" ng-model="confirmed" ng-change="change()" id="ng-change-example1" />
* <input type="checkbox" ng-model="confirmed" id="ng-change-example2" />
* <label for="ng-change-example2">Confirmed</label><br />
* <tt>debug = {{confirmed}}</tt><br/>
* <tt>counter = {{counter}}</tt><br/>
@@ -27598,18 +27720,19 @@
* @element input
* @param {string=} ngList optional delimiter that should be used to split the value. If
* specified in form `/something/` then the value will be converted into a regular expression.
*
* @example
- <example name="ngList-directive">
+ <example name="ngList-directive" module="listExample">
<file name="index.html">
<script>
- function Ctrl($scope) {
- $scope.names = ['igor', 'misko', 'vojta'];
- }
+ angular.module('listExample', [])
+ .controller('ExampleController', ['$scope', function($scope) {
+ $scope.names = ['igor', 'misko', 'vojta'];
+ }]);
</script>
- <form name="myForm" ng-controller="Ctrl">
+ <form name="myForm" ng-controller="ExampleController">
List: <input name="namesInput" ng-model="names" ng-list required>
<span class="error" ng-show="myForm.namesInput.$error.required">
Required!</span>
<br>
<tt>names = {{names}}</tt><br/>
@@ -27697,19 +27820,20 @@
* @element input
* @param {string=} ngValue angular expression, whose value will be bound to the `value` attribute
* of the `input` element
*
* @example
- <example name="ngValue-directive">
+ <example name="ngValue-directive" module="valueExample">
<file name="index.html">
<script>
- function Ctrl($scope) {
- $scope.names = ['pizza', 'unicorns', 'robots'];
- $scope.my = { favorite: 'unicorns' };
- }
+ angular.module('valueExample', [])
+ .controller('ExampleController', ['$scope', function($scope) {
+ $scope.names = ['pizza', 'unicorns', 'robots'];
+ $scope.my = { favorite: 'unicorns' };
+ }]);
</script>
- <form ng-controller="Ctrl">
+ <form ng-controller="ExampleController">
<h2>Which is your favorite?</h2>
<label ng-repeat="name in names" for="{{name}}">
{{name}}
<input type="radio"
ng-model="my.favorite"
@@ -27763,11 +27887,11 @@
* expression changes.
*
* Typically, you don't use `ngBind` directly, but instead you use the double curly markup like
* `{{ expression }}` which is similar but less verbose.
*
- * It is preferable to use `ngBind` instead of `{{ expression }}` when a template is momentarily
+ * It is preferable to use `ngBind` instead of `{{ expression }}` if a template is momentarily
* displayed by the browser in its raw state before Angular compiles it. Since `ngBind` is an
* element attribute, it makes the bindings invisible to the user while the page is loading.
*
* An alternative solution to this problem would be using the
* {@link ng.directive:ngCloak ngCloak} directive.
@@ -27776,18 +27900,19 @@
* @element ANY
* @param {expression} ngBind {@link guide/expression Expression} to evaluate.
*
* @example
* Enter a name in the Live Preview text box; the greeting below the text box changes instantly.
- <example>
+ <example module="bindExample">
<file name="index.html">
<script>
- function Ctrl($scope) {
- $scope.name = 'Whirled';
- }
+ angular.module('bindExample', [])
+ .controller('ExampleController', ['$scope', function($scope) {
+ $scope.name = 'Whirled';
+ }]);
</script>
- <div ng-controller="Ctrl">
+ <div ng-controller="ExampleController">
Enter name: <input type="text" ng-model="name"><br>
Hello <span ng-bind="name"></span>!
</div>
</file>
<file name="protractor.js" type="protractor">
@@ -27834,19 +27959,20 @@
* @param {string} ngBindTemplate template of form
* <tt>{{</tt> <tt>expression</tt> <tt>}}</tt> to eval.
*
* @example
* Try it here: enter text in text box and watch the greeting change.
- <example>
+ <example module="bindExample">
<file name="index.html">
<script>
- function Ctrl($scope) {
- $scope.salutation = 'Hello';
- $scope.name = 'World';
- }
+ angular.module('bindExample', [])
+ .controller('ExampleController', ['$scope', function ($scope) {
+ $scope.salutation = 'Hello';
+ $scope.name = 'World';
+ }]);
</script>
- <div ng-controller="Ctrl">
+ <div ng-controller="ExampleController">
Salutation: <input type="text" ng-model="salutation"><br>
Name: <input type="text" ng-model="name"><br>
<pre ng-bind-template="{{salutation}} {{name}}!"></pre>
</div>
</file>
@@ -27900,24 +28026,24 @@
* @param {expression} ngBindHtml {@link guide/expression Expression} to evaluate.
*
* @example
Try it here: enter text in text box and watch the greeting change.
- <example module="ngBindHtmlExample" deps="angular-sanitize.js">
+ <example module="bindHtmlExample" deps="angular-sanitize.js">
<file name="index.html">
- <div ng-controller="ngBindHtmlCtrl">
+ <div ng-controller="ExampleController">
<p ng-bind-html="myHTML"></p>
</div>
</file>
<file name="script.js">
- angular.module('ngBindHtmlExample', ['ngSanitize'])
-
- .controller('ngBindHtmlCtrl', ['$scope', function ngBindHtmlCtrl($scope) {
- $scope.myHTML =
- 'I am an <code>HTML</code>string with <a href="#">links!</a> and other <em>stuff</em>';
- }]);
+ angular.module('bindHtmlExample', ['ngSanitize'])
+ .controller('ExampleController', ['$scope', function($scope) {
+ $scope.myHTML =
+ 'I am an <code>HTML</code>string with ' +
+ '<a href="#">links!</a> and other <em>stuff</em>';
+ }]);
</file>
<file name="protractor.js" type="protractor">
it('should check ng-bind-html', function() {
expect(element(by.binding('myHTML')).getText()).toBe(
@@ -27925,19 +28051,28 @@
});
</file>
</example>
*/
var ngBindHtmlDirective = ['$sce', '$parse', function($sce, $parse) {
- return function(scope, element, attr) {
- element.addClass('ng-binding').data('$binding', attr.ngBindHtml);
+ return {
+ compile: function (tElement) {
+ tElement.addClass('ng-binding');
- var parsed = $parse(attr.ngBindHtml);
- function getStringValue() { return (parsed(scope) || '').toString(); }
+ return function (scope, element, attr) {
+ element.data('$binding', attr.ngBindHtml);
- scope.$watch(getStringValue, function ngBindHtmlWatchAction(value) {
- element.html($sce.getTrustedHtml(parsed(scope)) || '');
- });
+ var parsed = $parse(attr.ngBindHtml);
+
+ function getStringValue() {
+ return (parsed(scope) || '').toString();
+ }
+
+ scope.$watch(getStringValue, function ngBindHtmlWatchAction(value) {
+ element.html($sce.getTrustedHtml(parsed(scope)) || '');
+ });
+ };
+ }
};
}];
function classDirective(name, selector) {
name = 'ngClass' + name;
@@ -28412,11 +28547,11 @@
* * Since there is always a `.` in the bindings, you don't have to worry about prototypal
* inheritance masking primitives.
*
* This example demonstrates the `controller as` syntax.
*
- * <example name="ngControllerAs">
+ * <example name="ngControllerAs" module="controllerAsExample">
* <file name="index.html">
* <div id="ctrl-as-exmpl" ng-controller="SettingsController1 as settings">
* Name: <input type="text" ng-model="settings.name"/>
* [ <a href="" ng-click="settings.greet()">greet</a> ]<br/>
* Contact:
@@ -28433,10 +28568,13 @@
* <li>[ <a href="" ng-click="settings.addContact()">add</a> ]</li>
* </ul>
* </div>
* </file>
* <file name="app.js">
+ * angular.module('controllerAsExample', [])
+ * .controller('SettingsController1', SettingsController1);
+ *
* function SettingsController1() {
* this.name = "John Smith";
* this.contacts = [
* {type: 'phone', value: '408 555 1212'},
* {type: 'email', value: 'john.smith@example.org'} ];
@@ -28461,42 +28599,42 @@
* };
* </file>
* <file name="protractor.js" type="protractor">
* it('should check controller as', function() {
* var container = element(by.id('ctrl-as-exmpl'));
- * expect(container.findElement(by.model('settings.name'))
+ * expect(container.element(by.model('settings.name'))
* .getAttribute('value')).toBe('John Smith');
*
* var firstRepeat =
- * container.findElement(by.repeater('contact in settings.contacts').row(0));
+ * container.element(by.repeater('contact in settings.contacts').row(0));
* var secondRepeat =
- * container.findElement(by.repeater('contact in settings.contacts').row(1));
+ * container.element(by.repeater('contact in settings.contacts').row(1));
*
- * expect(firstRepeat.findElement(by.model('contact.value')).getAttribute('value'))
+ * expect(firstRepeat.element(by.model('contact.value')).getAttribute('value'))
* .toBe('408 555 1212');
*
- * expect(secondRepeat.findElement(by.model('contact.value')).getAttribute('value'))
+ * expect(secondRepeat.element(by.model('contact.value')).getAttribute('value'))
* .toBe('john.smith@example.org');
*
- * firstRepeat.findElement(by.linkText('clear')).click();
+ * firstRepeat.element(by.linkText('clear')).click();
*
- * expect(firstRepeat.findElement(by.model('contact.value')).getAttribute('value'))
+ * expect(firstRepeat.element(by.model('contact.value')).getAttribute('value'))
* .toBe('');
*
- * container.findElement(by.linkText('add')).click();
+ * container.element(by.linkText('add')).click();
*
- * expect(container.findElement(by.repeater('contact in settings.contacts').row(2))
- * .findElement(by.model('contact.value'))
+ * expect(container.element(by.repeater('contact in settings.contacts').row(2))
+ * .element(by.model('contact.value'))
* .getAttribute('value'))
* .toBe('yourname@example.org');
* });
* </file>
* </example>
*
* This example demonstrates the "attach to `$scope`" style of controller.
*
- * <example name="ngController">
+ * <example name="ngController" module="controllerExample">
* <file name="index.html">
* <div id="ctrl-exmpl" ng-controller="SettingsController2">
* Name: <input type="text" ng-model="name"/>
* [ <a href="" ng-click="greet()">greet</a> ]<br/>
* Contact:
@@ -28513,10 +28651,13 @@
* <li>[ <a href="" ng-click="addContact()">add</a> ]</li>
* </ul>
* </div>
* </file>
* <file name="app.js">
+ * angular.module('controllerExample', [])
+ * .controller('SettingsController2', ['$scope', SettingsController2]);
+ *
* function SettingsController2($scope) {
* $scope.name = "John Smith";
* $scope.contacts = [
* {type:'phone', value:'408 555 1212'},
* {type:'email', value:'john.smith@example.org'} ];
@@ -28542,32 +28683,32 @@
* </file>
* <file name="protractor.js" type="protractor">
* it('should check controller', function() {
* var container = element(by.id('ctrl-exmpl'));
*
- * expect(container.findElement(by.model('name'))
+ * expect(container.element(by.model('name'))
* .getAttribute('value')).toBe('John Smith');
*
* var firstRepeat =
- * container.findElement(by.repeater('contact in contacts').row(0));
+ * container.element(by.repeater('contact in contacts').row(0));
* var secondRepeat =
- * container.findElement(by.repeater('contact in contacts').row(1));
+ * container.element(by.repeater('contact in contacts').row(1));
*
- * expect(firstRepeat.findElement(by.model('contact.value')).getAttribute('value'))
+ * expect(firstRepeat.element(by.model('contact.value')).getAttribute('value'))
* .toBe('408 555 1212');
- * expect(secondRepeat.findElement(by.model('contact.value')).getAttribute('value'))
+ * expect(secondRepeat.element(by.model('contact.value')).getAttribute('value'))
* .toBe('john.smith@example.org');
*
- * firstRepeat.findElement(by.linkText('clear')).click();
+ * firstRepeat.element(by.linkText('clear')).click();
*
- * expect(firstRepeat.findElement(by.model('contact.value')).getAttribute('value'))
+ * expect(firstRepeat.element(by.model('contact.value')).getAttribute('value'))
* .toBe('');
*
- * container.findElement(by.linkText('add')).click();
+ * container.element(by.linkText('add')).click();
*
- * expect(container.findElement(by.repeater('contact in contacts').row(2))
- * .findElement(by.model('contact.value'))
+ * expect(container.element(by.repeater('contact in contacts').row(2))
+ * .element(by.model('contact.value'))
* .getAttribute('value'))
* .toBe('yourname@example.org');
* });
* </file>
*</example>
@@ -28590,24 +28731,37 @@
* Enables [CSP (Content Security Policy)](https://developer.mozilla.org/en/Security/CSP) support.
*
* This is necessary when developing things like Google Chrome Extensions.
*
* CSP forbids apps to use `eval` or `Function(string)` generated functions (among other things).
- * For us to be compatible, we just need to implement the "getterFn" in $parse without violating
- * any of these restrictions.
+ * For Angular to be CSP compatible there are only two things that we need to do differently:
*
+ * - don't use `Function` constructor to generate optimized value getters
+ * - don't inject custom stylesheet into the document
+ *
* AngularJS uses `Function(string)` generated functions as a speed optimization. Applying the `ngCsp`
* directive will cause Angular to use CSP compatibility mode. When this mode is on AngularJS will
* evaluate all expressions up to 30% slower than in non-CSP mode, but no security violations will
* be raised.
*
* CSP forbids JavaScript to inline stylesheet rules. In non CSP mode Angular automatically
* includes some CSS rules (e.g. {@link ng.directive:ngCloak ngCloak}).
* To make those directives work in CSP mode, include the `angular-csp.css` manually.
*
- * In order to use this feature put the `ngCsp` directive on the root element of the application.
+ * Angular tries to autodetect if CSP is active and automatically turn on the CSP-safe mode. This
+ * autodetection however triggers a CSP error to be logged in the console:
*
+ * ```
+ * Refused to evaluate a string as JavaScript because 'unsafe-eval' is not an allowed source of
+ * script in the following Content Security Policy directive: "default-src 'self'". Note that
+ * 'script-src' was not explicitly set, so 'default-src' is used as a fallback.
+ * ```
+ *
+ * This error is harmless but annoying. To prevent the error from showing up, put the `ngCsp`
+ * directive on the root element of the application or on the `angular.js` script tag, whichever
+ * appears first in the html document.
+ *
* *Note: This directive is only available in the `ng-csp` and `data-ng-csp` attribute form.*
*
* @example
* This example shows how to apply the `ngCsp` directive to the `html` tag.
```html
@@ -28617,13 +28771,13 @@
...
</html>
```
*/
-// ngCsp is not implemented as a proper directive any more, because we need it be processed while we bootstrap
-// the system (before $parse is instantiated), for this reason we just have a csp() fn that looks for ng-csp attribute
-// anywhere in the current doc
+// ngCsp is not implemented as a proper directive any more, because we need it be processed while we
+// bootstrap the system (before $parse is instantiated), for this reason we just have
+// the csp.isActive() fn that looks for ng-csp attribute anywhere in the current doc
/**
* @ngdoc directive
* @name ngClick
*
@@ -28934,25 +29088,26 @@
* @priority 0
* @param {expression} ngSubmit {@link guide/expression Expression} to eval.
* ({@link guide/expression#-event- Event object is available as `$event`})
*
* @example
- <example>
+ <example module="submitExample">
<file name="index.html">
<script>
- function Ctrl($scope) {
- $scope.list = [];
- $scope.text = 'hello';
- $scope.submit = function() {
- if ($scope.text) {
- $scope.list.push(this.text);
- $scope.text = '';
- }
- };
- }
+ angular.module('submitExample', [])
+ .controller('ExampleController', ['$scope', function($scope) {
+ $scope.list = [];
+ $scope.text = 'hello';
+ $scope.submit = function() {
+ if ($scope.text) {
+ $scope.list.push(this.text);
+ $scope.text = '';
+ }
+ };
+ }]);
</script>
- <form ng-submit="submit()" ng-controller="Ctrl">
+ <form ng-submit="submit()" ng-controller="ExampleController">
Enter text and hit enter:
<input type="text" ng-model="text" name="text" />
<input type="submit" id="submit" value="Submit" />
<pre>list={{list}}</pre>
</form>
@@ -28960,11 +29115,11 @@
<file name="protractor.js" type="protractor">
it('should check ng-submit', function() {
expect(element(by.binding('list')).getText()).toBe('list=[]');
element(by.css('#submit')).click();
expect(element(by.binding('list')).getText()).toContain('hello');
- expect(element(by.input('text')).getAttribute('value')).toBe('');
+ expect(element(by.model('text')).getAttribute('value')).toBe('');
});
it('should ignore empty strings', function() {
expect(element(by.binding('list')).getText()).toBe('list=[]');
element(by.css('#submit')).click();
element(by.css('#submit')).click();
@@ -29233,13 +29388,13 @@
* - If the attribute is not set, disable scrolling.
* - If the attribute is set without value, enable scrolling.
* - Otherwise enable scrolling only if the expression evaluates to truthy value.
*
* @example
- <example module="ngAnimate" deps="angular-animate.js" animations="true">
+ <example module="includeExample" deps="angular-animate.js" animations="true">
<file name="index.html">
- <div ng-controller="Ctrl">
+ <div ng-controller="ExampleController">
<select ng-model="template" ng-options="t.name for t in templates">
<option value="">(blank)</option>
</select>
url of the template: <tt>{{template.url}}</tt>
<hr/>
@@ -29247,16 +29402,17 @@
<div class="slide-animate" ng-include="template.url"></div>
</div>
</div>
</file>
<file name="script.js">
- function Ctrl($scope) {
- $scope.templates =
- [ { name: 'template1.html', url: 'template1.html'},
- { name: 'template2.html', url: 'template2.html'} ];
- $scope.template = $scope.templates[0];
- }
+ angular.module('includeExample', ['ngAnimate'])
+ .controller('ExampleController', ['$scope', function($scope) {
+ $scope.templates =
+ [ { name: 'template1.html', url: 'template1.html'},
+ { name: 'template2.html', url: 'template2.html'} ];
+ $scope.template = $scope.templates[0];
+ }]);
</file>
<file name="template1.html">
Content of template1.html
</file>
<file name="template2.html">
@@ -29315,21 +29471,21 @@
// Firefox can't handle using selects
// See https://github.com/angular/protractor/issues/480
return;
}
templateSelect.click();
- templateSelect.element.all(by.css('option')).get(2).click();
+ templateSelect.all(by.css('option')).get(2).click();
expect(includeElem.getText()).toMatch(/Content of template2.html/);
});
it('should change to blank', function() {
if (browser.params.browser == 'firefox') {
// Firefox can't handle using selects
return;
}
templateSelect.click();
- templateSelect.element.all(by.css('option')).get(0).click();
+ templateSelect.all(by.css('option')).get(0).click();
expect(includeElem.isPresent()).toBe(false);
});
</file>
</example>
*/
@@ -29477,18 +29633,19 @@
*
* @element ANY
* @param {expression} ngInit {@link guide/expression Expression} to eval.
*
* @example
- <example>
+ <example module="initExample">
<file name="index.html">
<script>
- function Ctrl($scope) {
- $scope.list = [['a', 'b'], ['c', 'd']];
- }
+ angular.module('initExample', [])
+ .controller('ExampleController', ['$scope', function($scope) {
+ $scope.list = [['a', 'b'], ['c', 'd']];
+ }]);
</script>
- <div ng-controller="Ctrl">
+ <div ng-controller="ExampleController">
<div ng-repeat="innerList in list" ng-init="outerIndex = $index">
<div ng-repeat="value in innerList" ng-init="innerIndex = $index">
<span class="example-init">list[ {{outerIndex}} ][ {{innerIndex}} ] = {{value}};</span>
</div>
</div>
@@ -29624,11 +29781,11 @@
* Notice that we are still using two plural categories(one, other), but we added
* three explicit number rules 0, 1 and 2.
* When one person, perhaps John, views the document, "John is viewing" will be shown.
* When three people view the document, no explicit number rule is found, so
* an offset of 2 is taken off 3, and Angular uses 1 to decide the plural category.
- * In this case, plural category 'one' is matched and "John, Marry and one other person are viewing"
+ * In this case, plural category 'one' is matched and "John, Mary and one other person are viewing"
* is shown.
*
* Note that when you specify offsets, you must provide explicit number rules for
* numbers from 0 up to and including the offset. If you use an offset of 3, for example,
* you must provide explicit number rules for 0, 1, 2 and 3. You must also provide plural strings for
@@ -29637,20 +29794,21 @@
* @param {string|expression} count The variable to be bound to.
* @param {string} when The mapping between plural category to its corresponding strings.
* @param {number=} offset Offset to deduct from the total number.
*
* @example
- <example>
+ <example module="pluralizeExample">
<file name="index.html">
<script>
- function Ctrl($scope) {
- $scope.person1 = 'Igor';
- $scope.person2 = 'Misko';
- $scope.personCount = 1;
- }
+ angular.module('pluralizeExample', [])
+ .controller('ExampleController', ['$scope', function($scope) {
+ $scope.person1 = 'Igor';
+ $scope.person2 = 'Misko';
+ $scope.personCount = 1;
+ }]);
</script>
- <div ng-controller="Ctrl">
+ <div ng-controller="ExampleController">
Person 1:<input type="text" ng-model="person1" value="Igor" /><br/>
Person 2:<input type="text" ng-model="person2" value="Misko" /><br/>
Number of People:<input type="text" ng-model="personCount" value="1" /><br/>
<!--- Example with simple pluralization rules for en locale --->
@@ -30506,11 +30664,11 @@
}
</file>
<file name="protractor.js" type="protractor">
var colorSpan = element(by.css('span'));
- iit('should check ng-style', function() {
+ it('should check ng-style', function() {
expect(colorSpan.getCssValue('color')).toBe('rgba(0, 0, 0, 1)');
element(by.css('input[value=\'set color\']')).click();
expect(colorSpan.getCssValue('color')).toBe('rgba(255, 0, 0, 1)');
element(by.css('input[value=clear]')).click();
expect(colorSpan.getCssValue('color')).toBe('rgba(0, 0, 0, 1)');
@@ -30580,13 +30738,13 @@
* are multiple default cases, all of them will be displayed when no other
* case match.
*
*
* @example
- <example module="ngAnimate" deps="angular-animate.js" animations="true">
+ <example module="switchExample" deps="angular-animate.js" animations="true">
<file name="index.html">
- <div ng-controller="Ctrl">
+ <div ng-controller="ExampleController">
<select ng-model="selection" ng-options="item for item in items">
</select>
<tt>selection={{selection}}</tt>
<hr/>
<div class="animate-switch-container"
@@ -30596,14 +30754,15 @@
<div class="animate-switch" ng-switch-default>default</div>
</div>
</div>
</file>
<file name="script.js">
- function Ctrl($scope) {
- $scope.items = ['settings', 'home', 'other'];
- $scope.selection = $scope.items[0];
- }
+ angular.module('switchExample', ['ngAnimate'])
+ .controller('ExampleController', ['$scope', function($scope) {
+ $scope.items = ['settings', 'home', 'other'];
+ $scope.selection = $scope.items[0];
+ }]);
</file>
<file name="animations.css">
.animate-switch-container {
position:relative;
background:white;
@@ -30642,15 +30801,15 @@
it('should start in settings', function() {
expect(switchElem.getText()).toMatch(/Settings Div/);
});
it('should change to home', function() {
- select.element.all(by.css('option')).get(1).click();
+ select.all(by.css('option')).get(1).click();
expect(switchElem.getText()).toMatch(/Home Span/);
});
it('should select default', function() {
- select.element.all(by.css('option')).get(2).click();
+ select.all(by.css('option')).get(2).click();
expect(switchElem.getText()).toMatch(/default/);
});
</file>
</example>
*/
@@ -30738,32 +30897,31 @@
* Any existing content of the element that this directive is placed on will be removed before the transcluded content is inserted.
*
* @element ANY
*
* @example
- <example module="transclude">
+ <example module="transcludeExample">
<file name="index.html">
<script>
- function Ctrl($scope) {
- $scope.title = 'Lorem Ipsum';
- $scope.text = 'Neque porro quisquam est qui dolorem ipsum quia dolor...';
- }
-
- angular.module('transclude', [])
+ angular.module('transcludeExample', [])
.directive('pane', function(){
return {
restrict: 'E',
transclude: true,
scope: { title:'@' },
template: '<div style="border: 1px solid black;">' +
'<div style="background-color: gray">{{title}}</div>' +
'<div ng-transclude></div>' +
'</div>'
};
- });
+ })
+ .controller('ExampleController', ['$scope', function($scope) {
+ $scope.title = 'Lorem Ipsum';
+ $scope.text = 'Neque porro quisquam est qui dolorem ipsum quia dolor...';
+ }]);
</script>
- <div ng-controller="Ctrl">
+ <div ng-controller="ExampleController">
<input ng-model="title"><br>
<textarea ng-model="text"></textarea> <br/>
<pane title="{{title}}">{{text}}</pane>
</div>
</file>
@@ -30918,25 +31076,26 @@
* * `trackexpr`: Used when working with an array of objects. The result of this expression will be
* used to identify the objects in the array. The `trackexpr` will most likely refer to the
* `value` variable (e.g. `value.propertyName`).
*
* @example
- <example>
+ <example module="selectExample">
<file name="index.html">
<script>
- function MyCntrl($scope) {
- $scope.colors = [
- {name:'black', shade:'dark'},
- {name:'white', shade:'light'},
- {name:'red', shade:'dark'},
- {name:'blue', shade:'dark'},
- {name:'yellow', shade:'light'}
- ];
- $scope.myColor = $scope.colors[2]; // red
- }
+ angular.module('selectExample', [])
+ .controller('ExampleController', ['$scope', function($scope) {
+ $scope.colors = [
+ {name:'black', shade:'dark'},
+ {name:'white', shade:'light'},
+ {name:'red', shade:'dark'},
+ {name:'blue', shade:'dark'},
+ {name:'yellow', shade:'light'}
+ ];
+ $scope.myColor = $scope.colors[2]; // red
+ }]);
</script>
- <div ng-controller="MyCntrl">
+ <div ng-controller="ExampleController">
<ul>
<li ng-repeat="color in colors">
Name: <input ng-model="color.name">
[<a href ng-click="colors.splice($index, 1)">X</a>]
</li>
@@ -30969,11 +31128,11 @@
</div>
</file>
<file name="protractor.js" type="protractor">
it('should check ng-options', function() {
expect(element(by.binding('{selected_color:myColor}')).getText()).toMatch('red');
- element.all(by.select('myColor')).first().click();
+ element.all(by.model('myColor')).first().click();
element.all(by.css('select[ng-model="myColor"] option')).first().click();
expect(element(by.binding('{selected_color:myColor}')).getText()).toMatch('black');
element(by.css('.nullable select[ng-model="myColor"]')).click();
element.all(by.css('.nullable select[ng-model="myColor"] option')).first().click();
expect(element(by.binding('{selected_color:myColor}')).getText()).toMatch('null');
@@ -31385,10 +31544,16 @@
lastElement.val(existingOption.id = option.id);
}
// lastElement.prop('selected') provided by jQuery has side-effects
if (existingOption.selected !== option.selected) {
lastElement.prop('selected', (existingOption.selected = option.selected));
+ if (msie) {
+ // See #7692
+ // The selected item wouldn't visually update on IE without this.
+ // Tested on Win7: IE9, IE10 and IE11. Future IEs should be tested as well
+ lastElement.prop('selected', existingOption.selected);
+ }
}
} else {
// grow elements
// if it's a null option
@@ -31399,11 +31564,11 @@
// jQuery(v1.4.2) Bug: We should be able to chain the method calls, but
// in this version of jQuery on some browser the .text() returns a string
// rather then the element.
(element = optionTemplate.clone())
.val(option.id)
- .attr('selected', option.selected)
+ .prop('selected', option.selected)
.text(option.label);
}
existingOptions.push(existingOption = {
element: element,
@@ -31780,10 +31945,10 @@
}
function push(value) {
if (value === undefined) {
value = '';
- } else if (typeof value != 'string') {
+ } else if (typeof value !== 'string') {
value = angular.toJson(value);
}
result.push('' + value);
}
\ No newline at end of file