1; i++) {
key = ensureSafeMemberName(element.shift(), fullExp);
- var propertyObj = obj[key];
+ var propertyObj = ensureSafeObject(obj[key], fullExp);
if (!propertyObj) {
propertyObj = {};
obj[key] = propertyObj;
@@ -11114,13 +11539,12 @@ function setter(obj, path, setValue, fullExp) {
obj = propertyObj;
}
key = ensureSafeMemberName(element.shift(), fullExp);
- ensureSafeObject(obj, fullExp);
ensureSafeObject(obj[key], fullExp);
obj[key] = setValue;
return setValue;
}
-var getterFnCache = {};
+var getterFnCache = createMap();
/**
* Implementation of the "Black Hole" variant from:
@@ -11161,23 +11585,19 @@ function cspSafeGetterFn(key0, key1, key2, key3, key4, fullExp) {
}
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)) {
- return getterFnCache[path];
- }
+ var fn = getterFnCache[path];
+
+ if (fn) return fn;
var pathKeys = path.split('.'),
- pathKeysLength = pathKeys.length,
- fn;
+ pathKeysLength = pathKeys.length;
// http://jsperf.com/angularjs-parse-getter/6
if (options.csp) {
if (pathKeysLength < 6) {
fn = cspSafeGetterFn(pathKeys[0], pathKeys[1], pathKeys[2], pathKeys[3], pathKeys[4], fullExp);
} else {
- fn = function(scope, locals) {
+ fn = function cspSafeGetter(scope, locals) {
var i = 0, val;
do {
val = cspSafeGetterFn(pathKeys[i++], pathKeys[i++], pathKeys[i++], pathKeys[i++],
@@ -11190,7 +11610,7 @@ function getterFn(path, options, fullExp) {
};
}
} else {
- var code = 'var p;\n';
+ var code = '';
forEach(pathKeys, function(key, index) {
ensureSafeMemberName(key, fullExp);
code += 'if(s == null) return undefined;\n' +
@@ -11198,22 +11618,23 @@ function getterFn(path, options, fullExp) {
// we simply dereference 's' on any .dot notation
? 's'
// but if we are first then we check locals first, and if so read it first
- : '((k&&k.hasOwnProperty("' + key + '"))?k:s)') + '.' + key + ';\n';
+ : '((l&&l.hasOwnProperty("' + key + '"))?l:s)') + '.' + key + ';\n';
});
code += 'return s;';
/* jshint -W054 */
- var evaledFnGetter = new Function('s', 'k', code); // s=scope, k=locals
+ var evaledFnGetter = new Function('s', 'l', code); // s=scope, l=locals
/* jshint +W054 */
evaledFnGetter.toString = valueFn(code);
+
fn = evaledFnGetter;
}
- // Only cache the value if it's not going to mess up the cache object
- // This is more performant that using Object.prototype.hasOwnProperty.call
- if (path !== 'hasOwnProperty') {
- getterFnCache[path] = fn;
- }
+ fn.sharedGetter = true;
+ fn.assign = function(self, value) {
+ return setter(self, path, value, path);
+ };
+ getterFnCache[path] = fn;
return fn;
}
@@ -11263,14 +11684,13 @@ function getterFn(path, options, fullExp) {
/**
* @ngdoc provider
* @name $parseProvider
- * @kind function
*
* @description
* `$parseProvider` can be used for configuring the default behavior of the {@link ng.$parse $parse}
* service.
*/
function $ParseProvider() {
- var cache = {};
+ var cache = createMap();
var $parseOptions = {
csp: false
@@ -11280,15 +11700,31 @@ function $ParseProvider() {
this.$get = ['$filter', '$sniffer', function($filter, $sniffer) {
$parseOptions.csp = $sniffer.csp;
- return function(exp, interceptorFn) {
- var parsedExpression, oneTime,
- cacheKey = (exp = trim(exp));
+ function wrapSharedExpression(exp) {
+ var wrapped = exp;
+
+ if (exp.sharedGetter) {
+ wrapped = function $parseWrapper(self, locals) {
+ return exp(self, locals);
+ };
+ wrapped.literal = exp.literal;
+ wrapped.constant = exp.constant;
+ wrapped.assign = exp.assign;
+ }
+
+ return wrapped;
+ }
+
+ return function $parse(exp, interceptorFn) {
+ var parsedExpression, oneTime, cacheKey;
switch (typeof exp) {
case 'string':
- if (cache.hasOwnProperty(cacheKey)) {
- parsedExpression = cache[cacheKey];
- } else {
+ cacheKey = exp = exp.trim();
+
+ parsedExpression = cache[cacheKey];
+
+ if (!parsedExpression) {
if (exp.charAt(0) === ':' && exp.charAt(1) === ':') {
oneTime = true;
exp = exp.substring(2);
@@ -11298,14 +11734,19 @@ function $ParseProvider() {
var parser = new Parser(lexer, $filter, $parseOptions);
parsedExpression = parser.parse(exp);
- if (parsedExpression.constant) parsedExpression.$$watchDelegate = constantWatch;
- else if (oneTime) parsedExpression.$$watchDelegate = oneTimeWatch;
-
- if (cacheKey !== 'hasOwnProperty') {
- // Only cache the value if it's not going to mess up the cache object
- // This is more performant that using Object.prototype.hasOwnProperty.call
- cache[cacheKey] = parsedExpression;
+ if (parsedExpression.constant) {
+ parsedExpression.$$watchDelegate = constantWatchDelegate;
+ } else if (oneTime) {
+ //oneTime is not part of the exp passed to the Parser so we may have to
+ //wrap the parsedExpression before adding a $$watchDelegate
+ parsedExpression = wrapSharedExpression(parsedExpression);
+ parsedExpression.$$watchDelegate = parsedExpression.literal ?
+ oneTimeLiteralWatchDelegate : oneTimeWatchDelegate;
+ } else if (parsedExpression.inputs) {
+ parsedExpression.$$watchDelegate = inputsWatchDelegate;
}
+
+ cache[cacheKey] = parsedExpression;
}
return addInterceptor(parsedExpression, interceptorFn);
@@ -11317,7 +11758,89 @@ function $ParseProvider() {
}
};
- function oneTimeWatch(scope, listener, objectEquality, deregisterNotifier, parsedExpression) {
+ function collectExpressionInputs(inputs, list) {
+ for (var i = 0, ii = inputs.length; i < ii; i++) {
+ var input = inputs[i];
+ if (!input.constant) {
+ if (input.inputs) {
+ collectExpressionInputs(input.inputs, list);
+ } else if (list.indexOf(input) === -1) { // TODO(perf) can we do better?
+ list.push(input);
+ }
+ }
+ }
+
+ return list;
+ }
+
+ function expressionInputDirtyCheck(newValue, oldValueOfValue) {
+
+ if (newValue == null || oldValueOfValue == null) { // null/undefined
+ return newValue === oldValueOfValue;
+ }
+
+ if (typeof newValue === 'object') {
+
+ // attempt to convert the value to a primitive type
+ // TODO(docs): add a note to docs that by implementing valueOf even objects and arrays can
+ // be cheaply dirty-checked
+ newValue = newValue.valueOf();
+
+ if (typeof newValue === 'object') {
+ // objects/arrays are not supported - deep-watching them would be too expensive
+ return false;
+ }
+
+ // fall-through to the primitive equality check
+ }
+
+ //Primitive or NaN
+ return newValue === oldValueOfValue || (newValue !== newValue && oldValueOfValue !== oldValueOfValue);
+ }
+
+ function inputsWatchDelegate(scope, listener, objectEquality, parsedExpression) {
+ var inputExpressions = parsedExpression.$$inputs ||
+ (parsedExpression.$$inputs = collectExpressionInputs(parsedExpression.inputs, []));
+
+ var lastResult;
+
+ if (inputExpressions.length === 1) {
+ var oldInputValue = expressionInputDirtyCheck; // init to something unique so that equals check fails
+ inputExpressions = inputExpressions[0];
+ return scope.$watch(function expressionInputWatch(scope) {
+ var newInputValue = inputExpressions(scope);
+ if (!expressionInputDirtyCheck(newInputValue, oldInputValue)) {
+ lastResult = parsedExpression(scope);
+ oldInputValue = newInputValue && newInputValue.valueOf();
+ }
+ return lastResult;
+ }, listener, objectEquality);
+ }
+
+ var oldInputValueOfValues = [];
+ for (var i = 0, ii = inputExpressions.length; i < ii; i++) {
+ oldInputValueOfValues[i] = expressionInputDirtyCheck; // init to something unique so that equals check fails
+ }
+
+ return scope.$watch(function expressionInputsWatch(scope) {
+ var changed = false;
+
+ for (var i = 0, ii = inputExpressions.length; i < ii; i++) {
+ var newInputValue = inputExpressions[i](scope);
+ if (changed || (changed = !expressionInputDirtyCheck(newInputValue, oldInputValueOfValues[i]))) {
+ oldInputValueOfValues[i] = newInputValue && newInputValue.valueOf();
+ }
+ }
+
+ if (changed) {
+ lastResult = parsedExpression(scope);
+ }
+
+ return lastResult;
+ }, listener, objectEquality);
+ }
+
+ function oneTimeWatchDelegate(scope, listener, objectEquality, parsedExpression) {
var unwatch, lastValue;
return unwatch = scope.$watch(function oneTimeWatch(scope) {
return parsedExpression(scope);
@@ -11333,10 +11856,34 @@ function $ParseProvider() {
}
});
}
- }, objectEquality, deregisterNotifier);
+ }, objectEquality);
}
- function constantWatch(scope, listener, objectEquality, deregisterNotifier, parsedExpression) {
+ function oneTimeLiteralWatchDelegate(scope, listener, objectEquality, parsedExpression) {
+ var unwatch;
+ return unwatch = scope.$watch(function oneTimeWatch(scope) {
+ return parsedExpression(scope);
+ }, function oneTimeListener(value, old, scope) {
+ if (isFunction(listener)) {
+ listener.call(this, value, old, scope);
+ }
+ if (isAllDefined(value)) {
+ scope.$$postDigest(function () {
+ if(isAllDefined(value)) unwatch();
+ });
+ }
+ }, objectEquality);
+
+ function isAllDefined(value) {
+ var allDefined = true;
+ forEach(value, function (val) {
+ if (!isDefined(val)) allDefined = false;
+ });
+ return allDefined;
+ }
+ }
+
+ function constantWatchDelegate(scope, listener, objectEquality, parsedExpression) {
var unwatch;
return unwatch = scope.$watch(function constantWatch(scope) {
return parsedExpression(scope);
@@ -11345,23 +11892,32 @@ function $ParseProvider() {
listener.apply(this, arguments);
}
unwatch();
- }, objectEquality, deregisterNotifier);
+ }, objectEquality);
}
function addInterceptor(parsedExpression, interceptorFn) {
- if (isFunction(interceptorFn)) {
- var fn = function interceptedExpression(scope, locals) {
- var value = parsedExpression(scope, locals);
- var result = interceptorFn(value, scope, locals);
- // we only return the interceptor's result if the
- // initial value is defined (for bind-once)
- return isDefined(value) ? result : value;
- };
+ if (!interceptorFn) return parsedExpression;
+
+ var fn = function interceptedExpression(scope, locals) {
+ var value = parsedExpression(scope, locals);
+ var result = interceptorFn(value, scope, locals);
+ // we only return the interceptor's result if the
+ // initial value is defined (for bind-once)
+ return isDefined(value) ? result : value;
+ };
+
+ // Propagate $$watchDelegates other then inputsWatchDelegate
+ if (parsedExpression.$$watchDelegate &&
+ parsedExpression.$$watchDelegate !== inputsWatchDelegate) {
fn.$$watchDelegate = parsedExpression.$$watchDelegate;
- return fn;
- } else {
- return parsedExpression;
+ } else if (!interceptorFn.$stateful) {
+ // If there is an interceptor, but no watchDelegate then treat the interceptor like
+ // we treat filters - it is assumed to be a pure function unless flagged with $stateful
+ fn.$$watchDelegate = inputsWatchDelegate;
+ fn.inputs = [parsedExpression];
}
+
+ return fn;
}
}];
}
@@ -11374,16 +11930,16 @@ function $ParseProvider() {
* @description
* A promise/deferred implementation inspired by [Kris Kowal's Q](https://github.com/kriskowal/q).
*
- * $q can be used in two fashions --- One, which is more similar to Kris Kowal's Q or jQuery's Deferred
- * implementations, the other resembles ES6 promises to some degree.
+ * $q can be used in two fashions --- one which is more similar to Kris Kowal's Q or jQuery's Deferred
+ * implementations, and the other which resembles ES6 promises to some degree.
*
* # $q constructor
*
* The streamlined ES6 style promise is essentially just using $q as a constructor which takes a `resolver`
- * function as the first argument). This is similar to the native Promise implementation from ES6 Harmony,
+ * function as the first argument. This is similar to the native Promise implementation from ES6 Harmony,
* see [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise).
*
- * While the constructor-style use is supported, not all of the supporting methods from Harmony promises are
+ * While the constructor-style use is supported, not all of the supporting methods from ES6 Harmony promises are
* available yet.
*
* It can be used like so:
@@ -11410,9 +11966,9 @@ function $ParseProvider() {
* });
* ```
*
- * Note, progress/notify callbacks are not currently supported via the ES6-style interface.
+ * Note: progress/notify callbacks are not currently supported via the ES6-style interface.
*
- * However, the more traditional CommonJS style usage is still available, and documented below.
+ * However, the more traditional CommonJS-style usage is still available, and documented below.
*
* [The CommonJS Promise proposal](http://wiki.commonjs.org/wiki/Promises) describes a promise as an
* interface for interacting with an object that represents the result of an action that is
@@ -11500,7 +12056,7 @@ function $ParseProvider() {
*
* This method *returns a new promise* which is resolved or rejected via the return value of the
* `successCallback`, `errorCallback`. It also notifies via the return value of the
- * `notifyCallback` method. The promise can not be resolved or rejected from the notifyCallback
+ * `notifyCallback` method. The promise cannot be resolved or rejected from the notifyCallback
* method.
*
* - `catch(errorCallback)` – shorthand for `promise.then(null, errorCallback)`
@@ -11570,7 +12126,7 @@ function $ParseProvider() {
* ```
*
* @param {function(function, function)} resolver Function which is responsible for resolving or
- * rejecting the newly created promise. The first parameteter is a function which resolves the
+ * rejecting the newly created promise. The first parameter is a function which resolves the
* promise, the second parameter is a function which rejects the promise.
*
* @returns {Promise} The newly created promise.
@@ -11595,16 +12151,29 @@ function $$QProvider() {
/**
* Constructs a promise manager.
*
- * @param {function(Function)} nextTick Function for executing functions in the next turn.
+ * @param {function(function)} nextTick Function for executing functions in the next turn.
* @param {function(...*)} exceptionHandler Function into which unexpected exceptions are passed for
* debugging purposes.
* @returns {object} Promise manager.
*/
function qFactory(nextTick, exceptionHandler) {
+ var $qMinErr = minErr('$q', TypeError);
+ function callOnce(self, resolveFn, rejectFn) {
+ var called = false;
+ function wrap(fn) {
+ return function(value) {
+ if (called) return;
+ called = true;
+ fn.call(self, value);
+ };
+ }
+
+ return [wrap(resolveFn), wrap(rejectFn)];
+ }
/**
* @ngdoc method
- * @name $q#defer
+ * @name ng.$q#defer
* @kind function
*
* @description
@@ -11613,152 +12182,148 @@ function qFactory(nextTick, exceptionHandler) {
* @returns {Deferred} Returns a new instance of deferred.
*/
var defer = function() {
- var pending = [],
- value, deferred;
-
- deferred = {
-
- resolve: function(val) {
- if (pending) {
- var callbacks = pending;
- pending = undefined;
- value = ref(val);
-
- if (callbacks.length) {
- nextTick(function() {
- var callback;
- for (var i = 0, ii = callbacks.length; i < ii; i++) {
- callback = callbacks[i];
- value.then(callback[0], callback[1], callback[2]);
- }
- });
- }
- }
- },
-
-
- reject: function(reason) {
- deferred.resolve(createInternalRejectedPromise(reason));
- },
-
-
- notify: function(progress) {
- if (pending) {
- var callbacks = pending;
-
- if (pending.length) {
- nextTick(function() {
- var callback;
- for (var i = 0, ii = callbacks.length; i < ii; i++) {
- callback = callbacks[i];
- callback[2](progress);
- }
- });
- }
- }
- },
-
-
- promise: {
- then: function(callback, errback, progressback) {
- var result = defer();
-
- var wrappedCallback = function(value) {
- try {
- result.resolve((isFunction(callback) ? callback : defaultCallback)(value));
- } catch(e) {
- result.reject(e);
- exceptionHandler(e);
- }
- };
-
- var wrappedErrback = function(reason) {
- try {
- result.resolve((isFunction(errback) ? errback : defaultErrback)(reason));
- } catch(e) {
- result.reject(e);
- exceptionHandler(e);
- }
- };
-
- var wrappedProgressback = function(progress) {
- try {
- result.notify((isFunction(progressback) ? progressback : defaultCallback)(progress));
- } catch(e) {
- exceptionHandler(e);
- }
- };
-
- if (pending) {
- pending.push([wrappedCallback, wrappedErrback, wrappedProgressback]);
- } else {
- value.then(wrappedCallback, wrappedErrback, wrappedProgressback);
- }
-
- return result.promise;
- },
-
- "catch": function(callback) {
- return this.then(null, callback);
- },
-
- "finally": function(callback) {
-
- function makePromise(value, resolved) {
- var result = defer();
- if (resolved) {
- result.resolve(value);
- } else {
- result.reject(value);
- }
- return result.promise;
- }
-
- function handleCallback(value, isResolved) {
- var callbackOutput = null;
- try {
- callbackOutput = (callback ||defaultCallback)();
- } catch(e) {
- return makePromise(e, false);
- }
- if (isPromiseLike(callbackOutput)) {
- return callbackOutput.then(function() {
- return makePromise(value, isResolved);
- }, function(error) {
- return makePromise(error, false);
- });
- } else {
- return makePromise(value, isResolved);
- }
- }
-
- return this.then(function(value) {
- return handleCallback(value, true);
- }, function(error) {
- return handleCallback(error, false);
- });
- }
- }
- };
-
- return deferred;
+ return new Deferred();
};
+ function Promise() {
+ this.$$state = { status: 0 };
+ }
- var ref = function(value) {
- if (isPromiseLike(value)) return value;
- return {
- then: function(callback) {
- var result = defer();
+ Promise.prototype = {
+ then: function(onFulfilled, onRejected, progressBack) {
+ var result = new Deferred();
+
+ this.$$state.pending = this.$$state.pending || [];
+ this.$$state.pending.push([result, onFulfilled, onRejected, progressBack]);
+ if (this.$$state.status > 0) scheduleProcessQueue(this.$$state);
+
+ return result.promise;
+ },
+
+ "catch": function(callback) {
+ return this.then(null, callback);
+ },
+
+ "finally": function(callback, progressBack) {
+ return this.then(function(value) {
+ return handleCallback(value, true, callback);
+ }, function(error) {
+ return handleCallback(error, false, callback);
+ }, progressBack);
+ }
+ };
+
+ //Faster, more basic than angular.bind http://jsperf.com/angular-bind-vs-custom-vs-native
+ function simpleBind(context, fn) {
+ return function(value) {
+ fn.call(context, value);
+ };
+ }
+
+ function processQueue(state) {
+ var fn, promise, pending;
+
+ pending = state.pending;
+ state.processScheduled = false;
+ state.pending = undefined;
+ for (var i = 0, ii = pending.length; i < ii; ++i) {
+ promise = pending[i][0];
+ fn = pending[i][state.status];
+ try {
+ if (isFunction(fn)) {
+ promise.resolve(fn(state.value));
+ } else if (state.status === 1) {
+ promise.resolve(state.value);
+ } else {
+ promise.reject(state.value);
+ }
+ } catch(e) {
+ promise.reject(e);
+ exceptionHandler(e);
+ }
+ }
+ }
+
+ function scheduleProcessQueue(state) {
+ if (state.processScheduled || !state.pending) return;
+ state.processScheduled = true;
+ nextTick(function() { processQueue(state); });
+ }
+
+ function Deferred() {
+ this.promise = new Promise();
+ //Necessary to support unbound execution :/
+ this.resolve = simpleBind(this, this.resolve);
+ this.reject = simpleBind(this, this.reject);
+ this.notify = simpleBind(this, this.notify);
+ }
+
+ Deferred.prototype = {
+ resolve: function(val) {
+ if (this.promise.$$state.status) return;
+ if (val === this.promise) {
+ this.$$reject($qMinErr(
+ 'qcycle',
+ "Expected promise to be resolved with value other than itself '{0}'",
+ val));
+ }
+ else {
+ this.$$resolve(val);
+ }
+
+ },
+
+ $$resolve: function(val) {
+ var then, fns;
+
+ fns = callOnce(this, this.$$resolve, this.$$reject);
+ try {
+ if ((isObject(val) || isFunction(val))) then = val && val.then;
+ if (isFunction(then)) {
+ this.promise.$$state.status = -1;
+ then.call(val, fns[0], fns[1], this.notify);
+ } else {
+ this.promise.$$state.value = val;
+ this.promise.$$state.status = 1;
+ scheduleProcessQueue(this.promise.$$state);
+ }
+ } catch(e) {
+ fns[1](e);
+ exceptionHandler(e);
+ }
+ },
+
+ reject: function(reason) {
+ if (this.promise.$$state.status) return;
+ this.$$reject(reason);
+ },
+
+ $$reject: function(reason) {
+ this.promise.$$state.value = reason;
+ this.promise.$$state.status = 2;
+ scheduleProcessQueue(this.promise.$$state);
+ },
+
+ notify: function(progress) {
+ var callbacks = this.promise.$$state.pending;
+
+ if ((this.promise.$$state.status <= 0) && callbacks && callbacks.length) {
nextTick(function() {
- result.resolve(callback(value));
+ var callback, result;
+ for (var i = 0, ii = callbacks.length; i < ii; i++) {
+ result = callbacks[i][0];
+ callback = callbacks[i][3];
+ try {
+ result.notify(isFunction(callback) ? callback(progress) : progress);
+ } catch(e) {
+ exceptionHandler(e);
+ }
+ }
});
- return result.promise;
}
- };
+ }
};
-
/**
* @ngdoc method
* @name $q#reject
@@ -11796,28 +12361,38 @@ function qFactory(nextTick, exceptionHandler) {
* @returns {Promise} Returns a promise that was already resolved as rejected with the `reason`.
*/
var reject = function(reason) {
- var result = defer();
+ var result = new Deferred();
result.reject(reason);
return result.promise;
};
- var createInternalRejectedPromise = function(reason) {
- return {
- then: function(callback, errback) {
- var result = defer();
- nextTick(function() {
- try {
- result.resolve((isFunction(errback) ? errback : defaultErrback)(reason));
- } catch(e) {
- result.reject(e);
- exceptionHandler(e);
- }
- });
- return result.promise;
- }
- };
+ var makePromise = function makePromise(value, resolved) {
+ var result = new Deferred();
+ if (resolved) {
+ result.resolve(value);
+ } else {
+ result.reject(value);
+ }
+ return result.promise;
};
+ var handleCallback = function handleCallback(value, isResolved, callback) {
+ var callbackOutput = null;
+ try {
+ if (isFunction(callback)) callbackOutput = callback();
+ } catch(e) {
+ return makePromise(e, false);
+ }
+ if (isPromiseLike(callbackOutput)) {
+ return callbackOutput.then(function() {
+ return makePromise(value, isResolved);
+ }, function(error) {
+ return makePromise(error, false);
+ });
+ } else {
+ return makePromise(value, isResolved);
+ }
+ };
/**
* @ngdoc method
@@ -11832,65 +12407,14 @@ function qFactory(nextTick, exceptionHandler) {
* @param {*} value Value or a promise
* @returns {Promise} Returns a promise of the passed value or promise
*/
- var when = function(value, callback, errback, progressback) {
- var result = defer(),
- done;
- var wrappedCallback = function(value) {
- try {
- return (isFunction(callback) ? callback : defaultCallback)(value);
- } catch (e) {
- exceptionHandler(e);
- return reject(e);
- }
- };
- var wrappedErrback = function(reason) {
- try {
- return (isFunction(errback) ? errback : defaultErrback)(reason);
- } catch (e) {
- exceptionHandler(e);
- return reject(e);
- }
- };
-
- var wrappedProgressback = function(progress) {
- try {
- return (isFunction(progressback) ? progressback : defaultCallback)(progress);
- } catch (e) {
- exceptionHandler(e);
- }
- };
-
- nextTick(function() {
- ref(value).then(function(value) {
- if (done) return;
- done = true;
- result.resolve(ref(value).then(wrappedCallback, wrappedErrback, wrappedProgressback));
- }, function(reason) {
- if (done) return;
- done = true;
- result.resolve(wrappedErrback(reason));
- }, function(progress) {
- if (done) return;
- result.notify(wrappedProgressback(progress));
- });
- });
-
- return result.promise;
+ var when = function(value, callback, errback, progressBack) {
+ var result = new Deferred();
+ result.resolve(value);
+ return result.promise.then(callback, errback, progressBack);
};
-
- function defaultCallback(value) {
- return value;
- }
-
-
- function defaultErrback(reason) {
- return reject(reason);
- }
-
-
/**
* @ngdoc method
* @name $q#all
@@ -11906,14 +12430,15 @@ function qFactory(nextTick, exceptionHandler) {
* If any of the promises is resolved with a rejection, this resulting promise will be rejected
* with the same rejection value.
*/
+
function all(promises) {
- var deferred = defer(),
+ var deferred = new Deferred(),
counter = 0,
results = isArray(promises) ? [] : {};
forEach(promises, function(promise, key) {
counter++;
- ref(promise).then(function(value) {
+ when(promise).then(function(value) {
if (results.hasOwnProperty(key)) return;
results[key] = value;
if (!(--counter)) deferred.resolve(results);
@@ -11932,8 +12457,7 @@ function qFactory(nextTick, exceptionHandler) {
var $Q = function Q(resolver) {
if (!isFunction(resolver)) {
- // TODO(@caitp): minErr this
- throw new TypeError('Expected resolverFn');
+ throw $qMinErr('norslvr', "Expected resolverFn, got '{0}'", resolver);
}
if (!(this instanceof Q)) {
@@ -11941,7 +12465,7 @@ function qFactory(nextTick, exceptionHandler) {
return new Q(resolver);
}
- var deferred = defer();
+ var deferred = new Deferred();
function resolveFn(value) {
deferred.resolve(value);
@@ -12067,6 +12591,7 @@ function $RootScopeProvider(){
var TTL = 10;
var $rootScopeMinErr = minErr('$rootScope');
var lastDirtyWatch = null;
+ var applyAsyncId = null;
this.digestTtl = function(value) {
if (arguments.length) {
@@ -12129,16 +12654,33 @@ function $RootScopeProvider(){
this.$$postDigestQueue = [];
this.$$listeners = {};
this.$$listenerCount = {};
- this.$$isolateBindings = {};
+ this.$$isolateBindings = null;
+ this.$$applyAsyncQueue = [];
}
/**
* @ngdoc property
* @name $rootScope.Scope#$id
- * @returns {number} Unique scope ID (monotonically increasing alphanumeric sequence) useful for
- * debugging.
+ *
+ * @description
+ * Unique scope ID (monotonically increasing) useful for debugging.
*/
+ /**
+ * @ngdoc property
+ * @name $rootScope.Scope#$parent
+ *
+ * @description
+ * Reference to the parent scope.
+ */
+
+ /**
+ * @ngdoc property
+ * @name $rootScope.Scope#$root
+ *
+ * @description
+ * Reference to the root scope.
+ */
Scope.prototype = {
constructor: Scope,
@@ -12150,9 +12692,8 @@ function $RootScopeProvider(){
* @description
* Creates a new child {@link ng.$rootScope.Scope scope}.
*
- * The parent scope will propagate the {@link ng.$rootScope.Scope#$digest $digest()} and
- * {@link ng.$rootScope.Scope#$digest $digest()} events. The scope can be removed from the
- * scope hierarchy using {@link ng.$rootScope.Scope#$destroy $destroy()}.
+ * The parent scope will propagate the {@link ng.$rootScope.Scope#$digest $digest()} event.
+ * The scope can be removed from the scope hierarchy using {@link ng.$rootScope.Scope#$destroy $destroy()}.
*
* {@link ng.$rootScope.Scope#$destroy $destroy()} must be called on a scope when it is
* desired for the scope and its child scopes to be permanently detached from the parent and
@@ -12167,8 +12708,7 @@ function $RootScopeProvider(){
*
*/
$new: function(isolate) {
- var ChildScope,
- child;
+ var child;
if (isolate) {
child = new Scope();
@@ -12179,18 +12719,18 @@ function $RootScopeProvider(){
} else {
// Only create a child scope class if somebody asks for one,
// but cache it to allow the VM to optimize lookups.
- if (!this.$$childScopeClass) {
- this.$$childScopeClass = function() {
+ if (!this.$$ChildScope) {
+ this.$$ChildScope = function ChildScope() {
this.$$watchers = this.$$nextSibling =
this.$$childHead = this.$$childTail = null;
this.$$listeners = {};
this.$$listenerCount = {};
this.$id = nextUid();
- this.$$childScopeClass = null;
+ this.$$ChildScope = null;
};
- this.$$childScopeClass.prototype = this;
+ this.$$ChildScope.prototype = this;
}
- child = new this.$$childScopeClass();
+ child = new this.$$ChildScope();
}
child['this'] = child;
child.$parent = this;
@@ -12244,7 +12784,6 @@ function $RootScopeProvider(){
* can compare the `newVal` and `oldVal`. If these two values are identical (`===`) then the
* listener was called due to initialization.
*
- * The example below contains an illustration of using a function as your $watch listener
*
*
* # Example
@@ -12274,14 +12813,14 @@ function $RootScopeProvider(){
- // Using a listener function
+ // Using a function as a watchExpression
var food;
scope.foodCounter = 0;
expect(scope.foodCounter).toEqual(0);
scope.$watch(
- // This is the listener function
+ // This function returns the value being watched. It is called for each turn of the $digest loop
function() { return food; },
- // This is the change handler
+ // This is the change listener, called when the value returned from the above function changes
function(newValue, oldValue) {
if ( newValue !== oldValue ) {
// Only increment the counter if the value changed
@@ -12319,15 +12858,13 @@ function $RootScopeProvider(){
* - `scope` refers to the current scope
* @param {boolean=} objectEquality Compare for object equality using {@link angular.equals} instead of
* comparing for reference equality.
- * @param {function()=} deregisterNotifier Function to call when the deregistration function
- * get called.
* @returns {function()} Returns a deregistration function for this listener.
*/
- $watch: function(watchExp, listener, objectEquality, deregisterNotifier) {
- var get = compileToFn(watchExp, 'watch');
+ $watch: function(watchExp, listener, objectEquality) {
+ var get = $parse(watchExp);
if (get.$$watchDelegate) {
- return get.$$watchDelegate(this, listener, objectEquality, deregisterNotifier, get);
+ return get.$$watchDelegate(this, listener, objectEquality, get);
}
var scope = this,
array = scope.$$watchers,
@@ -12355,9 +12892,6 @@ function $RootScopeProvider(){
return function deregisterWatch() {
arrayRemove(array, watcher);
lastDirtyWatch = null;
- if (isFunction(deregisterNotifier)) {
- deregisterNotifier();
- }
};
},
@@ -12390,43 +12924,56 @@ function $RootScopeProvider(){
var oldValues = new Array(watchExpressions.length);
var newValues = new Array(watchExpressions.length);
var deregisterFns = [];
- var changeCount = 0;
var self = this;
- var masterUnwatch;
+ var changeReactionScheduled = false;
+ var firstRun = true;
+
+ if (!watchExpressions.length) {
+ // No expressions means we call the listener ASAP
+ var shouldCall = true;
+ self.$evalAsync(function () {
+ if (shouldCall) listener(newValues, newValues, self);
+ });
+ return function deregisterWatchGroup() {
+ shouldCall = false;
+ };
+ }
if (watchExpressions.length === 1) {
// Special case size of one
return this.$watch(watchExpressions[0], function watchGroupAction(value, oldValue, scope) {
newValues[0] = value;
oldValues[0] = oldValue;
- listener.call(this, newValues, (value === oldValue) ? newValues : oldValues, scope);
+ listener(newValues, (value === oldValue) ? newValues : oldValues, scope);
});
}
forEach(watchExpressions, function (expr, i) {
- var unwatch = self.$watch(expr, function watchGroupSubAction(value, oldValue) {
+ var unwatchFn = self.$watch(expr, function watchGroupSubAction(value, oldValue) {
newValues[i] = value;
oldValues[i] = oldValue;
- changeCount++;
- }, false, function watchGroupDeregNotifier() {
- arrayRemove(deregisterFns, unwatch);
- if (!deregisterFns.length) {
- masterUnwatch();
+ if (!changeReactionScheduled) {
+ changeReactionScheduled = true;
+ self.$evalAsync(watchGroupAction);
}
});
-
- deregisterFns.push(unwatch);
- }, this);
-
- masterUnwatch = self.$watch(function watchGroupChangeWatch() {
- return changeCount;
- }, function watchGroupChangeAction(value, oldValue) {
- listener(newValues, (value === oldValue) ? newValues : oldValues, self);
+ deregisterFns.push(unwatchFn);
});
+ function watchGroupAction() {
+ changeReactionScheduled = false;
+
+ if (firstRun) {
+ firstRun = false;
+ listener(newValues, newValues, self);
+ } else {
+ listener(newValues, oldValues, self);
+ }
+ }
+
return function deregisterWatchGroup() {
while (deregisterFns.length) {
- deregisterFns[0]();
+ deregisterFns.shift()();
}
};
},
@@ -12488,6 +13035,8 @@ function $RootScopeProvider(){
* de-registration function is executed, the internal watch operation is terminated.
*/
$watchCollection: function(obj, listener) {
+ $watchCollectionInterceptor.$stateful = true;
+
var self = this;
// the current value, updated on each dirty-check run
var newValue;
@@ -12507,7 +13056,7 @@ function $RootScopeProvider(){
function $watchCollectionInterceptor(_value) {
newValue = _value;
- var newLength, key, bothNaN;
+ var newLength, key, bothNaN, newItem, oldItem;
if (!isObject(newValue)) { // if primitive
if (oldValue !== newValue) {
@@ -12531,11 +13080,13 @@ function $RootScopeProvider(){
}
// copy the items to oldValue and look for changes.
for (var i = 0; i < newLength; i++) {
- bothNaN = (oldValue[i] !== oldValue[i]) &&
- (newValue[i] !== newValue[i]);
- if (!bothNaN && (oldValue[i] !== newValue[i])) {
+ oldItem = oldValue[i];
+ newItem = newValue[i];
+
+ bothNaN = (oldItem !== oldItem) && (newItem !== newItem);
+ if (!bothNaN && (oldItem !== newItem)) {
changeDetected++;
- oldValue[i] = newValue[i];
+ oldValue[i] = newItem;
}
}
} else {
@@ -12550,16 +13101,18 @@ function $RootScopeProvider(){
for (key in newValue) {
if (newValue.hasOwnProperty(key)) {
newLength++;
- if (oldValue.hasOwnProperty(key)) {
- bothNaN = (oldValue[key] !== oldValue[key]) &&
- (newValue[key] !== newValue[key]);
- if (!bothNaN && (oldValue[key] !== newValue[key])) {
+ newItem = newValue[key];
+ oldItem = oldValue[key];
+
+ if (key in oldValue) {
+ bothNaN = (oldItem !== oldItem) && (newItem !== newItem);
+ if (!bothNaN && (oldItem !== newItem)) {
changeDetected++;
- oldValue[key] = newValue[key];
+ oldValue[key] = newItem;
}
} else {
oldLength++;
- oldValue[key] = newValue[key];
+ oldValue[key] = newItem;
changeDetected++;
}
}
@@ -12568,7 +13121,7 @@ function $RootScopeProvider(){
// we used to have more keys, need to find them and destroy them.
changeDetected++;
for(key in oldValue) {
- if (oldValue.hasOwnProperty(key) && !newValue.hasOwnProperty(key)) {
+ if (!newValue.hasOwnProperty(key)) {
oldLength--;
delete oldValue[key];
}
@@ -12673,6 +13226,15 @@ function $RootScopeProvider(){
logIdx, logMsg, asyncTask;
beginPhase('$digest');
+ // Check for changes to browser url that happened in sync before the call to $digest
+ $browser.$$checkUrlChange();
+
+ if (this === $rootScope && applyAsyncId !== null) {
+ // If this is the root scope, and $applyAsync has scheduled a deferred $apply(), then
+ // cancel the scheduled $apply and flush the queue of expressions to be evaluated.
+ $browser.defer.cancel(applyAsyncId);
+ flushApplyAsync();
+ }
lastDirtyWatch = null;
@@ -12685,7 +13247,6 @@ function $RootScopeProvider(){
asyncTask = asyncQueue.shift();
asyncTask.scope.$eval(asyncTask.expression);
} catch (e) {
- clearPhase();
$exceptionHandler(e);
}
lastDirtyWatch = null;
@@ -12728,7 +13289,6 @@ function $RootScopeProvider(){
}
}
} catch (e) {
- clearPhase();
$exceptionHandler(e);
}
}
@@ -12812,7 +13372,9 @@ function $RootScopeProvider(){
this.$$destroyed = true;
if (this === $rootScope) return;
- forEach(this.$$listenerCount, bind(null, decrementListenerCount, this));
+ for (var eventName in this.$$listenerCount) {
+ decrementListenerCount(this, this.$$listenerCount[eventName], eventName);
+ }
// sever all the references to parent scopes (after this cleanup, the current scope should
// not be retained by any of our references and should be eligible for garbage collection)
@@ -12983,6 +13545,33 @@ function $RootScopeProvider(){
}
},
+ /**
+ * @ngdoc method
+ * @name $rootScope.Scope#$applyAsync
+ * @kind function
+ *
+ * @description
+ * Schedule the invokation of $apply to occur at a later time. The actual time difference
+ * varies across browsers, but is typically around ~10 milliseconds.
+ *
+ * This can be used to queue up multiple expressions which need to be evaluated in the same
+ * digest.
+ *
+ * @param {(string|function())=} exp An angular expression to be executed.
+ *
+ * - `string`: execute using the rules as defined in {@link guide/expression expression}.
+ * - `function(scope)`: execute the function with current `scope` parameter.
+ */
+ $applyAsync: function(expr) {
+ var scope = this;
+ expr && $rootScope.$$applyAsyncQueue.push($applyAsyncExpression);
+ scheduleApplyAsync();
+
+ function $applyAsyncExpression() {
+ scope.$eval(expr);
+ }
+ },
+
/**
* @ngdoc method
* @name $rootScope.Scope#$on
@@ -13027,7 +13616,7 @@ function $RootScopeProvider(){
var self = this;
return function() {
- namedListeners[indexOf(namedListeners, listener)] = null;
+ namedListeners[namedListeners.indexOf(listener)] = null;
decrementListenerCount(self, 1, name);
};
},
@@ -13138,8 +13727,11 @@ function $RootScopeProvider(){
event.defaultPrevented = true;
},
defaultPrevented: false
- },
- listenerArgs = concat([event], arguments, 1),
+ };
+
+ if (!target.$$listenerCount[name]) return event;
+
+ var listenerArgs = concat([event], arguments, 1),
listeners, i, length;
//down while you can, then up and next sibling or up and next sibling until back at root
@@ -13196,11 +13788,6 @@ function $RootScopeProvider(){
$rootScope.$$phase = null;
}
- function compileToFn(exp, name) {
- var fn = $parse(exp);
- assertArgFn(fn, name);
- return fn;
- }
function decrementListenerCount(current, count, name) {
do {
@@ -13217,6 +13804,26 @@ function $RootScopeProvider(){
* because it's unique we can easily tell it apart from other values
*/
function initWatchVal() {}
+
+ function flushApplyAsync() {
+ var queue = $rootScope.$$applyAsyncQueue;
+ while (queue.length) {
+ try {
+ queue.shift()();
+ } catch(e) {
+ $exceptionHandler(e);
+ }
+ }
+ applyAsyncId = null;
+ }
+
+ function scheduleApplyAsync() {
+ if (applyAsyncId === null) {
+ applyAsyncId = $browser.defer(function() {
+ $rootScope.$apply(flushApplyAsync);
+ });
+ }
+ }
}];
}
@@ -13226,7 +13833,7 @@ function $RootScopeProvider(){
*/
function $$SanitizeUriProvider() {
var aHrefSanitizationWhitelist = /^\s*(https?|ftp|mailto|tel|file):/,
- imgSrcSanitizationWhitelist = /^\s*(https?|ftp|file|blob):|data:image\//;
+ imgSrcSanitizationWhitelist = /^\s*((https?|ftp|file|blob):|data:image\/)/;
/**
* @description
@@ -14442,6 +15049,173 @@ function $SnifferProvider() {
}];
}
+var $compileMinErr = minErr('$compile');
+
+/**
+ * @ngdoc service
+ * @name $templateRequest
+ *
+ * @description
+ * The `$templateRequest` service downloads the provided template using `$http` and, upon success,
+ * stores the contents inside of `$templateCache`. If the HTTP request fails or the response data
+ * of the HTTP request is empty then a `$compile` error will be thrown (the exception can be thwarted
+ * by setting the 2nd parameter of the function to true).
+ *
+ * @param {string} tpl The HTTP request template URL
+ * @param {boolean=} ignoreRequestError Whether or not to ignore the exception when the request fails or the template is empty
+ *
+ * @return {Promise} the HTTP Promise for the given.
+ *
+ * @property {number} totalPendingRequests total amount of pending template requests being downloaded.
+ */
+function $TemplateRequestProvider() {
+ this.$get = ['$templateCache', '$http', '$q', function($templateCache, $http, $q) {
+ function handleRequestFn(tpl, ignoreRequestError) {
+ var self = handleRequestFn;
+ self.totalPendingRequests++;
+
+ return $http.get(tpl, { cache : $templateCache })
+ .then(function(response) {
+ var html = response.data;
+ if(!html || html.length === 0) {
+ return handleError();
+ }
+
+ self.totalPendingRequests--;
+ $templateCache.put(tpl, html);
+ return html;
+ }, handleError);
+
+ function handleError() {
+ self.totalPendingRequests--;
+ if (!ignoreRequestError) {
+ throw $compileMinErr('tpload', 'Failed to load template: {0}', tpl);
+ }
+ return $q.reject();
+ }
+ }
+
+ handleRequestFn.totalPendingRequests = 0;
+
+ return handleRequestFn;
+ }];
+}
+
+function $$TestabilityProvider() {
+ this.$get = ['$rootScope', '$browser', '$location',
+ function($rootScope, $browser, $location) {
+
+ /**
+ * @name $testability
+ *
+ * @description
+ * The private $$testability service provides a collection of methods for use when debugging
+ * or by automated test and debugging tools.
+ */
+ var testability = {};
+
+ /**
+ * @name $$testability#findBindings
+ *
+ * @description
+ * Returns an array of elements that are bound (via ng-bind or {{}})
+ * to expressions matching the input.
+ *
+ * @param {Element} element The element root to search from.
+ * @param {string} expression The binding expression to match.
+ * @param {boolean} opt_exactMatch If true, only returns exact matches
+ * for the expression. Filters and whitespace are ignored.
+ */
+ testability.findBindings = function(element, expression, opt_exactMatch) {
+ var bindings = element.getElementsByClassName('ng-binding');
+ var matches = [];
+ forEach(bindings, function(binding) {
+ var dataBinding = angular.element(binding).data('$binding');
+ if (dataBinding) {
+ forEach(dataBinding, function(bindingName) {
+ if (opt_exactMatch) {
+ var matcher = new RegExp('(^|\\s)' + expression + '(\\s|\\||$)');
+ if (matcher.test(bindingName)) {
+ matches.push(binding);
+ }
+ } else {
+ if (bindingName.indexOf(expression) != -1) {
+ matches.push(binding);
+ }
+ }
+ });
+ }
+ });
+ return matches;
+ };
+
+ /**
+ * @name $$testability#findModels
+ *
+ * @description
+ * Returns an array of elements that are two-way found via ng-model to
+ * expressions matching the input.
+ *
+ * @param {Element} element The element root to search from.
+ * @param {string} expression The model expression to match.
+ * @param {boolean} opt_exactMatch If true, only returns exact matches
+ * for the expression.
+ */
+ testability.findModels = function(element, expression, opt_exactMatch) {
+ var prefixes = ['ng-', 'data-ng-', 'ng\\:'];
+ for (var p = 0; p < prefixes.length; ++p) {
+ var attributeEquals = opt_exactMatch ? '=' : '*=';
+ var selector = '[' + prefixes[p] + 'model' + attributeEquals + '"' + expression + '"]';
+ var elements = element.querySelectorAll(selector);
+ if (elements.length) {
+ return elements;
+ }
+ }
+ };
+
+ /**
+ * @name $$testability#getLocation
+ *
+ * @description
+ * Shortcut for getting the location in a browser agnostic way. Returns
+ * the path, search, and hash. (e.g. /path?a=b#hash)
+ */
+ testability.getLocation = function() {
+ return $location.url();
+ };
+
+ /**
+ * @name $$testability#setLocation
+ *
+ * @description
+ * Shortcut for navigating to a location without doing a full page reload.
+ *
+ * @param {string} url The location url (path, search and hash,
+ * e.g. /path?a=b#hash) to go to.
+ */
+ testability.setLocation = function(url) {
+ if (url !== $location.url()) {
+ $location.url(url);
+ $rootScope.$digest();
+ }
+ };
+
+ /**
+ * @name $$testability#whenStable
+ *
+ * @description
+ * Calls the callback when $timeout and $http requests are completed.
+ *
+ * @param {function} callback
+ */
+ testability.whenStable = function(callback) {
+ $browser.notifyWhenNoOutstandingRequests(callback);
+ };
+
+ return testability;
+ }];
+}
+
function $TimeoutProvider() {
this.$get = ['$rootScope', '$browser', '$q', '$$q', '$exceptionHandler',
function($rootScope, $browser, $q, $$q, $exceptionHandler) {
@@ -14733,16 +15507,6 @@ function $WindowProvider(){
* For more information about how angular filters work, and how to create your own filters, see
* {@link guide/filter Filters} in the Angular Developer Guide.
*/
-/**
- * @ngdoc method
- * @name $filterProvider#register
- * @description
- * Register filter factory function.
- *
- * @param {String} name Name of the filter.
- * @param {Function} fn The filter factory function which is injectable.
- */
-
/**
* @ngdoc service
@@ -14781,7 +15545,7 @@ function $FilterProvider($provide) {
/**
* @ngdoc method
- * @name $controllerProvider#register
+ * @name $filterProvider#register
* @param {string|Object} name Name of the filter function, or an object map of filters where
* the keys are the filter names and the values are the filter factories.
* @returns {Object} Registered filter instance, or if a map of filters was provided then a map
@@ -14854,11 +15618,13 @@ function $FilterProvider($provide) {
* which have property `name` containing "M" and property `phone` containing "1". A special
* property name `$` can be used (as in `{$:"text"}`) to accept a match against any
* property of the object. That's equivalent to the simple substring match with a `string`
- * as described above.
+ * as described above. The predicate can be negated by prefixing the string with `!`.
+ * For Example `{name: "!M"}` predicate will return an array of items which have property `name`
+ * not containing "M".
*
- * - `function(value)`: A predicate function can be used to write arbitrary filters. The function is
- * called for each element of `array`. The final result is an array of those elements that
- * the predicate returned true for.
+ * - `function(value, index)`: A predicate function can be used to write arbitrary filters. The
+ * function is called for each element of `array`. The final result is an array of those
+ * elements that the predicate returned true for.
*
* @param {function(actual, expected)|true|undefined} comparator Comparator which is used in
* determining if the expected value (from the filter expression) and actual value (from
@@ -14951,9 +15717,9 @@ function filterFilter() {
var comparatorType = typeof(comparator),
predicates = [];
- predicates.check = function(value) {
+ predicates.check = function(value, index) {
for (var j = 0; j < predicates.length; j++) {
- if(!predicates[j](value)) {
+ if(!predicates[j](value, index)) {
return false;
}
}
@@ -15042,7 +15808,7 @@ function filterFilter() {
var filtered = [];
for ( var j = 0; j < array.length; j++) {
var value = array[j];
- if (predicates.check(value)) {
+ if (predicates.check(value, j)) {
filtered.push(value);
}
}
@@ -15103,8 +15869,12 @@ function currencyFilter($locale) {
var formats = $locale.NUMBER_FORMATS;
return function(amount, currencySymbol){
if (isUndefined(currencySymbol)) currencySymbol = formats.CURRENCY_SYM;
- return formatNumber(amount, formats.PATTERNS[1], formats.GROUP_SEP, formats.DECIMAL_SEP, 2).
- replace(/\u00A4/g, currencySymbol);
+
+ // if null or undefined pass it through
+ return (amount == null)
+ ? amount
+ : formatNumber(amount, formats.PATTERNS[1], formats.GROUP_SEP, formats.DECIMAL_SEP, 2).
+ replace(/\u00A4/g, currencySymbol);
};
}
@@ -15163,14 +15933,18 @@ numberFilter.$inject = ['$locale'];
function numberFilter($locale) {
var formats = $locale.NUMBER_FORMATS;
return function(number, fractionSize) {
- return formatNumber(number, formats.PATTERNS[0], formats.GROUP_SEP, formats.DECIMAL_SEP,
- fractionSize);
+
+ // if null or undefined pass it through
+ return (number == null)
+ ? number
+ : formatNumber(number, formats.PATTERNS[0], formats.GROUP_SEP, formats.DECIMAL_SEP,
+ fractionSize);
};
}
var DECIMAL_SEP = '.';
function formatNumber(number, pattern, groupSep, decimalSep, fractionSize) {
- if (number == null || !isFinite(number) || isObject(number)) return '';
+ if (!isFinite(number) || isObject(number)) return '';
var isNegative = number < 0;
number = Math.abs(number);
@@ -15203,6 +15977,10 @@ function formatNumber(number, pattern, groupSep, decimalSep, fractionSize) {
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/round
number = +(Math.round(+(number.toString() + 'e' + fractionSize)).toString() + 'e' + -fractionSize);
+ if (number === 0) {
+ isNegative = false;
+ }
+
var fraction = ('' + number).split(DECIMAL_SEP);
var whole = fraction[0];
fraction = fraction[1] || '';
@@ -15376,14 +16154,14 @@ var DATE_FORMATS_SPLIT = /((?:[^yMdHhmsaZEw']+)|(?:'(?:[^']|'')*')|(?:E+|y+|M+|d
* * `'EEE'`: Day in Week, (Sun-Sat)
* * `'HH'`: Hour in day, padded (00-23)
* * `'H'`: Hour in day (0-23)
- * * `'hh'`: Hour in am/pm, padded (01-12)
- * * `'h'`: Hour in am/pm, (1-12)
+ * * `'hh'`: Hour in AM/PM, padded (01-12)
+ * * `'h'`: Hour in AM/PM, (1-12)
* * `'mm'`: Minute in hour, padded (00-59)
* * `'m'`: Minute in hour (0-59)
* * `'ss'`: Second in minute, padded (00-59)
* * `'s'`: Second in minute (0-59)
* * `'.sss' or ',sss'`: Millisecond in second, padded (000-999)
- * * `'a'`: am/pm marker
+ * * `'a'`: AM/PM marker
* * `'Z'`: 4 digit (+sign) representation of the timezone offset (-1200-+1200)
* * `'ww'`: ISO-8601 week of year (00-53)
* * `'w'`: ISO-8601 week of year (0-53)
@@ -15392,26 +16170,28 @@ var DATE_FORMATS_SPLIT = /((?:[^yMdHhmsaZEw']+)|(?:'(?:[^']|'')*')|(?:E+|y+|M+|d
* {@link guide/i18n localizable formats}:
*
* * `'medium'`: equivalent to `'MMM d, y h:mm:ss a'` for en_US locale
- * (e.g. Sep 3, 2010 12:05:08 pm)
- * * `'short'`: equivalent to `'M/d/yy h:mm a'` for en_US locale (e.g. 9/3/10 12:05 pm)
+ * (e.g. Sep 3, 2010 12:05:08 PM)
+ * * `'short'`: equivalent to `'M/d/yy h:mm a'` for en_US locale (e.g. 9/3/10 12:05 PM)
* * `'fullDate'`: equivalent to `'EEEE, MMMM d, y'` for en_US locale
* (e.g. Friday, September 3, 2010)
* * `'longDate'`: equivalent to `'MMMM d, y'` for en_US locale (e.g. September 3, 2010)
* * `'mediumDate'`: equivalent to `'MMM d, y'` for en_US locale (e.g. Sep 3, 2010)
* * `'shortDate'`: equivalent to `'M/d/yy'` for en_US locale (e.g. 9/3/10)
- * * `'mediumTime'`: equivalent to `'h:mm:ss a'` for en_US locale (e.g. 12:05:08 pm)
- * * `'shortTime'`: equivalent to `'h:mm a'` for en_US locale (e.g. 12:05 pm)
+ * * `'mediumTime'`: equivalent to `'h:mm:ss a'` for en_US locale (e.g. 12:05:08 PM)
+ * * `'shortTime'`: equivalent to `'h:mm a'` for en_US locale (e.g. 12:05 PM)
*
- * `format` string can contain literal values. These need to be quoted with single quotes (e.g.
- * `"h 'in the morning'"`). In order to output single quote, use two single quotes in a sequence
+ * `format` string can contain literal values. These need to be escaped by surrounding with single quotes (e.g.
+ * `"h 'in the morning'"`). In order to output a single quote, escape it - i.e., two single quotes in a sequence
* (e.g. `"h 'o''clock'"`).
*
* @param {(Date|number|string)} date Date to format either as Date object, milliseconds (string or
- * number) or various ISO 8601 datetime string formats (e.g. yyyy-MM-ddTHH:mm:ss.SSSZ and its
+ * number) or various ISO 8601 datetime string formats (e.g. yyyy-MM-ddTHH:mm:ss.sssZ and its
* shorter versions like yyyy-MM-ddTHH:mmZ, yyyy-MM-dd or yyyyMMddTHHmmssZ). If no timezone is
* specified in the string input, the time is considered to be in the local timezone.
* @param {string=} format Formatting rules (see Description). If not specified,
* `mediumDate` is used.
+ * @param {string=} timezone Timezone to be used for formatting. Right now, only `'UTC'` is supported.
+ * If not specified, the timezone of the browser will be used.
* @returns {string} Formatted string or the input if input is not recognized as date/millis.
*
* @example
@@ -15423,6 +16203,8 @@ var DATE_FORMATS_SPLIT = /((?:[^yMdHhmsaZEw']+)|(?:'(?:[^']|'')*')|(?:E+|y+|M+|d
{{1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'}}
{{1288323623006 | date:'MM/dd/yyyy @ h:mma'}} :
{{'1288323623006' | date:'MM/dd/yyyy @ h:mma'}}
+ {{1288323623006 | date:"MM/dd/yyyy 'at' h:mma"}} :
+ {{'1288323623006' | date:"MM/dd/yyyy 'at' h:mma"}}
it('should format date', function() {
@@ -15432,6 +16214,8 @@ var DATE_FORMATS_SPLIT = /((?:[^yMdHhmsaZEw']+)|(?:'(?:[^']|'')*')|(?:E+|y+|M+|d
toMatch(/2010\-10\-2\d \d{2}:\d{2}:\d{2} (\-|\+)?\d{4}/);
expect(element(by.binding("'1288323623006' | date:'MM/dd/yyyy @ h:mma'")).getText()).
toMatch(/10\/2\d\/2010 @ \d{1,2}:\d{2}(AM|PM)/);
+ expect(element(by.binding("'1288323623006' | date:\"MM/dd/yyyy 'at' h:mma\"")).getText()).
+ toMatch(/10\/2\d\/2010 at \d{1,2}:\d{2}(AM|PM)/);
});
@@ -15467,7 +16251,7 @@ function dateFilter($locale) {
}
- return function(date, format) {
+ return function(date, format, timezone) {
var text = '',
parts = [],
fn, match;
@@ -15497,6 +16281,10 @@ function dateFilter($locale) {
}
}
+ if (timezone && timezone === 'UTC') {
+ date = new Date(date.getTime());
+ date.setMinutes(date.getMinutes() + date.getTimezoneOffset());
+ }
forEach(parts, function(value){
fn = DATE_FORMATS[value];
text += fn ? fn(date, $locale.DATETIME_FORMATS)
@@ -15571,10 +16359,11 @@ var uppercaseFilter = valueFn(uppercase);
*
* @description
* Creates a new array or string containing only a specified number of elements. The elements
- * are taken from either the beginning or the end of the source array or string, as specified by
- * the value and sign (positive or negative) of `limit`.
+ * are taken from either the beginning or the end of the source array, string or number, as specified by
+ * the value and sign (positive or negative) of `limit`. If a number is used as input, it is
+ * converted to a string.
*
- * @param {Array|string} input Source array or string to be limited.
+ * @param {Array|string|number} input Source array, string or number to be limited.
* @param {string|number} limit The length of the returned array or string. If the `limit` number
* is positive, `limit` number of items from the beginning of the source array/string are copied.
* If the number is negative, `limit` number of items from the end of the source array/string
@@ -15590,52 +16379,68 @@ var uppercaseFilter = valueFn(uppercase);
.controller('ExampleController', ['$scope', function($scope) {
$scope.numbers = [1,2,3,4,5,6,7,8,9];
$scope.letters = "abcdefghi";
+ $scope.longNumber = 2345432342;
$scope.numLimit = 3;
$scope.letterLimit = 3;
+ $scope.longNumberLimit = 3;
}]);
var numLimitInput = element(by.model('numLimit'));
var letterLimitInput = element(by.model('letterLimit'));
+ var longNumberLimitInput = element(by.model('longNumberLimit'));
var limitedNumbers = element(by.binding('numbers | limitTo:numLimit'));
var limitedLetters = element(by.binding('letters | limitTo:letterLimit'));
+ var limitedLongNumber = element(by.binding('longNumber | limitTo:longNumberLimit'));
it('should limit the number array to first three items', function() {
expect(numLimitInput.getAttribute('value')).toBe('3');
expect(letterLimitInput.getAttribute('value')).toBe('3');
+ expect(longNumberLimitInput.getAttribute('value')).toBe('3');
expect(limitedNumbers.getText()).toEqual('Output numbers: [1,2,3]');
expect(limitedLetters.getText()).toEqual('Output letters: abc');
+ expect(limitedLongNumber.getText()).toEqual('Output long number: 234');
});
- it('should update the output when -3 is entered', function() {
- numLimitInput.clear();
- numLimitInput.sendKeys('-3');
- letterLimitInput.clear();
- letterLimitInput.sendKeys('-3');
- expect(limitedNumbers.getText()).toEqual('Output numbers: [7,8,9]');
- expect(limitedLetters.getText()).toEqual('Output letters: ghi');
- });
+ // There is a bug in safari and protractor that doesn't like the minus key
+ // it('should update the output when -3 is entered', function() {
+ // numLimitInput.clear();
+ // numLimitInput.sendKeys('-3');
+ // letterLimitInput.clear();
+ // letterLimitInput.sendKeys('-3');
+ // longNumberLimitInput.clear();
+ // longNumberLimitInput.sendKeys('-3');
+ // expect(limitedNumbers.getText()).toEqual('Output numbers: [7,8,9]');
+ // expect(limitedLetters.getText()).toEqual('Output letters: ghi');
+ // expect(limitedLongNumber.getText()).toEqual('Output long number: 342');
+ // });
it('should not exceed the maximum size of input array', function() {
numLimitInput.clear();
numLimitInput.sendKeys('100');
letterLimitInput.clear();
letterLimitInput.sendKeys('100');
+ longNumberLimitInput.clear();
+ longNumberLimitInput.sendKeys('100');
expect(limitedNumbers.getText()).toEqual('Output numbers: [1,2,3,4,5,6,7,8,9]');
expect(limitedLetters.getText()).toEqual('Output letters: abcdefghi');
+ expect(limitedLongNumber.getText()).toEqual('Output long number: 2345432342');
});
- */
+*/
function limitToFilter(){
return function(input, limit) {
+ if (isNumber(input)) input = input.toString();
if (!isArray(input) && !isString(input)) return input;
if (Math.abs(Number(limit)) === Infinity) {
@@ -15696,9 +16501,13 @@ function limitToFilter(){
*
* - `function`: Getter function. The result of this function will be sorted using the
* `<`, `=`, `>` operator.
- * - `string`: An Angular expression which evaluates to an object to order by, such as 'name'
- * to sort by a property called 'name'. Optionally prefixed with `+` or `-` to control
- * ascending or descending sort order (for example, +name or -name).
+ * - `string`: An Angular expression. The result of this expression is used to compare elements
+ * (for example `name` to sort by a property called `name` or `name.substr(0, 3)` to sort by
+ * 3 first characters of a property called `name`). The result of a constant expression
+ * is interpreted as a property name to be used in comparisons (for example `"special name"`
+ * to sort object by the value of their `special name` property). An expression can be
+ * optionally prefixed with `+` or `-` to control ascending or descending sort order
+ * (for example, `+name` or `-name`).
* - `Array`: An array of function or string predicates. The first predicate in the array
* is used for sorting, but when two items are equivalent, the next predicate is used.
*
@@ -15789,10 +16598,10 @@ function limitToFilter(){
orderByFilter.$inject = ['$parse'];
function orderByFilter($parse){
return function(array, sortPredicate, reverseOrder) {
- if (!isArray(array)) return array;
+ if (!(isArrayLike(array))) return array;
if (!sortPredicate) return array;
sortPredicate = isArray(sortPredicate) ? sortPredicate: [sortPredicate];
- sortPredicate = map(sortPredicate, function(predicate){
+ sortPredicate = sortPredicate.map(function(predicate){
var descending = false, get = predicate || identity;
if (isString(predicate)) {
if ((predicate.charAt(0) == '+' || predicate.charAt(0) == '-')) {
@@ -15923,12 +16732,12 @@ var htmlAnchorDirective = valueFn({
*
* The wrong way to write it:
* ```html
- *
+ * link1
* ```
*
* The correct way to write it:
* ```html
- *
+ * link1
* ```
*
* @element A
@@ -16066,7 +16875,7 @@ var htmlAnchorDirective = valueFn({
*
* @description
*
- * The following markup will make the button enabled on Chrome/Firefox but not on IE8 and older IEs:
+ * We shouldn't do this, because it will make the button enabled on Chrome/Firefox but not on IE8 and older IEs:
* ```html
*
* Disabled
@@ -16330,14 +17139,24 @@ forEach(['src', 'srcset', 'href'], function(attrName) {
};
});
-/* global -nullFormCtrl */
+/* global -nullFormCtrl, -SUBMITTED_CLASS, addSetValidityMethod: true
+ */
var nullFormCtrl = {
$addControl: noop,
+ $$renameControl: nullFormRenameControl,
$removeControl: noop,
$setValidity: noop,
+ $$setPending: noop,
$setDirty: noop,
- $setPristine: noop
-};
+ $setPristine: noop,
+ $setSubmitted: noop,
+ $$clearControlValidity: noop
+},
+SUBMITTED_CLASS = 'ng-submitted';
+
+function nullFormRenameControl(control, name) {
+ control.$name = name;
+}
/**
* @ngdoc type
@@ -16347,13 +17166,13 @@ var nullFormCtrl = {
* @property {boolean} $dirty True if user has already interacted with the form.
* @property {boolean} $valid True if all of the containing forms and controls are valid.
* @property {boolean} $invalid True if at least one containing control or form is invalid.
+ * @property {boolean} $submitted True if user has submitted the form even if its invalid.
*
- * @property {Object} $error Is an object hash, containing references to all invalid controls or
- * forms, where:
+ * @property {Object} $error Is an object hash, containing references to controls or
+ * forms with failing validators, where:
*
* - keys are validation tokens (error names),
- * - values are arrays of controls or forms that are invalid for given error name.
- *
+ * - values are arrays of controls or forms that have a failing validator for given error name.
*
* Built-in validation tokens:
*
@@ -16376,33 +17195,28 @@ var nullFormCtrl = {
*
*/
//asks for $scope to fool the BC controller module
-FormController.$inject = ['$element', '$attrs', '$scope', '$animate'];
-function FormController(element, attrs, $scope, $animate) {
+FormController.$inject = ['$element', '$attrs', '$scope', '$animate', '$interpolate'];
+function FormController(element, attrs, $scope, $animate, $interpolate) {
var form = this,
- parentForm = element.parent().controller('form') || nullFormCtrl,
- invalidCount = 0, // used to easily determine if we are valid
- errors = form.$error = {},
controls = [];
+ var parentForm = form.$$parentForm = element.parent().controller('form') || nullFormCtrl;
+
// init state
- form.$name = attrs.name || attrs.ngForm;
+ form.$error = {};
+ form.$$success = {};
+ form.$pending = undefined;
+ form.$name = $interpolate(attrs.name || attrs.ngForm || '')($scope);
form.$dirty = false;
form.$pristine = true;
form.$valid = true;
form.$invalid = false;
+ form.$submitted = false;
parentForm.$addControl(form);
// Setup initial state of the control
element.addClass(PRISTINE_CLASS);
- toggleValidCss(true);
-
- // convenience method for easy toggling of classes
- function toggleValidCss(isValid, validationErrorKey) {
- validationErrorKey = validationErrorKey ? '-' + snake_case(validationErrorKey, '-') : '';
- $animate.removeClass(element, (isValid ? INVALID_CLASS : VALID_CLASS) + validationErrorKey);
- $animate.addClass(element, (isValid ? VALID_CLASS : INVALID_CLASS) + validationErrorKey);
- }
/**
* @ngdoc method
@@ -16458,6 +17272,17 @@ function FormController(element, attrs, $scope, $animate) {
}
};
+ // Private API: rename a form control
+ form.$$renameControl = function(control, newName) {
+ var oldName = control.$name;
+
+ if (form[oldName] === control) {
+ delete form[oldName];
+ }
+ form[newName] = control;
+ control.$name = newName;
+ };
+
/**
* @ngdoc method
* @name form.FormController#$removeControl
@@ -16471,13 +17296,17 @@ function FormController(element, attrs, $scope, $animate) {
if (control.$name && form[control.$name] === control) {
delete form[control.$name];
}
- forEach(errors, function(queue, validationToken) {
- form.$setValidity(validationToken, true, control);
+ forEach(form.$pending, function(value, name) {
+ form.$setValidity(name, null, control);
+ });
+ forEach(form.$error, function(value, name) {
+ form.$setValidity(name, null, control);
});
arrayRemove(controls, control);
};
+
/**
* @ngdoc method
* @name form.FormController#$setValidity
@@ -16487,43 +17316,33 @@ function FormController(element, attrs, $scope, $animate) {
*
* This method will also propagate to parent forms.
*/
- form.$setValidity = function(validationToken, isValid, control) {
- var queue = errors[validationToken];
-
- if (isValid) {
- if (queue) {
- arrayRemove(queue, control);
- if (!queue.length) {
- invalidCount--;
- if (!invalidCount) {
- toggleValidCss(isValid);
- form.$valid = true;
- form.$invalid = false;
- }
- errors[validationToken] = false;
- toggleValidCss(true, validationToken);
- parentForm.$setValidity(validationToken, true, form);
+ addSetValidityMethod({
+ ctrl: this,
+ $element: element,
+ set: function(object, property, control) {
+ var list = object[property];
+ if (!list) {
+ object[property] = [control];
+ } else {
+ var index = list.indexOf(control);
+ if (index === -1) {
+ list.push(control);
}
}
-
- } else {
- if (!invalidCount) {
- toggleValidCss(isValid);
+ },
+ unset: function(object, property, control) {
+ var list = object[property];
+ if (!list) {
+ return;
}
- if (queue) {
- if (includes(queue, control)) return;
- } else {
- errors[validationToken] = queue = [];
- invalidCount++;
- toggleValidCss(false, validationToken);
- parentForm.$setValidity(validationToken, false, form);
+ arrayRemove(list, control);
+ if (list.length === 0) {
+ delete object[property];
}
- queue.push(control);
-
- form.$valid = false;
- form.$invalid = true;
- }
- };
+ },
+ parentForm: parentForm,
+ $animate: $animate
+ });
/**
* @ngdoc method
@@ -16558,16 +17377,47 @@ function FormController(element, attrs, $scope, $animate) {
* saving or resetting it.
*/
form.$setPristine = function () {
- $animate.removeClass(element, DIRTY_CLASS);
- $animate.addClass(element, PRISTINE_CLASS);
+ $animate.setClass(element, PRISTINE_CLASS, DIRTY_CLASS + ' ' + SUBMITTED_CLASS);
form.$dirty = false;
form.$pristine = true;
+ form.$submitted = false;
forEach(controls, function(control) {
control.$setPristine();
});
};
-}
+ /**
+ * @ngdoc method
+ * @name form.FormController#$setUntouched
+ *
+ * @description
+ * Sets the form to its untouched state.
+ *
+ * This method can be called to remove the 'ng-touched' class and set the form controls to their
+ * untouched state (ng-untouched class).
+ *
+ * Setting a form controls back to their untouched state is often useful when setting the form
+ * back to its pristine state.
+ */
+ form.$setUntouched = function () {
+ forEach(controls, function(control) {
+ control.$setUntouched();
+ });
+ };
+
+ /**
+ * @ngdoc method
+ * @name form.FormController#$setSubmitted
+ *
+ * @description
+ * Sets the form to its submitted state.
+ */
+ form.$setSubmitted = function () {
+ $animate.addClass(element, SUBMITTED_CLASS);
+ form.$submitted = true;
+ parentForm.$setSubmitted();
+ };
+}
/**
* @ngdoc directive
@@ -16617,6 +17467,7 @@ function FormController(element, attrs, $scope, $animate) {
* - `ng-invalid` is set if the form is invalid.
* - `ng-pristine` is set if the form is pristine.
* - `ng-dirty` is set if the form is dirty.
+ * - `ng-submitted` is set if the form was submitted.
*
* Keep in mind that ngAnimate can detect each of these classes when added and removed.
*
@@ -16654,9 +17505,6 @@ function FormController(element, attrs, $scope, $animate) {
* submitted. Note that `ngClick` events will occur before the model is updated. Use `ngSubmit`
* to have access to the updated model.
*
- * @param {string=} name Name of the form. If specified, the form controller will be published into
- * related scope, under this name.
- *
* ## Animation Hooks
*
* Animations in ngForm are triggered when any of the associated CSS classes are added and removed.
@@ -16733,6 +17581,8 @@ function FormController(element, attrs, $scope, $animate) {
*
+ * @param {string=} name Name of the form. If specified, the form controller will be published into
+ * related scope, under this name.
*/
var formDirectiveFactory = function(isNgForm) {
return ['$timeout', function($timeout) {
@@ -16753,6 +17603,7 @@ var formDirectiveFactory = function(isNgForm) {
var handleFormSubmission = function(event) {
scope.$apply(function() {
controller.$commitViewValue();
+ controller.$setSubmitted();
});
event.preventDefault
@@ -16771,13 +17622,20 @@ var formDirectiveFactory = function(isNgForm) {
});
}
- var parentFormCtrl = formElement.parent().controller('form'),
- alias = attr.name || attr.ngForm;
+ var parentFormCtrl = controller.$$parentForm,
+ alias = controller.$name;
if (alias) {
setter(scope, alias, controller, alias);
+ attr.$observe(attr.name ? 'name' : 'ngForm', function(newValue) {
+ if (alias === newValue) return;
+ setter(scope, alias, undefined, alias);
+ alias = newValue;
+ setter(scope, alias, controller, alias);
+ parentFormCtrl.$$renameControl(controller, alias);
+ });
}
- if (parentFormCtrl) {
+ if (parentFormCtrl !== nullFormCtrl) {
formElement.on('$destroy', function() {
parentFormCtrl.$removeControl(controller);
if (alias) {
@@ -16806,16 +17664,20 @@ var ngFormDirective = formDirectiveFactory(true);
TOUCHED_CLASS: true,
*/
+// Regex code is obtained from SO: https://stackoverflow.com/questions/3143070/javascript-regex-iso-datetime#answer-3143231
+var ISO_DATE_REGEXP = /\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d:[0-5]\d\.\d+([+-][0-2]\d:[0-5]\d|Z)/;
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-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)*$/i;
var NUMBER_REGEXP = /^\s*(\-|\+)?(\d+|(\d*(\.\d*)))\s*$/;
var DATE_REGEXP = /^(\d{4})-(\d{2})-(\d{2})$/;
-var DATETIMELOCAL_REGEXP = /^(\d{4})-(\d\d)-(\d\d)T(\d\d):(\d\d)$/;
+var DATETIMELOCAL_REGEXP = /^(\d{4})-(\d\d)-(\d\d)T(\d\d):(\d\d)(?::(\d\d)(\.\d{1,3})?)?$/;
var WEEK_REGEXP = /^(\d{4})-W(\d\d)$/;
var MONTH_REGEXP = /^(\d{4})-(\d\d)$/;
-var TIME_REGEXP = /^(\d\d):(\d\d)$/;
+var TIME_REGEXP = /^(\d\d):(\d\d)(?::(\d\d)(\.\d{1,3})?)?$/;
var DEFAULT_REGEXP = /(\s+|^)default(\s+|$)/;
+var $ngModelMinErr = new minErr('ngModel');
+
var inputType = {
/**
@@ -16823,7 +17685,9 @@ var inputType = {
* @name input[text]
*
* @description
- * Standard HTML text input with angular data binding.
+ * Standard HTML text input with angular data binding, inherited by most of the `input` elements.
+ *
+ * *NOTE* Not every feature offered is available for all input types.
*
* @param {string} ngModel Assignable angular expression to data-bind to.
* @param {string=} name Property name of the form under which the control is published.
@@ -16841,6 +17705,8 @@ var inputType = {
* @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.
+ * This parameter is ignored for input[type=password] controls, which will never trim the
+ * input.
*
* @example
@@ -16907,6 +17773,9 @@ var inputType = {
* modern browsers do not yet support this input type, it is important to provide cues to users on the
* expected input format via a placeholder or label. The model must always be a Date object.
*
+ * The timezone to be used to read/write the `Date` instance in the model can be defined using
+ * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser.
+ *
* @param {string} ngModel Assignable angular expression to data-bind to.
* @param {string=} name Property name of the form under which the control is published.
* @param {string=} min Sets the `min` validation error key if the value entered is less than `min`. This must be a
@@ -16930,7 +17799,7 @@ var inputType = {
}]);
*/
'datetime-local': createDateInputType('datetimelocal', DATETIMELOCAL_REGEXP,
- createDateParser(DATETIMELOCAL_REGEXP, ['yyyy', 'MM', 'dd', 'HH', 'mm']),
- 'yyyy-MM-ddTHH:mm'),
+ createDateParser(DATETIMELOCAL_REGEXP, ['yyyy', 'MM', 'dd', 'HH', 'mm', 'ss', 'sss']),
+ 'yyyy-MM-ddTHH:mm:ss.sss'),
/**
* @ngdoc input
@@ -17075,15 +17947,18 @@ var inputType = {
* @description
* Input with time validation and transformation. In browsers that do not yet support
* the HTML5 date input, a text element will be used. In that case, the text must be entered in a valid ISO-8601
- * local time format (HH:mm), for example: `14:57`. Model must be a Date object. This binding will always output a
- * Date object to the model of January 1, 1900, or local date `new Date(0, 0, 1, HH, mm)`.
+ * local time format (HH:mm:ss), for example: `14:57:00`. Model must be a Date object. This binding will always output a
+ * Date object to the model of January 1, 1970, or local date `new Date(1970, 0, 1, HH, mm, ss)`.
+ *
+ * The timezone to be used to read/write the `Date` instance in the model can be defined using
+ * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser.
*
* @param {string} ngModel Assignable angular expression to data-bind to.
* @param {string=} name Property name of the form under which the control is published.
* @param {string=} min Sets the `min` validation error key if the value entered is less than `min`. This must be a
- * valid ISO time format (HH:mm).
+ * valid ISO time format (HH:mm:ss).
* @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`. This must be a
- * valid ISO time format (HH:mm).
+ * valid ISO time format (HH:mm:ss).
* @param {string=} required Sets `required` validation error key if the value is not entered.
* @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
* the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
@@ -17097,18 +17972,18 @@ var inputType = {
Pick a between 8am and 5pm:
+ placeholder="HH:mm:ss" min="08:00:00" max="17:00:00" required />
Required!
Not a valid date!
- value = {{value | date: "HH:mm"}}
+ value = {{value | date: "HH:mm:ss"}}
myForm.input.$valid = {{myForm.input.$valid}}
myForm.input.$error = {{myForm.input.$error}}
myForm.$valid = {{myForm.$valid}}
@@ -17116,7 +17991,7 @@ var inputType = {
- var value = element(by.binding('value | date: "HH:mm"'));
+ var value = element(by.binding('value | date: "HH:mm:ss"'));
var valid = element(by.binding('myForm.input.$valid'));
var input = element(by.model('value'));
@@ -17132,7 +18007,7 @@ var inputType = {
}
it('should initialize to model', function() {
- expect(value.getText()).toContain('14:57');
+ expect(value.getText()).toContain('14:57:00');
expect(valid.getText()).toContain('myForm.input.$valid = true');
});
@@ -17143,7 +18018,7 @@ var inputType = {
});
it('should be invalid if over max', function() {
- setInput('23:59');
+ setInput('23:59:00');
expect(value.getText()).toContain('');
expect(valid.getText()).toContain('myForm.input.$valid = false');
});
@@ -17151,8 +18026,8 @@ var inputType = {
*/
'time': createDateInputType('time', TIME_REGEXP,
- createDateParser(TIME_REGEXP, ['HH', 'mm']),
- 'HH:mm'),
+ createDateParser(TIME_REGEXP, ['HH', 'mm', 'ss', 'sss']),
+ 'HH:mm:ss.sss'),
/**
* @ngdoc input
@@ -17163,6 +18038,9 @@ var inputType = {
* the HTML5 week input, a text element will be used. In that case, the text must be entered in a valid ISO-8601
* week format (yyyy-W##), for example: `2013-W02`. The model must always be a Date object.
*
+ * The timezone to be used to read/write the `Date` instance in the model can be defined using
+ * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser.
+ *
* @param {string} ngModel Assignable angular expression to data-bind to.
* @param {string=} name Property name of the form under which the control is published.
* @param {string=} min Sets the `min` validation error key if the value entered is less than `min`. This must be a
@@ -17247,6 +18125,9 @@ var inputType = {
* month format (yyyy-MM), for example: `2009-01`. The model must always be a Date object. In the event the model is
* not set to the first of the month, the first of that model's month is assumed.
*
+ * The timezone to be used to read/write the `Date` instance in the model can be defined using
+ * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser.
+ *
* @param {string} ngModel Assignable angular expression to data-bind to.
* @param {string=} name Property name of the form under which the control is published.
* @param {string=} min Sets the `min` validation error key if the value entered is less than `min`. This must be
@@ -17664,13 +18545,6 @@ var inputType = {
'file': noop
};
-// A helper function to call $setValidity and return the value / undefined,
-// a pattern that is repeated a lot in the input validation logic.
-function validate(ctrl, validatorName, validity, value){
- ctrl.$setValidity(validatorName, validity);
- return validity ? value : undefined;
-}
-
function testFlags(validity, flags) {
var i, flag;
if (flags) {
@@ -17684,29 +18558,21 @@ function testFlags(validity, flags) {
return false;
}
-// 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] &&
- !testFlags(validity, ignoreFlags) &&
- testFlags(validity, badFlags)) {
- ctrl.$setValidity(validatorName, false);
- return;
- }
- return value;
- };
- ctrl.$parsers.push(validator);
- }
+function stringBasedInputType(ctrl) {
+ ctrl.$formatters.push(function(value) {
+ return ctrl.$isEmpty(value) ? value : value.toString();
+ });
}
function textInputType(scope, element, attr, ctrl, $sniffer, $browser) {
+ baseInputType(scope, element, attr, ctrl, $sniffer, $browser);
+ stringBasedInputType(ctrl);
+}
+
+function baseInputType(scope, element, attr, ctrl, $sniffer, $browser) {
var validity = element.prop(VALIDITY_STATE_PROPERTY);
var placeholder = element[0].placeholder, noevent = {};
- ctrl.$$validityState = validity;
+ var type = lowercase(element[0].type);
// In composition mode, users are still inputing intermediate text buffer,
// hold the listener until composition is done.
@@ -17740,23 +18606,16 @@ function textInputType(scope, element, attr, ctrl, $sniffer, $browser) {
// By default we will trim the value
// If the attribute ng-trim exists we will avoid trimming
- // e.g.
- if (!attr.ngTrim || attr.ngTrim !== 'false') {
+ // If input type is 'password', the value is never trimmed
+ if (type !== 'password' && (!attr.ngTrim || attr.ngTrim !== 'false')) {
value = trim(value);
}
- // 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, event, revalidate);
- } else {
- scope.$apply(function() {
- ctrl.$setViewValue(value, event, revalidate);
- });
- }
+ // If a control is suffering from bad input (due to native validators), browsers discard its
+ // value, so it may be necessary to revalidate (by calling $setViewValue again) even if the
+ // control's value is the same empty value twice in a row.
+ if (ctrl.$viewValue !== value || (value === '' && ctrl.$$hasNativeValidators)) {
+ ctrl.$setViewValue(value, event);
}
};
@@ -17797,173 +18656,240 @@ function textInputType(scope, element, attr, ctrl, $sniffer, $browser) {
element.on('change', listener);
ctrl.$render = function() {
- element.val(ctrl.$isEmpty(ctrl.$viewValue) ? '' : ctrl.$viewValue);
+ element.val(ctrl.$isEmpty(ctrl.$modelValue) ? '' : ctrl.$viewValue);
};
}
-function weekParser(isoWeek) {
- if(isDate(isoWeek)) {
- return isoWeek;
- }
+function weekParser(isoWeek, existingDate) {
+ if (isDate(isoWeek)) {
+ return isoWeek;
+ }
- if(isString(isoWeek)) {
- WEEK_REGEXP.lastIndex = 0;
- var parts = WEEK_REGEXP.exec(isoWeek);
- if(parts) {
- var year = +parts[1],
- week = +parts[2],
- firstThurs = getFirstThursdayOfYear(year),
- addDays = (week - 1) * 7;
- return new Date(year, 0, firstThurs.getDate() + addDays);
+ if (isString(isoWeek)) {
+ WEEK_REGEXP.lastIndex = 0;
+ var parts = WEEK_REGEXP.exec(isoWeek);
+ if (parts) {
+ var year = +parts[1],
+ week = +parts[2],
+ hours = 0,
+ minutes = 0,
+ seconds = 0,
+ milliseconds = 0,
+ firstThurs = getFirstThursdayOfYear(year),
+ addDays = (week - 1) * 7;
+
+ if (existingDate) {
+ hours = existingDate.getHours();
+ minutes = existingDate.getMinutes();
+ seconds = existingDate.getSeconds();
+ milliseconds = existingDate.getMilliseconds();
}
- }
- return NaN;
+ return new Date(year, 0, firstThurs.getDate() + addDays, hours, minutes, seconds, milliseconds);
+ }
+ }
+
+ return NaN;
}
function createDateParser(regexp, mapping) {
- return function(iso) {
- var parts, map;
+ return function(iso, date) {
+ var parts, map;
- if(isDate(iso)) {
- return iso;
+ if (isDate(iso)) {
+ return iso;
+ }
+
+ if (isString(iso)) {
+ // When a date is JSON'ified to wraps itself inside of an extra
+ // set of double quotes. This makes the date parsing code unable
+ // to match the date string and parse it as a date.
+ if (iso.charAt(0) == '"' && iso.charAt(iso.length-1) == '"') {
+ iso = iso.substring(1, iso.length-1);
}
-
- if(isString(iso)) {
- regexp.lastIndex = 0;
- parts = regexp.exec(iso);
-
- if(parts) {
- parts.shift();
- map = { yyyy: 0, MM: 1, dd: 1, HH: 0, mm: 0 };
-
- forEach(parts, function(part, index) {
- if(index < mapping.length) {
- map[mapping[index]] = +part;
- }
- });
-
- return new Date(map.yyyy, map.MM - 1, map.dd, map.HH, map.mm);
- }
+ if (ISO_DATE_REGEXP.test(iso)) {
+ return new Date(iso);
}
+ regexp.lastIndex = 0;
+ parts = regexp.exec(iso);
- return NaN;
- };
+ if (parts) {
+ parts.shift();
+ if (date) {
+ map = {
+ yyyy: date.getFullYear(),
+ MM: date.getMonth() + 1,
+ dd: date.getDate(),
+ HH: date.getHours(),
+ mm: date.getMinutes(),
+ ss: date.getSeconds(),
+ sss: date.getMilliseconds() / 1000
+ };
+ } else {
+ map = { yyyy: 1970, MM: 1, dd: 1, HH: 0, mm: 0, ss: 0, sss: 0 };
+ }
+
+ forEach(parts, function(part, index) {
+ if (index < mapping.length) {
+ map[mapping[index]] = +part;
+ }
+ });
+ return new Date(map.yyyy, map.MM - 1, map.dd, map.HH, map.mm, map.ss || 0, map.sss * 1000 || 0);
+ }
+ }
+
+ return NaN;
+ };
}
function createDateInputType(type, regexp, parseDate, format) {
- return function dynamicDateInputType(scope, element, attr, ctrl, $sniffer, $browser, $filter) {
- textInputType(scope, element, attr, ctrl, $sniffer, $browser);
+ return function dynamicDateInputType(scope, element, attr, ctrl, $sniffer, $browser, $filter) {
+ badInputChecker(scope, element, attr, ctrl);
+ baseInputType(scope, element, attr, ctrl, $sniffer, $browser);
+ var timezone = ctrl && ctrl.$options && ctrl.$options.timezone;
- ctrl.$parsers.push(function(value) {
- if(ctrl.$isEmpty(value)) {
- ctrl.$setValidity(type, true);
- return null;
- }
-
- if(regexp.test(value)) {
- ctrl.$setValidity(type, true);
- return parseDate(value);
- }
-
- ctrl.$setValidity(type, false);
- return undefined;
- });
-
- ctrl.$formatters.push(function(value) {
- if(isDate(value)) {
- return $filter('date')(value, format);
- }
- return '';
- });
-
- if(attr.min) {
- var minValidator = function(value) {
- var valid = ctrl.$isEmpty(value) ||
- (parseDate(value) >= parseDate(attr.min));
- ctrl.$setValidity('min', valid);
- return valid ? value : undefined;
- };
-
- ctrl.$parsers.push(minValidator);
- ctrl.$formatters.push(minValidator);
+ ctrl.$$parserName = type;
+ ctrl.$parsers.push(function(value) {
+ if (ctrl.$isEmpty(value)) return null;
+ if (regexp.test(value)) {
+ var previousDate = ctrl.$modelValue;
+ if (previousDate && timezone === 'UTC') {
+ var timezoneOffset = 60000 * previousDate.getTimezoneOffset();
+ previousDate = new Date(previousDate.getTime() + timezoneOffset);
+ }
+ var parsedDate = parseDate(value, previousDate);
+ if (timezone === 'UTC') {
+ parsedDate.setMinutes(parsedDate.getMinutes() - parsedDate.getTimezoneOffset());
+ }
+ return parsedDate;
}
+ return undefined;
+ });
- if(attr.max) {
- var maxValidator = function(value) {
- var valid = ctrl.$isEmpty(value) ||
- (parseDate(value) <= parseDate(attr.max));
- ctrl.$setValidity('max', valid);
- return valid ? value : undefined;
- };
-
- ctrl.$parsers.push(maxValidator);
- ctrl.$formatters.push(maxValidator);
+ ctrl.$formatters.push(function(value) {
+ if (isDate(value)) {
+ return $filter('date')(value, format, timezone);
}
- };
+ return '';
+ });
+
+ if (isDefined(attr.min) || attr.ngMin) {
+ var minVal;
+ ctrl.$validators.min = function(value) {
+ return ctrl.$isEmpty(value) || isUndefined(minVal) || parseDate(value) >= minVal;
+ };
+ attr.$observe('min', function(val) {
+ minVal = parseObservedDateValue(val);
+ ctrl.$validate();
+ });
+ }
+
+ if (isDefined(attr.max) || attr.ngMax) {
+ var maxVal;
+ ctrl.$validators.max = function(value) {
+ return ctrl.$isEmpty(value) || isUndefined(maxVal) || parseDate(value) <= maxVal;
+ };
+ attr.$observe('max', function(val) {
+ maxVal = parseObservedDateValue(val);
+ ctrl.$validate();
+ });
+ }
+
+ function parseObservedDateValue(val) {
+ return isDefined(val) ? (isDate(val) ? val : parseDate(val)) : undefined;
+ }
+ };
}
-var numberBadFlags = ['badInput'];
+function badInputChecker(scope, element, attr, ctrl) {
+ var node = element[0];
+ var nativeValidation = ctrl.$$hasNativeValidators = isObject(node.validity);
+ if (nativeValidation) {
+ ctrl.$parsers.push(function(value) {
+ var validity = element.prop(VALIDITY_STATE_PROPERTY) || {};
+ // Detect bug in FF35 for input[email] (https://bugzilla.mozilla.org/show_bug.cgi?id=1064430):
+ // - also sets validity.badInput (should only be validity.typeMismatch).
+ // - see http://www.whatwg.org/specs/web-apps/current-work/multipage/forms.html#e-mail-state-(type=email)
+ // - can ignore this case as we can still read out the erroneous email...
+ return validity.badInput && !validity.typeMismatch ? undefined : value;
+ });
+ }
+}
function numberInputType(scope, element, attr, ctrl, $sniffer, $browser) {
- textInputType(scope, element, attr, ctrl, $sniffer, $browser);
+ badInputChecker(scope, element, attr, ctrl);
+ baseInputType(scope, element, attr, ctrl, $sniffer, $browser);
+ ctrl.$$parserName = 'number';
ctrl.$parsers.push(function(value) {
- var empty = ctrl.$isEmpty(value);
- if (empty || NUMBER_REGEXP.test(value)) {
- ctrl.$setValidity('number', true);
- return value === '' ? null : (empty ? value : parseFloat(value));
- } else {
- ctrl.$setValidity('number', false);
- return undefined;
+ if (ctrl.$isEmpty(value)) return null;
+ if (NUMBER_REGEXP.test(value)) return parseFloat(value);
+ return undefined;
+ });
+
+ ctrl.$formatters.push(function(value) {
+ if (!ctrl.$isEmpty(value)) {
+ if (!isNumber(value)) {
+ throw $ngModelMinErr('numfmt', 'Expected `{0}` to be a number', value);
+ }
+ value = value.toString();
}
+ return value;
});
- addNativeHtml5Validators(ctrl, 'number', numberBadFlags, null, ctrl.$$validityState);
-
- ctrl.$formatters.push(function(value) {
- return ctrl.$isEmpty(value) ? '' : '' + value;
- });
-
- if (attr.min) {
- var minValidator = function(value) {
- var min = parseFloat(attr.min);
- return validate(ctrl, 'min', ctrl.$isEmpty(value) || value >= min, value);
+ if (attr.min || attr.ngMin) {
+ var minVal;
+ ctrl.$validators.min = function(value) {
+ return ctrl.$isEmpty(value) || isUndefined(minVal) || value >= minVal;
};
- ctrl.$parsers.push(minValidator);
- ctrl.$formatters.push(minValidator);
+ attr.$observe('min', function(val) {
+ if (isDefined(val) && !isNumber(val)) {
+ val = parseFloat(val, 10);
+ }
+ minVal = isNumber(val) && !isNaN(val) ? val : undefined;
+ // TODO(matsko): implement validateLater to reduce number of validations
+ ctrl.$validate();
+ });
}
- if (attr.max) {
- var maxValidator = function(value) {
- var max = parseFloat(attr.max);
- return validate(ctrl, 'max', ctrl.$isEmpty(value) || value <= max, value);
+ if (attr.max || attr.ngMax) {
+ var maxVal;
+ ctrl.$validators.max = function(value) {
+ return ctrl.$isEmpty(value) || isUndefined(maxVal) || value <= maxVal;
};
- ctrl.$parsers.push(maxValidator);
- ctrl.$formatters.push(maxValidator);
+ attr.$observe('max', function(val) {
+ if (isDefined(val) && !isNumber(val)) {
+ val = parseFloat(val, 10);
+ }
+ maxVal = isNumber(val) && !isNaN(val) ? val : undefined;
+ // TODO(matsko): implement validateLater to reduce number of validations
+ ctrl.$validate();
+ });
}
-
- ctrl.$formatters.push(function(value) {
- return validate(ctrl, 'number', ctrl.$isEmpty(value) || isNumber(value), value);
- });
}
function urlInputType(scope, element, attr, ctrl, $sniffer, $browser) {
- textInputType(scope, element, attr, ctrl, $sniffer, $browser);
+ // Note: no badInputChecker here by purpose as `url` is only a validation
+ // in browsers, i.e. we can always read out input.value even if it is not valid!
+ baseInputType(scope, element, attr, ctrl, $sniffer, $browser);
+ stringBasedInputType(ctrl);
- ctrl.$validators.url = function(modelValue, viewValue) {
- var value = modelValue || viewValue;
+ ctrl.$$parserName = 'url';
+ ctrl.$validators.url = function(value) {
return ctrl.$isEmpty(value) || URL_REGEXP.test(value);
};
}
function emailInputType(scope, element, attr, ctrl, $sniffer, $browser) {
- textInputType(scope, element, attr, ctrl, $sniffer, $browser);
+ // Note: no badInputChecker here by purpose as `url` is only a validation
+ // in browsers, i.e. we can always read out input.value even if it is not valid!
+ baseInputType(scope, element, attr, ctrl, $sniffer, $browser);
+ stringBasedInputType(ctrl);
- ctrl.$validators.email = function(modelValue, viewValue) {
- var value = modelValue || viewValue;
+ ctrl.$$parserName = 'email';
+ ctrl.$validators.email = function(value) {
return ctrl.$isEmpty(value) || EMAIL_REGEXP.test(value);
};
}
@@ -17976,9 +18902,7 @@ function radioInputType(scope, element, attr, ctrl) {
var listener = function(ev) {
if (element[0].checked) {
- scope.$apply(function() {
- ctrl.$setViewValue(attr.value, ev && ev.type);
- });
+ ctrl.$setViewValue(attr.value, ev && ev.type);
}
};
@@ -17997,7 +18921,7 @@ function parseConstantExpr($parse, context, name, expression, fallback) {
if (isDefined(expression)) {
parseFn = $parse(expression);
if (!parseFn.constant) {
- throw new minErr('ngModel')('constexpr', 'Expected constant expression for `{0}`, but saw ' +
+ throw minErr('ngModel')('constexpr', 'Expected constant expression for `{0}`, but saw ' +
'`{1}`.', name, expression);
}
return parseFn(context);
@@ -18010,9 +18934,7 @@ function checkboxInputType(scope, element, attr, ctrl, $sniffer, $browser, $filt
var falseValue = parseConstantExpr($parse, scope, 'ngFalseValue', attr.ngFalseValue, false);
var listener = function(ev) {
- scope.$apply(function() {
- ctrl.$setViewValue(element[0].checked, ev && ev.type);
- });
+ ctrl.$setViewValue(element[0].checked, ev && ev.type);
};
element.on('click', listener);
@@ -18021,7 +18943,7 @@ function checkboxInputType(scope, element, attr, ctrl, $sniffer, $browser, $filt
element[0].checked = ctrl.$viewValue;
};
- // Override the standard `$isEmpty` because a value of `false` means empty in a checkbox.
+ // Override the standard `$isEmpty` because an empty checkbox is never equal to the trueValue
ctrl.$isEmpty = function(value) {
return value !== trueValue;
};
@@ -18074,6 +18996,8 @@ function checkboxInputType(scope, element, attr, ctrl, $sniffer, $browser, $filt
* HTML input element control with angular data-binding. Input control follows HTML5 input types
* and polyfills the HTML5 validation behavior for older browsers.
*
+ * *NOTE* Not every feature offered is available for all input types.
+ *
* @param {string} ngModel Assignable angular expression to data-bind to.
* @param {string=} name Property name of the form under which the control is published.
* @param {string=} required Sets `required` validation error key if the value is not entered.
@@ -18087,6 +19011,9 @@ function checkboxInputType(scope, element, attr, ctrl, $sniffer, $browser, $filt
* patterns defined as scope expressions.
* @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.
+ * This parameter is ignored for input[type=password] controls, which will never trim the
+ * input.
*
* @example
@@ -18122,7 +19049,7 @@ function checkboxInputType(scope, element, attr, ctrl, $sniffer, $browser, $filt
- var user = element(by.binding('{{user}}'));
+ var user = element(by.exactBinding('user'));
var userNameValid = element(by.binding('myForm.userName.$valid'));
var lastNameValid = element(by.binding('myForm.lastName.$valid'));
var lastNameError = element(by.binding('myForm.lastName.$error'));
@@ -18195,7 +19122,8 @@ var VALID_CLASS = 'ng-valid',
PRISTINE_CLASS = 'ng-pristine',
DIRTY_CLASS = 'ng-dirty',
UNTOUCHED_CLASS = 'ng-untouched',
- TOUCHED_CLASS = 'ng-touched';
+ TOUCHED_CLASS = 'ng-touched',
+ PENDING_CLASS = 'ng-pending';
/**
* @ngdoc type
@@ -18230,11 +19158,52 @@ var VALID_CLASS = 'ng-valid',
* provided with the model value as an argument and must return a true or false value depending
* on the response of that validation.
*
+ * ```js
+ * ngModel.$validators.validCharacters = function(modelValue, viewValue) {
+ * var value = modelValue || viewValue;
+ * return /[0-9]+/.test(value) &&
+ * /[a-z]+/.test(value) &&
+ * /[A-Z]+/.test(value) &&
+ * /\W+/.test(value);
+ * };
+ * ```
+ *
+ * @property {Object.} $asyncValidators A collection of validations that are expected to
+ * perform an asynchronous validation (e.g. a HTTP request). The validation function that is provided
+ * is expected to return a promise when it is run during the model validation process. Once the promise
+ * is delivered then the validation status will be set to true when fulfilled and false when rejected.
+ * When the asynchronous validators are triggered, each of the validators will run in parallel and the model
+ * value will only be updated once all validators have been fulfilled. Also, keep in mind that all
+ * asynchronous validators will only run once all synchronous validators have passed.
+ *
+ * Please note that if $http is used then it is important that the server returns a success HTTP response code
+ * in order to fulfill the validation and a status level of `4xx` in order to reject the validation.
+ *
+ * ```js
+ * ngModel.$asyncValidators.uniqueUsername = function(modelValue, viewValue) {
+ * var value = modelValue || viewValue;
+ *
+ * // Lookup user by username
+ * return $http.get('/api/users/' + value).
+ * then(function resolved() {
+ * //username exists, this means validation fails
+ * return $q.reject('exists');
+ * }, function rejected() {
+ * //username does not exist, therefore this validation passes
+ * return true;
+ * });
+ * };
+ * ```
+ *
+ * @param {string} name The name of the validator.
+ * @param {Function} validationFn The validation function that will be run.
+ *
* @property {Array.} $viewChangeListeners Array of functions to execute whenever the
* view value has changed. It is called with no arguments, and its return value is ignored.
* This can be used in place of additional $watches against the model value.
*
- * @property {Object} $error An object hash with all errors as keys.
+ * @property {Object} $error An object hash with all failing validator ids as keys.
+ * @property {Object} $pending An object hash with all pending validator ids as keys.
*
* @property {boolean} $untouched True if control has not lost focus yet.
* @property {boolean} $touched True if control has lost focus.
@@ -18284,7 +19253,7 @@ var VALID_CLASS = 'ng-valid',
restrict: 'A', // only activate on element attribute
require: '?ngModel', // get a hold of NgModelController
link: function(scope, element, attrs, ngModel) {
- if(!ngModel) return; // do nothing if no ng-model
+ if (!ngModel) return; // do nothing if no ng-model
// Specify how UI should be updated
ngModel.$render = function() {
@@ -18302,7 +19271,7 @@ var VALID_CLASS = 'ng-valid',
var html = element.html();
// When we clear the content editable the browser leaves a behind
// If strip-br attribute is provided then we strip this out
- if( attrs.stripBr && html == ' ' ) {
+ if ( attrs.stripBr && html == ' ' ) {
html = '';
}
ngModel.$setViewValue(html);
@@ -18344,11 +19313,12 @@ var VALID_CLASS = 'ng-valid',
*
*
*/
-var NgModelController = ['$scope', '$exceptionHandler', '$attrs', '$element', '$parse', '$animate', '$timeout',
- function($scope, $exceptionHandler, $attr, $element, $parse, $animate, $timeout) {
+var NgModelController = ['$scope', '$exceptionHandler', '$attrs', '$element', '$parse', '$animate', '$timeout', '$rootScope', '$q', '$interpolate',
+ function($scope, $exceptionHandler, $attr, $element, $parse, $animate, $timeout, $rootScope, $q, $interpolate) {
this.$viewValue = Number.NaN;
this.$modelValue = Number.NaN;
this.$validators = {};
+ this.$asyncValidators = {};
this.$parsers = [];
this.$formatters = [];
this.$viewChangeListeners = [];
@@ -18358,18 +19328,43 @@ var NgModelController = ['$scope', '$exceptionHandler', '$attrs', '$element', '$
this.$dirty = false;
this.$valid = true;
this.$invalid = false;
- this.$name = $attr.name;
+ this.$error = {}; // keep invalid keys here
+ this.$$success = {}; // keep valid keys here
+ this.$pending = undefined; // keep pending keys here
+ this.$name = $interpolate($attr.name || '', false)($scope);
- var ngModelGet = $parse($attr.ngModel),
- ngModelSet = ngModelGet.assign,
+ var parsedNgModel = $parse($attr.ngModel),
pendingDebounce = null,
ctrl = this;
- if (!ngModelSet) {
- throw minErr('ngModel')('nonassign', "Expression '{0}' is non-assignable. Element: {1}",
- $attr.ngModel, startingTag($element));
- }
+ var ngModelGet = function ngModelGet() {
+ var modelValue = parsedNgModel($scope);
+ if (ctrl.$options && ctrl.$options.getterSetter && isFunction(modelValue)) {
+ modelValue = modelValue();
+ }
+ return modelValue;
+ };
+
+ var ngModelSet = function ngModelSet(newValue) {
+ var getterSetter;
+ if (ctrl.$options && ctrl.$options.getterSetter &&
+ isFunction(getterSetter = parsedNgModel($scope))) {
+
+ getterSetter(ctrl.$modelValue);
+ } else {
+ parsedNgModel.assign($scope, ctrl.$modelValue);
+ }
+ };
+
+ this.$$setOptions = function(options) {
+ ctrl.$options = options;
+
+ if (!parsedNgModel.assign && (!options || !options.getterSetter)) {
+ throw $ngModelMinErr('nonassign', "Expression '{0}' is non-assignable. Element: {1}",
+ $attr.ngModel, startingTag($element));
+ }
+ };
/**
* @ngdoc method
@@ -18407,7 +19402,7 @@ var NgModelController = ['$scope', '$exceptionHandler', '$attrs', '$element', '$
* default. The `checkboxInputType` directive does this because in its case a value of `false`
* implies empty.
*
- * @param {*} value Reference to check.
+ * @param {*} value Model value to check.
* @returns {boolean} True if `value` is empty.
*/
this.$isEmpty = function(value) {
@@ -18415,66 +19410,44 @@ var NgModelController = ['$scope', '$exceptionHandler', '$attrs', '$element', '$
};
var parentForm = $element.inheritedData('$formController') || nullFormCtrl,
- invalidCount = 0, // used to easily determine if we are valid
- $error = this.$error = {}; // keep invalid keys here
-
+ currentValidationRunId = 0;
// Setup initial state of the control
$element
.addClass(PRISTINE_CLASS)
.addClass(UNTOUCHED_CLASS);
- toggleValidCss(true);
-
- // convenience method for easy toggling of classes
- function toggleValidCss(isValid, validationErrorKey) {
- validationErrorKey = validationErrorKey ? '-' + snake_case(validationErrorKey, '-') : '';
- $animate.removeClass($element, (isValid ? INVALID_CLASS : VALID_CLASS) + validationErrorKey);
- $animate.addClass($element, (isValid ? VALID_CLASS : INVALID_CLASS) + validationErrorKey);
- }
/**
* @ngdoc method
* @name ngModel.NgModelController#$setValidity
*
* @description
- * Change the validity state, and notifies the form when the control changes validity. (i.e. it
- * does not notify form if given validator is already marked as invalid).
+ * Change the validity state, and notifies the form.
*
* This method can be called within $parsers/$formatters. However, if possible, please use the
- * `ngModel.$validators` pipeline which is designed to handle validations with true/false values.
+ * `ngModel.$validators` pipeline which is designed to call this method automatically.
*
* @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]` and `$pending[validationErrorKey]`
+ * 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).
+ * @param {boolean} isValid Whether the current state is valid (true), invalid (false), pending (undefined),
+ * or skipped (null).
*/
- this.$setValidity = function(validationErrorKey, isValid) {
- // Purposeful use of ! here to cast isValid to boolean in case it is undefined
- // jshint -W018
- if ($error[validationErrorKey] === !isValid) return;
- // jshint +W018
-
- if (isValid) {
- if ($error[validationErrorKey]) invalidCount--;
- if (!invalidCount) {
- toggleValidCss(true);
- ctrl.$valid = true;
- ctrl.$invalid = false;
- }
- } else {
- toggleValidCss(false);
- ctrl.$invalid = true;
- ctrl.$valid = false;
- invalidCount++;
- }
-
- $error[validationErrorKey] = !isValid;
- toggleValidCss(isValid, validationErrorKey);
-
- parentForm.$setValidity(validationErrorKey, isValid, ctrl);
- };
+ addSetValidityMethod({
+ ctrl: this,
+ $element: $element,
+ set: function(object, property) {
+ object[property] = true;
+ },
+ unset: function(object, property) {
+ delete object[property];
+ },
+ parentForm: parentForm,
+ $animate: $animate
+ });
/**
* @ngdoc method
@@ -18600,27 +19573,104 @@ var NgModelController = ['$scope', '$exceptionHandler', '$attrs', '$element', '$
* @name ngModel.NgModelController#$validate
*
* @description
- * Runs each of the registered validations set on the $validators object.
+ * Runs each of the registered validators (first synchronous validators and then asynchronous validators).
*/
this.$validate = function() {
- // ignore $validate before model initialized
- if (ctrl.$modelValue !== ctrl.$modelValue) {
+ // ignore $validate before model is initialized
+ if (isNumber(ctrl.$modelValue) && isNaN(ctrl.$modelValue)) {
return;
}
-
- var prev = ctrl.$modelValue;
- ctrl.$$runValidators(ctrl.$$invalidModelValue || ctrl.$modelValue, ctrl.$viewValue);
- if (prev !== ctrl.$modelValue) {
- ctrl.$$writeModelToScope();
- }
+ this.$$parseAndValidate();
};
- this.$$runValidators = function(modelValue, viewValue) {
- forEach(ctrl.$validators, function(fn, name) {
- ctrl.$setValidity(name, fn(modelValue, viewValue));
- });
- ctrl.$modelValue = ctrl.$valid ? modelValue : undefined;
- ctrl.$$invalidModelValue = ctrl.$valid ? undefined : modelValue;
+ this.$$runValidators = function(parseValid, modelValue, viewValue, doneCallback) {
+ currentValidationRunId++;
+ var localValidationRunId = currentValidationRunId;
+
+ // check parser error
+ if (!processParseErrors(parseValid)) {
+ validationDone(false);
+ return;
+ }
+ if (!processSyncValidators()) {
+ validationDone(false);
+ return;
+ }
+ processAsyncValidators();
+
+ function processParseErrors(parseValid) {
+ var errorKey = ctrl.$$parserName || 'parse';
+ if (parseValid === undefined) {
+ setValidity(errorKey, null);
+ } else {
+ setValidity(errorKey, parseValid);
+ if (!parseValid) {
+ forEach(ctrl.$validators, function(v, name) {
+ setValidity(name, null);
+ });
+ forEach(ctrl.$asyncValidators, function(v, name) {
+ setValidity(name, null);
+ });
+ return false;
+ }
+ }
+ return true;
+ }
+
+ function processSyncValidators() {
+ var syncValidatorsValid = true;
+ forEach(ctrl.$validators, function(validator, name) {
+ var result = validator(modelValue, viewValue);
+ syncValidatorsValid = syncValidatorsValid && result;
+ setValidity(name, result);
+ });
+ if (!syncValidatorsValid) {
+ forEach(ctrl.$asyncValidators, function(v, name) {
+ setValidity(name, null);
+ });
+ return false;
+ }
+ return true;
+ }
+
+ function processAsyncValidators() {
+ var validatorPromises = [];
+ var allValid = true;
+ forEach(ctrl.$asyncValidators, function(validator, name) {
+ var promise = validator(modelValue, viewValue);
+ if (!isPromiseLike(promise)) {
+ throw $ngModelMinErr("$asyncValidators",
+ "Expected asynchronous validator to return a promise but got '{0}' instead.", promise);
+ }
+ setValidity(name, undefined);
+ validatorPromises.push(promise.then(function() {
+ setValidity(name, true);
+ }, function(error) {
+ allValid = false;
+ setValidity(name, false);
+ }));
+ });
+ if (!validatorPromises.length) {
+ validationDone(true);
+ } else {
+ $q.all(validatorPromises).then(function() {
+ validationDone(allValid);
+ }, noop);
+ }
+ }
+
+ function setValidity(name, isValid) {
+ if (localValidationRunId === currentValidationRunId) {
+ ctrl.$setValidity(name, isValid);
+ }
+ }
+
+ function validationDone(allValid) {
+ if (localValidationRunId === currentValidationRunId) {
+
+ doneCallback(allValid);
+ }
+ }
};
/**
@@ -18634,11 +19684,15 @@ var NgModelController = ['$scope', '$exceptionHandler', '$attrs', '$element', '$
* event defined in `ng-model-options`. this method is rarely needed as `NgModelController`
* usually handles calling this in response to input events.
*/
- this.$commitViewValue = function(revalidate) {
+ this.$commitViewValue = function() {
var viewValue = ctrl.$viewValue;
$timeout.cancel(pendingDebounce);
- if (!revalidate && ctrl.$$lastCommittedViewValue === viewValue) {
+
+ // If the view value has not changed then we should just exit, except in the case where there is
+ // a native validator on the element. In this case the validation state may have changed even though
+ // the viewValue has stayed empty.
+ if (ctrl.$$lastCommittedViewValue === viewValue && (viewValue !== '' || !ctrl.$$hasNativeValidators)) {
return;
}
ctrl.$$lastCommittedViewValue = viewValue;
@@ -18651,29 +19705,50 @@ var NgModelController = ['$scope', '$exceptionHandler', '$attrs', '$element', '$
$animate.addClass($element, DIRTY_CLASS);
parentForm.$setDirty();
}
+ this.$$parseAndValidate();
+ };
- var modelValue = viewValue;
- forEach(ctrl.$parsers, function(fn) {
- modelValue = fn(modelValue);
+ this.$$parseAndValidate = function() {
+ var parserValid = true,
+ viewValue = ctrl.$$lastCommittedViewValue,
+ modelValue = viewValue;
+ for(var i = 0; i < ctrl.$parsers.length; i++) {
+ modelValue = ctrl.$parsers[i](modelValue);
+ if (isUndefined(modelValue)) {
+ parserValid = false;
+ break;
+ }
+ }
+ if (isNumber(ctrl.$modelValue) && isNaN(ctrl.$modelValue)) {
+ // ctrl.$modelValue has not been touched yet...
+ ctrl.$modelValue = ngModelGet();
+ }
+ var prevModelValue = ctrl.$modelValue;
+ var allowInvalid = ctrl.$options && ctrl.$options.allowInvalid;
+ if (allowInvalid) {
+ ctrl.$modelValue = modelValue;
+ writeToModelIfNeeded();
+ }
+ ctrl.$$runValidators(parserValid, modelValue, viewValue, function(allValid) {
+ if (!allowInvalid) {
+ // Note: Don't check ctrl.$valid here, as we could have
+ // external validators (e.g. calculated on the server),
+ // that just call $setValidity and need the model value
+ // to calculate their validity.
+ ctrl.$modelValue = allValid ? modelValue : undefined;
+ writeToModelIfNeeded();
+ }
});
- if (ctrl.$modelValue !== modelValue &&
- (isUndefined(ctrl.$$invalidModelValue) || ctrl.$$invalidModelValue != modelValue)) {
- ctrl.$$runValidators(modelValue, viewValue);
- ctrl.$$writeModelToScope();
+ function writeToModelIfNeeded() {
+ if (ctrl.$modelValue !== prevModelValue) {
+ ctrl.$$writeModelToScope();
+ }
}
};
this.$$writeModelToScope = function() {
- var getterSetter;
-
- if (ctrl.$options && ctrl.$options.getterSetter &&
- isFunction(getterSetter = ngModelGet($scope))) {
-
- getterSetter(ctrl.$modelValue);
- } else {
- ngModelSet($scope, ctrl.$modelValue);
- }
+ ngModelSet(ctrl.$modelValue);
forEach(ctrl.$viewChangeListeners, function(listener) {
try {
listener();
@@ -18723,23 +19798,23 @@ var NgModelController = ['$scope', '$exceptionHandler', '$attrs', '$element', '$
* @param {string} value Value from the view.
* @param {string} trigger Event that triggered the update.
*/
- this.$setViewValue = function(value, trigger, revalidate) {
+ this.$setViewValue = function(value, trigger) {
ctrl.$viewValue = value;
if (!ctrl.$options || ctrl.$options.updateOnDefault) {
- ctrl.$$debounceViewValueCommit(trigger, revalidate);
+ ctrl.$$debounceViewValueCommit(trigger);
}
};
- this.$$debounceViewValueCommit = function(trigger, revalidate) {
+ this.$$debounceViewValueCommit = function(trigger) {
var debounceDelay = 0,
options = ctrl.$options,
debounce;
- if(options && isDefined(options.debounce)) {
+ if (options && isDefined(options.debounce)) {
debounce = options.debounce;
- if(isNumber(debounce)) {
+ if (isNumber(debounce)) {
debounceDelay = debounce;
- } else if(isNumber(debounce[trigger])) {
+ } else if (isNumber(debounce[trigger])) {
debounceDelay = debounce[trigger];
} else if (isNumber(debounce['default'])) {
debounceDelay = debounce['default'];
@@ -18749,24 +19824,32 @@ var NgModelController = ['$scope', '$exceptionHandler', '$attrs', '$element', '$
$timeout.cancel(pendingDebounce);
if (debounceDelay) {
pendingDebounce = $timeout(function() {
- ctrl.$commitViewValue(revalidate);
+ ctrl.$commitViewValue();
}, debounceDelay);
+ } else if ($rootScope.$$phase) {
+ ctrl.$commitViewValue();
} else {
- ctrl.$commitViewValue(revalidate);
+ $scope.$apply(function() {
+ ctrl.$commitViewValue();
+ });
}
};
// model -> value
+ // Note: we cannot use a normal scope.$watch as we want to detect the following:
+ // 1. scope value is 'a'
+ // 2. user enters 'b'
+ // 3. ng-change kicks in and reverts scope value to 'a'
+ // -> scope value did not change since the last digest as
+ // ng-change executes in apply phase
+ // 4. view should be changed back to 'a'
$scope.$watch(function ngModelWatch() {
- var modelValue = ngModelGet($scope);
-
- if (ctrl.$options && ctrl.$options.getterSetter && isFunction(modelValue)) {
- modelValue = modelValue();
- }
+ var modelValue = ngModelGet();
// if scope model value and ngModel value are out of sync
- if (ctrl.$modelValue !== modelValue &&
- (isUndefined(ctrl.$$invalidModelValue) || ctrl.$$invalidModelValue != modelValue)) {
+ // TODO(perf): why not move this to the action fn?
+ if (modelValue !== ctrl.$modelValue) {
+ ctrl.$modelValue = modelValue;
var formatters = ctrl.$formatters,
idx = formatters.length;
@@ -18775,12 +19858,11 @@ var NgModelController = ['$scope', '$exceptionHandler', '$attrs', '$element', '$
while(idx--) {
viewValue = formatters[idx](viewValue);
}
-
- ctrl.$$runValidators(modelValue, viewValue);
-
if (ctrl.$viewValue !== viewValue) {
ctrl.$viewValue = ctrl.$$lastCommittedViewValue = viewValue;
ctrl.$render();
+
+ ctrl.$$runValidators(undefined, modelValue, viewValue, noop);
}
}
@@ -18953,18 +20035,20 @@ var ngModelDirective = function() {
controller: NgModelController,
link: {
pre: function(scope, element, attr, ctrls) {
- // Pass the ng-model-options to the ng-model controller
- if (ctrls[2]) {
- ctrls[0].$options = ctrls[2].$options;
- }
-
- // notify others, especially parent forms
-
var modelCtrl = ctrls[0],
formCtrl = ctrls[1] || nullFormCtrl;
+ modelCtrl.$$setOptions(ctrls[2] && ctrls[2].$options);
+
+ // notify others, especially parent forms
formCtrl.$addControl(modelCtrl);
+ attr.$observe('name', function(newValue) {
+ if (modelCtrl.$name !== newValue) {
+ formCtrl.$$renameControl(modelCtrl, newValue);
+ }
+ });
+
scope.$on('$destroy', function() {
formCtrl.$removeControl(modelCtrl);
});
@@ -18973,13 +20057,13 @@ var ngModelDirective = function() {
var modelCtrl = ctrls[0];
if (modelCtrl.$options && modelCtrl.$options.updateOn) {
element.on(modelCtrl.$options.updateOn, function(ev) {
- scope.$apply(function() {
- modelCtrl.$$debounceViewValueCommit(ev && ev.type);
- });
+ modelCtrl.$$debounceViewValueCommit(ev && ev.type);
});
}
element.on('blur', function(ev) {
+ if (modelCtrl.$touched) return;
+
scope.$apply(function() {
modelCtrl.$setTouched();
});
@@ -18999,7 +20083,15 @@ var ngModelDirective = function() {
* The expression is evaluated immediately, unlike the JavaScript onchange event
* which only triggers at the end of a change (usually, when the user leaves the
* form element or presses the return key).
- * The expression is not evaluated when the value change is coming from the model.
+ *
+ * The `ngChange` expression is only evaluated when a change in the input value causes
+ * a new value to be committed to the model.
+ *
+ * It will not be evaluated:
+ * * if the value returned from the `$parsers` transformation pipeline has not changed
+ * * if the input has continued to be invalid since the model will stay `null`
+ * * if the model is changed programmatically and not by a change to the input value
+ *
*
* Note, this directive requires `ngModel` to be present.
*
@@ -19068,8 +20160,8 @@ var requiredDirective = function() {
if (!ctrl) return;
attr.required = true; // force truthy in case we are on non input element
- ctrl.$validators.required = function(modelValue, viewValue) {
- return !attr.required || !ctrl.$isEmpty(viewValue);
+ ctrl.$validators.required = function(value) {
+ return !attr.required || !ctrl.$isEmpty(value);
};
attr.$observe('required', function() {
@@ -19089,7 +20181,7 @@ var patternDirective = function() {
var regexp, patternExp = attr.ngPattern || attr.pattern;
attr.$observe('pattern', function(regex) {
- if(isString(regex) && regex.length > 0) {
+ if (isString(regex) && regex.length > 0) {
regex = new RegExp(regex);
}
@@ -19123,8 +20215,8 @@ var maxlengthDirective = function() {
maxlength = int(value) || 0;
ctrl.$validate();
});
- ctrl.$validators.maxlength = function(value) {
- return ctrl.$isEmpty(value) || value.length <= maxlength;
+ ctrl.$validators.maxlength = function(modelValue, viewValue) {
+ return ctrl.$isEmpty(modelValue) || viewValue.length <= maxlength;
};
}
};
@@ -19142,8 +20234,8 @@ var minlengthDirective = function() {
minlength = int(value) || 0;
ctrl.$validate();
});
- ctrl.$validators.minlength = function(value) {
- return ctrl.$isEmpty(value) || value.length >= minlength;
+ ctrl.$validators.minlength = function(modelValue, viewValue) {
+ return ctrl.$isEmpty(modelValue) || viewValue.length >= minlength;
};
}
};
@@ -19192,7 +20284,7 @@ var minlengthDirective = function() {
*
*
* var listInput = element(by.model('names'));
- * var names = element(by.binding('{{names}}'));
+ * var names = element(by.exactBinding('names'));
* var valid = element(by.binding('myForm.namesInput.$valid'));
* var error = element(by.css('span.error'));
*
@@ -19222,7 +20314,7 @@ var minlengthDirective = function() {
*
* it("should split the text by newlines", function() {
* var listInput = element(by.model('list'));
- * var output = element(by.binding('{{ list | json }}'));
+ * var output = element(by.binding('list | json'));
* listInput.sendKeys('abc\ndef\nghi');
* expect(output.getText()).toContain('[\n "abc",\n "def",\n "ghi"\n]');
* });
@@ -19235,6 +20327,7 @@ var minlengthDirective = function() {
var ngListDirective = function() {
return {
restrict: 'A',
+ priority: 100,
require: 'ngModel',
link: function(scope, element, attr, ctrl) {
// We want to control whitespace trimming so we use this convoluted approach
@@ -19372,6 +20465,8 @@ var ngValueDirective = function() {
* `submit` event. Note that `ngClick` events will occur before the model is updated. Use `ngSubmit`
* to have access to the updated model.
*
+ * `ngModelOptions` has an effect on the element it's declared on and its descendants.
+ *
* @param {Object} ngModelOptions options to apply to the current model. Valid keys are:
* - `updateOn`: string specifying which event should be the input bound to. You can set several
* events using an space delimited list. There is a special event called `default` that
@@ -19379,9 +20474,14 @@ var ngValueDirective = function() {
* - `debounce`: integer value which contains the debounce model update value in milliseconds. A
* value of 0 triggers an immediate update. If an object is supplied instead, you can specify a
* custom value for each event. For example:
- * `ngModelOptions="{ updateOn: 'default blur', debounce: {'default': 500, 'blur': 0} }"`
+ * `ng-model-options="{ updateOn: 'default blur', debounce: {'default': 500, 'blur': 0} }"`
+ * - `allowInvalid`: boolean value which indicates that the model can be set with values that did
+ * not validate correctly instead of the default behavior of setting the model to undefined.
* - `getterSetter`: boolean value which determines whether or not to treat functions bound to
`ngModel` as getters/setters.
+ * - `timezone`: Defines the timezone to be used to read/write the `Date` instance in the model for
+ * ` `, ` `, ... . Right now, the only supported value is `'UTC'`,
+ * otherwise the default timezone of the browser will be used.
*
* @example
@@ -19513,6 +20613,109 @@ var ngModelOptionsDirective = function() {
};
};
+// helper methods
+function addSetValidityMethod(context) {
+ var ctrl = context.ctrl,
+ $element = context.$element,
+ classCache = {},
+ set = context.set,
+ unset = context.unset,
+ parentForm = context.parentForm,
+ $animate = context.$animate;
+
+ ctrl.$setValidity = setValidity;
+ toggleValidationCss('', true);
+
+ function setValidity(validationErrorKey, state, options) {
+ if (state === undefined) {
+ createAndSet('$pending', validationErrorKey, options);
+ } else {
+ unsetAndCleanup('$pending', validationErrorKey, options);
+ }
+ if (!isBoolean(state)) {
+ unset(ctrl.$error, validationErrorKey, options);
+ unset(ctrl.$$success, validationErrorKey, options);
+ } else {
+ if (state) {
+ unset(ctrl.$error, validationErrorKey, options);
+ set(ctrl.$$success, validationErrorKey, options);
+ } else {
+ set(ctrl.$error, validationErrorKey, options);
+ unset(ctrl.$$success, validationErrorKey, options);
+ }
+ }
+ if (ctrl.$pending) {
+ cachedToggleClass(PENDING_CLASS, true);
+ ctrl.$valid = ctrl.$invalid = undefined;
+ toggleValidationCss('', null);
+ } else {
+ cachedToggleClass(PENDING_CLASS, false);
+ ctrl.$valid = isObjectEmpty(ctrl.$error);
+ ctrl.$invalid = !ctrl.$valid;
+ toggleValidationCss('', ctrl.$valid);
+ }
+
+ // re-read the state as the set/unset methods could have
+ // combined state in ctrl.$error[validationError] (used for forms),
+ // where setting/unsetting only increments/decrements the value,
+ // and does not replace it.
+ var combinedState;
+ if (ctrl.$pending && ctrl.$pending[validationErrorKey]) {
+ combinedState = undefined;
+ } else if (ctrl.$error[validationErrorKey]) {
+ combinedState = false;
+ } else if (ctrl.$$success[validationErrorKey]) {
+ combinedState = true;
+ } else {
+ combinedState = null;
+ }
+ toggleValidationCss(validationErrorKey, combinedState);
+ parentForm.$setValidity(validationErrorKey, combinedState, ctrl);
+ }
+
+ function createAndSet(name, value, options) {
+ if (!ctrl[name]) {
+ ctrl[name] = {};
+ }
+ set(ctrl[name], value, options);
+ }
+
+ function unsetAndCleanup(name, value, options) {
+ if (ctrl[name]) {
+ unset(ctrl[name], value, options);
+ }
+ if (isObjectEmpty(ctrl[name])) {
+ ctrl[name] = undefined;
+ }
+ }
+
+ function cachedToggleClass(className, switchValue) {
+ if (switchValue && !classCache[className]) {
+ $animate.addClass($element, className);
+ classCache[className] = true;
+ } else if (!switchValue && classCache[className]) {
+ $animate.removeClass($element, className);
+ classCache[className] = false;
+ }
+ }
+
+ function toggleValidationCss(validationErrorKey, isValid) {
+ validationErrorKey = validationErrorKey ? '-' + snake_case(validationErrorKey, '-') : '';
+
+ cachedToggleClass(VALID_CLASS + validationErrorKey, isValid === true);
+ cachedToggleClass(INVALID_CLASS + validationErrorKey, isValid === false);
+ }
+}
+
+function isObjectEmpty(obj) {
+ if (obj) {
+ for (var prop in obj) {
+ return false;
+ }
+ }
+ return true;
+}
+
/**
* @ngdoc directive
* @name ngBind
@@ -19564,20 +20767,23 @@ var ngModelOptionsDirective = function() {
*/
-var ngBindDirective = ngDirective({
- compile: function(templateElement) {
- templateElement.addClass('ng-binding');
- return function (scope, element, attr) {
- element.data('$binding', attr.ngBind);
- scope.$watch(attr.ngBind, function ngBindWatchAction(value) {
- // We are purposefully using == here rather than === because we want to
- // catch when value is "null or undefined"
- // jshint -W041
- element.text(value == undefined ? '' : value);
- });
- };
- }
-});
+var ngBindDirective = ['$compile', function($compile) {
+ return {
+ restrict: 'AC',
+ compile: function ngBindCompile(templateElement) {
+ $compile.$$addBindingClass(templateElement);
+ return function ngBindLink(scope, element, attr) {
+ $compile.$$addBindingInfo(element, attr.ngBind);
+ scope.$watch(attr.ngBind, function ngBindWatchAction(value) {
+ // We are purposefully using == here rather than === because we want to
+ // catch when value is "null or undefined"
+ // jshint -W041
+ element.text(value == undefined ? '' : value);
+ });
+ };
+ }
+ };
+}];
/**
@@ -19631,14 +20837,18 @@ var ngBindDirective = ngDirective({
*/
-var ngBindTemplateDirective = ['$interpolate', function($interpolate) {
- return function(scope, element, attr) {
- // TODO: move this to scenario runner
- var interpolateFn = $interpolate(element.attr(attr.$attr.ngBindTemplate));
- element.addClass('ng-binding').data('$binding', interpolateFn);
- attr.$observe('ngBindTemplate', function(value) {
- element.text(value);
- });
+var ngBindTemplateDirective = ['$interpolate', '$compile', function($interpolate, $compile) {
+ return {
+ compile: function ngBindTemplateCompile(templateElement) {
+ $compile.$$addBindingClass(templateElement);
+ return function ngBindTemplateLink(scope, element, attr) {
+ var interpolateFn = $interpolate(element.attr(attr.$attr.ngBindTemplate));
+ $compile.$$addBindingInfo(element, interpolateFn.expressions);
+ attr.$observe('ngBindTemplate', function(value) {
+ element.text(value);
+ });
+ };
+ }
};
}];
@@ -19663,7 +20873,6 @@ var ngBindTemplateDirective = ['$interpolate', function($interpolate) {
* @param {expression} ngBindHtml {@link guide/expression Expression} to evaluate.
*
* @example
- Try it here: enter text in text box and watch the greeting change.
@@ -19689,23 +20898,23 @@ var ngBindTemplateDirective = ['$interpolate', function($interpolate) {
*/
-var ngBindHtmlDirective = ['$sce', '$parse', function($sce, $parse) {
+var ngBindHtmlDirective = ['$sce', '$parse', '$compile', function($sce, $parse, $compile) {
return {
restrict: 'A',
- compile: function (tElement, tAttrs) {
- tElement.addClass('ng-binding');
+ compile: function ngBindHtmlCompile(tElement, tAttrs) {
+ var ngBindHtmlGetter = $parse(tAttrs.ngBindHtml);
+ var ngBindHtmlWatch = $parse(tAttrs.ngBindHtml, function getStringValue(value) {
+ return (value || '').toString();
+ });
+ $compile.$$addBindingClass(tElement);
- return function (scope, element, attr) {
- element.data('$binding', attr.ngBindHtml);
- var parsed = $parse(attr.ngBindHtml);
- var changeDetector = $parse(attr.ngBindHtml, function getStringValue(value) {
- return (value || '').toString();
- });
+ return function ngBindHtmlLink(scope, element, attr) {
+ $compile.$$addBindingInfo(element, attr.ngBindHtml);
- scope.$watch(changeDetector, function ngBindHtmlWatchAction() {
+ scope.$watch(ngBindHtmlWatch, function ngBindHtmlWatchAction() {
// we re-evaluate the expr because we want a TrustedValueHolderType
// for $sce, not a string
- element.html($sce.getTrustedHtml(parsed(scope)) || '');
+ element.html($sce.getTrustedHtml(ngBindHtmlGetter(scope)) || '');
});
};
}
@@ -19768,15 +20977,13 @@ function classDirective(name, selector) {
function updateClasses (oldClasses, newClasses) {
var toAdd = arrayDifference(newClasses, oldClasses);
var toRemove = arrayDifference(oldClasses, newClasses);
- toRemove = digestClassCounts(toRemove, -1);
toAdd = digestClassCounts(toAdd, 1);
-
- if (toAdd.length === 0) {
- $animate.removeClass(element, toRemove);
- } else if (toRemove.length === 0) {
+ toRemove = digestClassCounts(toRemove, -1);
+ if (toAdd && toAdd.length) {
$animate.addClass(element, toAdd);
- } else {
- $animate.setClass(element, toAdd, toRemove);
+ }
+ if (toRemove && toRemove.length) {
+ $animate.removeClass(element, toRemove);
}
}
@@ -20156,10 +21363,17 @@ var ngCloakDirective = ngDirective({
*
* @element ANY
* @scope
- * @param {expression} ngController Name of a globally accessible constructor function or an
- * {@link guide/expression expression} that on the current scope evaluates to a
- * constructor function. The controller instance can be published into a scope property
- * by specifying `as propertyName`.
+ * @priority 500
+ * @param {expression} ngController Name of a constructor function registered with the current
+ * {@link ng.$controllerProvider $controllerProvider} or an {@link guide/expression expression}
+ * that on the current scope evaluates to a constructor function.
+ *
+ * The controller instance can be published into a scope property by specifying
+ * `ng-controller="as propertyName"`.
+ *
+ * If the current `$controllerProvider` is configured to use globals (via
+ * {@link ng.$controllerProvider#allowGlobals `$controllerProvider.allowGlobals()` }), this may
+ * also be the name of a globally accessible constructor function (not recommended).
*
* @example
* Here is a simple form for editing user contact information. Adding, removing, clearing, and
@@ -20435,7 +21649,9 @@ var ngControllerDirective = [function() {
Increment
- count: {{count}}
+
+ count: {{count}}
+
it('should check ng-click', function() {
@@ -20453,20 +21669,33 @@ var ngControllerDirective = [function() {
* Events that are handled via these handler are always configured not to propagate further.
*/
var ngEventDirectives = {};
+
+// For events that might fire synchronously during DOM manipulation
+// we need to execute their event handlers asynchronously using $evalAsync,
+// so that they are not executed in an inconsistent state.
+var forceAsyncEvents = {
+ 'blur': true,
+ 'focus': true
+};
forEach(
'click dblclick mousedown mouseup mouseover mouseout mousemove mouseenter mouseleave keydown keyup keypress submit focus blur copy cut paste'.split(' '),
- function(name) {
- var directiveName = directiveNormalize('ng-' + name);
- ngEventDirectives[directiveName] = ['$parse', function($parse) {
+ function(eventName) {
+ var directiveName = directiveNormalize('ng-' + eventName);
+ ngEventDirectives[directiveName] = ['$parse', '$rootScope', function($parse, $rootScope) {
return {
restrict: 'A',
compile: function($element, attr) {
var fn = $parse(attr[directiveName]);
return function ngEventHandler(scope, element) {
- element.on(lowercase(name), function(event) {
- scope.$apply(function() {
+ element.on(eventName, function(event) {
+ var callback = function() {
fn(scope, {$event:event});
- });
+ };
+ if (forceAsyncEvents[eventName] && $rootScope.$$phase) {
+ scope.$evalAsync(callback);
+ } else {
+ scope.$apply(callback);
+ }
});
};
}
@@ -20724,6 +21953,13 @@ forEach(
* server and reloading the current page), but only if the form does not contain `action`,
* `data-action`, or `x-action` attributes.
*
+ *
+ * **Warning:** Be careful not to cause "double-submission" by using both the `ngClick` and
+ * `ngSubmit` handlers together. See the
+ * {@link form#submitting-a-form-and-preventing-the-default-action `form` directive documentation}
+ * for a detailed discussion of when `ngSubmit` may be triggered.
+ *
+ *
* @element form
* @priority 0
* @param {expression} ngSubmit {@link guide/expression Expression} to eval.
@@ -20776,6 +22012,10 @@ forEach(
* @description
* Specify custom behavior on focus event.
*
+ * Note: As the `focus` event is executed synchronously when calling `input.focus()`
+ * AngularJS executes the expression using `scope.$evalAsync` if the event is fired
+ * during an `$apply` to ensure a consistent state.
+ *
* @element window, input, select, textarea, a
* @priority 0
* @param {expression} ngFocus {@link guide/expression Expression} to evaluate upon
@@ -20792,6 +22032,14 @@ forEach(
* @description
* Specify custom behavior on blur event.
*
+ * A [blur event](https://developer.mozilla.org/en-US/docs/Web/Events/blur) fires when
+ * an element has lost focus.
+ *
+ * Note: As the `blur` event is executed synchronously also during DOM manipulations
+ * (e.g. removing a focussed input),
+ * AngularJS executes the expression using `scope.$evalAsync` if the event is fired
+ * during an `$apply` to ensure a consistent state.
+ *
* @element window, input, select, textarea, a
* @priority 0
* @param {expression} ngBlur {@link guide/expression Expression} to evaluate upon
@@ -20976,8 +22224,8 @@ var ngIfDirective = ['$animate', function($animate) {
childScope = null;
}
if(block) {
- previousElements = getBlockElements(block.clone);
- $animate.leave(previousElements, function() {
+ previousElements = getBlockNodes(block.clone);
+ $animate.leave(previousElements).then(function() {
previousElements = null;
});
block = null;
@@ -21138,6 +22386,9 @@ var ngIfDirective = ['$animate', function($animate) {
* @eventType emit on the scope ngInclude was declared in
* @description
* Emitted every time the ngInclude content is requested.
+ *
+ * @param {Object} angularEvent Synthetic event object.
+ * @param {String} src URL of content to load.
*/
@@ -21147,6 +22398,9 @@ var ngIfDirective = ['$animate', function($animate) {
* @eventType emit on the current ngInclude scope
* @description
* Emitted every time the ngInclude content is reloaded.
+ *
+ * @param {Object} angularEvent Synthetic event object.
+ * @param {String} src URL of content to load.
*/
@@ -21156,9 +22410,12 @@ var ngIfDirective = ['$animate', function($animate) {
* @eventType emit on the scope ngInclude was declared in
* @description
* Emitted when a template HTTP request yields an erronous response (status < 200 || status > 299)
+ *
+ * @param {Object} angularEvent Synthetic event object.
+ * @param {String} src URL of content to load.
*/
-var ngIncludeDirective = ['$http', '$templateCache', '$anchorScroll', '$animate', '$sce',
- function($http, $templateCache, $anchorScroll, $animate, $sce) {
+var ngIncludeDirective = ['$templateRequest', '$anchorScroll', '$animate', '$sce',
+ function($templateRequest, $anchorScroll, $animate, $sce) {
return {
restrict: 'ECA',
priority: 400,
@@ -21186,7 +22443,7 @@ var ngIncludeDirective = ['$http', '$templateCache', '$anchorScroll', '$animate'
currentScope = null;
}
if(currentElement) {
- $animate.leave(currentElement, function() {
+ $animate.leave(currentElement).then(function() {
previousElement = null;
});
previousElement = currentElement;
@@ -21203,7 +22460,9 @@ var ngIncludeDirective = ['$http', '$templateCache', '$anchorScroll', '$animate'
var thisChangeId = ++changeCounter;
if (src) {
- $http.get(src, {cache: $templateCache}).success(function(response) {
+ //set the 2nd param to true to ignore the template request error so that the inner
+ //contents and scope can be cleaned up.
+ $templateRequest(src, true).then(function(response) {
if (thisChangeId !== changeCounter) return;
var newScope = scope.$new();
ctrl.template = response;
@@ -21216,21 +22475,21 @@ var ngIncludeDirective = ['$http', '$templateCache', '$anchorScroll', '$animate'
// directives to non existing elements.
var clone = $transclude(newScope, function(clone) {
cleanupLastIncludeContent();
- $animate.enter(clone, null, $element, afterAnimation);
+ $animate.enter(clone, null, $element).then(afterAnimation);
});
currentScope = newScope;
currentElement = clone;
- currentScope.$emit('$includeContentLoaded');
+ currentScope.$emit('$includeContentLoaded', src);
scope.$eval(onloadExp);
- }).error(function() {
+ }, function() {
if (thisChangeId === changeCounter) {
cleanupLastIncludeContent();
- scope.$emit('$includeContentError');
+ scope.$emit('$includeContentError', src);
}
});
- scope.$emit('$includeContentRequested');
+ scope.$emit('$includeContentRequested', src);
} else {
cleanupLastIncludeContent();
ctrl.template = null;
@@ -21253,6 +22512,18 @@ var ngIncludeFillContentDirective = ['$compile',
priority: -400,
require: 'ngInclude',
link: function(scope, $element, $attr, ctrl) {
+ if (/SVG/.test($element[0].toString())) {
+ // WebKit: https://bugs.webkit.org/show_bug.cgi?id=135698 --- SVG elements do not
+ // support innerHTML, so detect this here and try to generate the contents
+ // specially.
+ $element.empty();
+ $compile(jqLiteBuildFragment(ctrl.template, document).childNodes)(scope,
+ function namespaceAdaptedClone(clone) {
+ $element.append(clone);
+ }, undefined, undefined, $element);
+ return;
+ }
+
$element.html(ctrl.template);
$compile($element.contents())(scope);
}
@@ -21787,6 +23058,29 @@ var ngPluralizeDirective = ['$locale', '$interpolate', function($locale, $interp
var ngRepeatDirective = ['$parse', '$animate', function($parse, $animate) {
var NG_REMOVED = '$$NG_REMOVED';
var ngRepeatMinErr = minErr('ngRepeat');
+
+ var updateScope = function(scope, index, valueIdentifier, value, keyIdentifier, key, arrayLength) {
+ // TODO(perf): generate setters to shave off ~40ms or 1-1.5%
+ scope[valueIdentifier] = value;
+ if (keyIdentifier) scope[keyIdentifier] = key;
+ scope.$index = index;
+ scope.$first = (index === 0);
+ scope.$last = (index === (arrayLength - 1));
+ scope.$middle = !(scope.$first || scope.$last);
+ // jshint bitwise: false
+ scope.$odd = !(scope.$even = (index&1) === 0);
+ // jshint bitwise: true
+ };
+
+ var getBlockStart = function(block) {
+ return block.clone[0];
+ };
+
+ var getBlockEnd = function(block) {
+ return block.clone[block.clone.length - 1];
+ };
+
+
return {
restrict: 'A',
multiElement: true,
@@ -21794,25 +23088,54 @@ var ngRepeatDirective = ['$parse', '$animate', function($parse, $animate) {
priority: 1000,
terminal: true,
$$tlb: true,
- link: function($scope, $element, $attr, ctrl, $transclude){
- var expression = $attr.ngRepeat;
- var match = expression.match(/^\s*([\s\S]+?)\s+in\s+([\s\S]+?)(?:\s+as\s+([\s\S]+?))?(?:\s+track\s+by\s+([\s\S]+?))?\s*$/),
- trackByExp, trackByExpGetter, aliasAs, trackByIdExpFn, trackByIdArrayFn, trackByIdObjFn,
- lhs, rhs, valueIdentifier, keyIdentifier,
- hashFnLocals = {$id: hashKey};
+ compile: function ngRepeatCompile($element, $attr) {
+ var expression = $attr.ngRepeat;
+ var ngRepeatEndComment = document.createComment(' end ngRepeat: ' + expression + ' ');
- if (!match) {
- throw ngRepeatMinErr('iexp', "Expected expression in form of '_item_ in _collection_[ track by _id_]' but got '{0}'.",
+ var match = expression.match(/^\s*([\s\S]+?)\s+in\s+([\s\S]+?)(?:\s+as\s+([\s\S]+?))?(?:\s+track\s+by\s+([\s\S]+?))?\s*$/);
+
+ if (!match) {
+ throw ngRepeatMinErr('iexp', "Expected expression in form of '_item_ in _collection_[ track by _id_]' but got '{0}'.",
expression);
- }
+ }
- lhs = match[1];
- rhs = match[2];
- aliasAs = match[3];
- trackByExp = match[4];
+ var lhs = match[1];
+ var rhs = match[2];
+ var aliasAs = match[3];
+ var trackByExp = match[4];
- if (trackByExp) {
- trackByExpGetter = $parse(trackByExp);
+ match = lhs.match(/^(?:([\$\w]+)|\(([\$\w]+)\s*,\s*([\$\w]+)\))$/);
+
+ if (!match) {
+ throw ngRepeatMinErr('iidexp', "'_item_' in '_item_ in _collection_' should be an identifier or '(_key_, _value_)' expression, but got '{0}'.",
+ lhs);
+ }
+ var valueIdentifier = match[3] || match[1];
+ var keyIdentifier = match[2];
+
+ if (aliasAs && (!/^[$a-zA-Z_][$a-zA-Z0-9_]*$/.test(aliasAs) ||
+ /^(null|undefined|this|\$index|\$first|\$middle|\$last|\$even|\$odd|\$parent)$/.test(aliasAs))) {
+ throw ngRepeatMinErr('badident', "alias '{0}' is invalid --- must be a valid JS identifier which is not a reserved name.",
+ aliasAs);
+ }
+
+ var trackByExpGetter, trackByIdExpFn, trackByIdArrayFn, trackByIdObjFn;
+ var hashFnLocals = {$id: hashKey};
+
+ if (trackByExp) {
+ trackByExpGetter = $parse(trackByExp);
+ } else {
+ trackByIdArrayFn = function (key, value) {
+ return hashKey(value);
+ };
+ trackByIdObjFn = function (key) {
+ return key;
+ };
+ }
+
+ return function ngRepeatLink($scope, $element, $attr, ctrl, $transclude) {
+
+ if (trackByExpGetter) {
trackByIdExpFn = function(key, value, index) {
// assign key, value, and $index to the locals so that they can be used in hash functions
if (keyIdentifier) hashFnLocals[keyIdentifier] = key;
@@ -21820,63 +23143,40 @@ var ngRepeatDirective = ['$parse', '$animate', function($parse, $animate) {
hashFnLocals.$index = index;
return trackByExpGetter($scope, hashFnLocals);
};
- } else {
- trackByIdArrayFn = function(key, value) {
- return hashKey(value);
- };
- trackByIdObjFn = function(key) {
- return key;
- };
}
- match = lhs.match(/^(?:([\$\w]+)|\(([\$\w]+)\s*,\s*([\$\w]+)\))$/);
- if (!match) {
- throw ngRepeatMinErr('iidexp', "'_item_' in '_item_ in _collection_' should be an identifier or '(_key_, _value_)' expression, but got '{0}'.",
- lhs);
- }
- valueIdentifier = match[3] || match[1];
- keyIdentifier = match[2];
-
// Store a list of elements from previous run. This is a hash where key is the item from the
// iterator, and the value is objects with following properties.
// - scope: bound scope
// - element: previous element.
// - index: position
- var lastBlockMap = {};
+ //
+ // We are using no-proto object so that we don't need to guard against inherited props via
+ // hasOwnProperty.
+ var lastBlockMap = createMap();
//watch props
- $scope.$watchCollection(rhs, function ngRepeatAction(collection){
+ $scope.$watchCollection(rhs, function ngRepeatAction(collection) {
var index, length,
- previousNode = $element[0], // current position of the node
+ previousNode = $element[0], // node that cloned nodes should be inserted after
+ // initialized to the comment node anchor
nextNode,
// Same as lastBlockMap but it has the current state. It will become the
// lastBlockMap on the next iteration.
- nextBlockMap = {},
- arrayLength,
+ nextBlockMap = createMap(),
+ collectionLength,
key, value, // key/value of iteration
trackById,
trackByIdFn,
collectionKeys,
block, // last object information {scope, element, id}
- nextBlockOrder = [],
+ nextBlockOrder,
elementsToRemove;
if (aliasAs) {
$scope[aliasAs] = collection;
}
- var updateScope = function(scope, index) {
- scope[valueIdentifier] = value;
- if (keyIdentifier) scope[keyIdentifier] = key;
- scope.$index = index;
- scope.$first = (index === 0);
- scope.$last = (index === (arrayLength - 1));
- scope.$middle = !(scope.$first || scope.$last);
- // jshint bitwise: false
- scope.$odd = !(scope.$even = (index&1) === 0);
- // jshint bitwise: true
- };
-
if (isArrayLike(collection)) {
collectionKeys = collection;
trackByIdFn = trackByIdExpFn || trackByIdArrayFn;
@@ -21892,96 +23192,98 @@ var ngRepeatDirective = ['$parse', '$animate', function($parse, $animate) {
collectionKeys.sort();
}
- arrayLength = collectionKeys.length;
+ collectionLength = collectionKeys.length;
+ nextBlockOrder = new Array(collectionLength);
// locate existing items
- length = nextBlockOrder.length = collectionKeys.length;
- for(index = 0; index < length; index++) {
- key = (collection === collectionKeys) ? index : collectionKeys[index];
- value = collection[key];
- trackById = trackByIdFn(key, value, index);
- assertNotHasOwnProperty(trackById, '`track by` id');
- if(lastBlockMap.hasOwnProperty(trackById)) {
- block = lastBlockMap[trackById];
- delete lastBlockMap[trackById];
- nextBlockMap[trackById] = block;
- nextBlockOrder[index] = block;
- } else if (nextBlockMap.hasOwnProperty(trackById)) {
- // restore lastBlockMap
- forEach(nextBlockOrder, function(block) {
- if (block && block.scope) lastBlockMap[block.id] = block;
- });
- // This is a duplicate and we need to throw an error
- throw ngRepeatMinErr('dupes', "Duplicates in a repeater are not allowed. Use 'track by' expression to specify unique keys. Repeater: {0}, Duplicate key: {1}",
- expression, trackById);
- } else {
- // new never before seen block
- nextBlockOrder[index] = { id: trackById };
- nextBlockMap[trackById] = false;
- }
- }
-
- // remove existing items
- for (var blockKey in lastBlockMap) {
- // lastBlockMap is our own object so we don't need to use special hasOwnPropertyFn
- if (lastBlockMap.hasOwnProperty(blockKey)) {
- block = lastBlockMap[blockKey];
- elementsToRemove = getBlockElements(block.clone);
- $animate.leave(elementsToRemove);
- forEach(elementsToRemove, function(element) { element[NG_REMOVED] = true; });
- block.scope.$destroy();
+ for (index = 0; index < collectionLength; index++) {
+ key = (collection === collectionKeys) ? index : collectionKeys[index];
+ value = collection[key];
+ trackById = trackByIdFn(key, value, index);
+ if (lastBlockMap[trackById]) {
+ // found previously seen block
+ block = lastBlockMap[trackById];
+ delete lastBlockMap[trackById];
+ nextBlockMap[trackById] = block;
+ nextBlockOrder[index] = block;
+ } else if (nextBlockMap[trackById]) {
+ // if collision detected. restore lastBlockMap and throw an error
+ forEach(nextBlockOrder, function (block) {
+ if (block && block.scope) lastBlockMap[block.id] = block;
+ });
+ throw ngRepeatMinErr('dupes',
+ "Duplicates in a repeater are not allowed. Use 'track by' expression to specify unique keys. Repeater: {0}, Duplicate key: {1}, Duplicate value: {2}",
+ expression, trackById, toJson(value));
+ } else {
+ // new never before seen block
+ nextBlockOrder[index] = {id: trackById, scope: undefined, clone: undefined};
+ nextBlockMap[trackById] = true;
}
}
+ // remove leftover items
+ for (var blockKey in lastBlockMap) {
+ block = lastBlockMap[blockKey];
+ elementsToRemove = getBlockNodes(block.clone);
+ $animate.leave(elementsToRemove);
+ if (elementsToRemove[0].parentNode) {
+ // if the element was not removed yet because of pending animation, mark it as deleted
+ // so that we can ignore it later
+ for (index = 0, length = elementsToRemove.length; index < length; index++) {
+ elementsToRemove[index][NG_REMOVED] = true;
+ }
+ }
+ block.scope.$destroy();
+ }
+
// we are not using forEach for perf reasons (trying to avoid #call)
- for (index = 0, length = collectionKeys.length; index < length; index++) {
+ for (index = 0; index < collectionLength; index++) {
key = (collection === collectionKeys) ? index : collectionKeys[index];
value = collection[key];
block = nextBlockOrder[index];
- if (nextBlockOrder[index - 1]) previousNode = getBlockEnd(nextBlockOrder[index - 1]);
if (block.scope) {
// if we have already seen this object, then we need to reuse the
// associated scope/element
+
nextNode = previousNode;
+
+ // skip nodes that are already pending removal via leave animation
do {
nextNode = nextNode.nextSibling;
- } while(nextNode && nextNode[NG_REMOVED]);
+ } while (nextNode && nextNode[NG_REMOVED]);
if (getBlockStart(block) != nextNode) {
// existing item which got moved
- $animate.move(getBlockElements(block.clone), null, jqLite(previousNode));
+ $animate.move(getBlockNodes(block.clone), null, jqLite(previousNode));
}
previousNode = getBlockEnd(block);
- updateScope(block.scope, index);
+ updateScope(block.scope, index, valueIdentifier, value, keyIdentifier, key, collectionLength);
} else {
// new item which we don't know about
- $transclude(function(clone, scope) {
+ $transclude(function ngRepeatTransclude(clone, scope) {
block.scope = scope;
- clone[clone.length++] = document.createComment(' end ngRepeat: ' + expression + ' ');
+ // http://jsperf.com/clone-vs-createcomment
+ var endNode = ngRepeatEndComment.cloneNode(false);
+ clone[clone.length++] = endNode;
+
+ // TODO(perf): support naked previousNode in `enter` to avoid creation of jqLite wrapper?
$animate.enter(clone, null, jqLite(previousNode));
- previousNode = clone;
+ previousNode = endNode;
// Note: We only need the first/last node of the cloned nodes.
// However, we need to keep the reference to the jqlite wrapper as it might be changed later
// by a directive with templateUrl when its template arrives.
block.clone = clone;
nextBlockMap[block.id] = block;
- updateScope(block.scope, index);
+ updateScope(block.scope, index, valueIdentifier, value, keyIdentifier, key, collectionLength);
});
}
}
lastBlockMap = nextBlockMap;
});
+ };
}
};
-
- function getBlockStart(block) {
- return block.clone[0];
- }
-
- function getBlockEnd(block) {
- return block.clone[block.clone.length - 1];
- }
}];
/**
@@ -21990,8 +23292,8 @@ var ngRepeatDirective = ['$parse', '$animate', function($parse, $animate) {
*
* @description
* The `ngShow` directive shows or hides the given HTML element based on the expression
- * provided to the ngShow attribute. The element is shown or hidden by removing or adding
- * the `ng-hide` CSS class onto the element. The `.ng-hide` CSS class is predefined
+ * provided to the `ngShow` attribute. The element is shown or hidden by removing or adding
+ * the `.ng-hide` CSS class onto the element. The `.ng-hide` CSS class is predefined
* in AngularJS and sets the display style to none (using an !important flag).
* For CSP mode please add `angular-csp.css` to your html file (see {@link ng.directive:ngCsp ngCsp}).
*
@@ -22003,13 +23305,13 @@ var ngRepeatDirective = ['$parse', '$animate', function($parse, $animate) {
*
* ```
*
- * When the ngShow expression evaluates to a falsy value then the ng-hide CSS class is added to the class
- * attribute on the element causing it to become hidden. When truthy, the ng-hide CSS class is removed
+ * When the `ngShow` expression evaluates to a falsy value then the `.ng-hide` CSS class is added to the class
+ * attribute on the element causing it to become hidden. When truthy, the `.ng-hide` CSS class is removed
* from the element causing the element not to appear hidden.
*
* ## Why is !important used?
*
- * You may be wondering why !important is used for the .ng-hide CSS class. This is because the `.ng-hide` selector
+ * You may be wondering why !important is used for the `.ng-hide` CSS class. This is because the `.ng-hide` selector
* can be easily overridden by heavier selectors. For example, something as simple
* as changing the display style on a HTML list item would make hidden elements appear visible.
* This also becomes a bigger issue when dealing with CSS frameworks.
@@ -22018,7 +23320,7 @@ var ngRepeatDirective = ['$parse', '$animate', function($parse, $animate) {
* specificity (when !important isn't used with any conflicting styles). If a developer chooses to override the
* styling to change how to hide an element then it is just a matter of using !important in their own CSS code.
*
- * ### Overriding .ng-hide
+ * ### Overriding `.ng-hide`
*
* By default, the `.ng-hide` class will style the element with `display:none!important`. If you wish to change
* the hide behavior with ngShow/ngHide then this can be achieved by restating the styles for the `.ng-hide`
@@ -22036,7 +23338,7 @@ var ngRepeatDirective = ['$parse', '$animate', function($parse, $animate) {
*
* By default you don't need to override in CSS anything and the animations will work around the display style.
*
- * ## A note about animations with ngShow
+ * ## A note about animations with `ngShow`
*
* Animations in ngShow/ngHide work with the show and hide events that are triggered when the directive expression
* is true and false. This system works like the animation system present with ngClass except that
@@ -22069,8 +23371,8 @@ var ngRepeatDirective = ['$parse', '$animate', function($parse, $animate) {
* property to block during animation states--ngAnimate will handle the style toggling automatically for you.
*
* @animations
- * addClass: .ng-hide - happens after the ngShow expression evaluates to a truthy value and the just before contents are set to visible
- * removeClass: .ng-hide - happens after the ngShow expression evaluates to a non truthy value and just before the contents are set to hidden
+ * addClass: `.ng-hide` - happens after the `ngShow` expression evaluates to a truthy value and the just before contents are set to visible
+ * removeClass: `.ng-hide` - happens after the `ngShow` expression evaluates to a non truthy value and just before the contents are set to hidden
*
* @element ANY
* @param {expression} ngShow If the {@link guide/expression expression} is truthy
@@ -22158,7 +23460,7 @@ var ngShowDirective = ['$animate', function($animate) {
*
* @description
* The `ngHide` directive shows or hides the given HTML element based on the expression
- * provided to the ngHide attribute. The element is shown or hidden by removing or adding
+ * provided to the `ngHide` attribute. The element is shown or hidden by removing or adding
* the `ng-hide` CSS class onto the element. The `.ng-hide` CSS class is predefined
* in AngularJS and sets the display style to none (using an !important flag).
* For CSP mode please add `angular-csp.css` to your html file (see {@link ng.directive:ngCsp ngCsp}).
@@ -22171,13 +23473,13 @@ var ngShowDirective = ['$animate', function($animate) {
*
* ```
*
- * When the ngHide expression evaluates to a truthy value then the .ng-hide CSS class is added to the class
- * attribute on the element causing it to become hidden. When falsy, the ng-hide CSS class is removed
+ * When the `ngHide` expression evaluates to a truthy value then the `.ng-hide` CSS class is added to the class
+ * attribute on the element causing it to become hidden. When falsy, the `.ng-hide` CSS class is removed
* from the element causing the element not to appear hidden.
*
* ## Why is !important used?
*
- * You may be wondering why !important is used for the .ng-hide CSS class. This is because the `.ng-hide` selector
+ * You may be wondering why !important is used for the `.ng-hide` CSS class. This is because the `.ng-hide` selector
* can be easily overridden by heavier selectors. For example, something as simple
* as changing the display style on a HTML list item would make hidden elements appear visible.
* This also becomes a bigger issue when dealing with CSS frameworks.
@@ -22186,7 +23488,7 @@ var ngShowDirective = ['$animate', function($animate) {
* specificity (when !important isn't used with any conflicting styles). If a developer chooses to override the
* styling to change how to hide an element then it is just a matter of using !important in their own CSS code.
*
- * ### Overriding .ng-hide
+ * ### Overriding `.ng-hide`
*
* By default, the `.ng-hide` class will style the element with `display:none!important`. If you wish to change
* the hide behavior with ngShow/ngHide then this can be achieved by restating the styles for the `.ng-hide`
@@ -22204,7 +23506,7 @@ var ngShowDirective = ['$animate', function($animate) {
*
* By default you don't need to override in CSS anything and the animations will work around the display style.
*
- * ## A note about animations with ngHide
+ * ## A note about animations with `ngHide`
*
* Animations in ngShow/ngHide work with the show and hide events that are triggered when the directive expression
* is true and false. This system works like the animation system present with ngClass, except that the `.ng-hide`
@@ -22228,8 +23530,8 @@ var ngShowDirective = ['$animate', function($animate) {
* property to block during animation states--ngAnimate will handle the style toggling automatically for you.
*
* @animations
- * removeClass: .ng-hide - happens after the ngHide expression evaluates to a truthy value and just before the contents are set to hidden
- * addClass: .ng-hide - happens after the ngHide expression evaluates to a non truthy value and just before the contents are set to visible
+ * removeClass: `.ng-hide` - happens after the `ngHide` expression evaluates to a truthy value and just before the contents are set to hidden
+ * addClass: `.ng-hide` - happens after the `ngHide` expression evaluates to a non truthy value and just before the contents are set to visible
*
* @element ANY
* @param {expression} ngHide If the {@link guide/expression expression} is truthy then
@@ -22403,7 +23705,7 @@ var ngStyleDirective = ngDirective(function(scope, element, attr) {
*
*
* @scope
- * @priority 800
+ * @priority 1200
* @param {*} ngSwitch|on expression to match against ng-switch-when .
* On child elements add:
*
@@ -22502,30 +23804,31 @@ var ngSwitchDirective = ['$animate', function($animate) {
var watchExpr = attr.ngSwitch || attr.on,
selectedTranscludes = [],
selectedElements = [],
- previousElements = [],
+ previousLeaveAnimations = [],
selectedScopes = [];
+ var spliceFactory = function(array, index) {
+ return function() { array.splice(index, 1); };
+ };
+
scope.$watch(watchExpr, function ngSwitchWatchAction(value) {
var i, ii;
- for (i = 0, ii = previousElements.length; i < ii; ++i) {
- previousElements[i].remove();
+ for (i = 0, ii = previousLeaveAnimations.length; i < ii; ++i) {
+ $animate.cancel(previousLeaveAnimations[i]);
}
- previousElements.length = 0;
+ previousLeaveAnimations.length = 0;
for (i = 0, ii = selectedScopes.length; i < ii; ++i) {
- var selected = getBlockElements(selectedElements[i].clone);
+ var selected = getBlockNodes(selectedElements[i].clone);
selectedScopes[i].$destroy();
- previousElements[i] = selected;
- $animate.leave(selected, function() {
- previousElements.splice(i, 1);
- });
+ var promise = previousLeaveAnimations[i] = $animate.leave(selected);
+ promise.then(spliceFactory(previousLeaveAnimations, i));
}
selectedElements.length = 0;
selectedScopes.length = 0;
if ((selectedTranscludes = ngSwitchController.cases['!' + value] || ngSwitchController.cases['?'])) {
- scope.$eval(attr.change);
forEach(selectedTranscludes, function(selectedTransclude) {
selectedTransclude.transclude(function(caseElement, selectedScope) {
selectedScopes.push(selectedScope);
@@ -22801,7 +24104,7 @@ var ngOptionsMinErr = minErr('ngOptions');
Select bogus .
- Currently selected: {{ {selected_color:myColor} }}
+ Currently selected: {{ {selected_color:myColor} }}
@@ -22910,6 +24213,7 @@ var selectDirective = ['$compile', '$parse', function($compile, $parse) {
optionsExp = attr.ngOptions,
nullOption = false, // if false, user will not be able to select it (used by ngOptions)
emptyOption,
+ renderScheduled = false,
// we can't just jqLite('') since jqLite is not smart enough
// to create it in and IE barfs otherwise.
optionTemplate = jqLite(document.createElement('option')),
@@ -23091,23 +24395,63 @@ var selectDirective = ['$compile', '$parse', function($compile, $parse) {
value = valueFn(scope, locals);
}
}
- // Update the null option's selected property here so $render cleans it up correctly
- if (optionGroupsCache[0].length > 1) {
- if (optionGroupsCache[0][1].id !== key) {
- optionGroupsCache[0][1].selected = false;
- }
- }
}
ctrl.$setViewValue(value);
+ render();
});
});
ctrl.$render = render;
- // TODO(vojta): can't we optimize this ?
- scope.$watch(render);
+ scope.$watchCollection(valuesFn, scheduleRendering);
+ scope.$watchCollection(function () {
+ var locals = {},
+ values = valuesFn(scope);
+ if (values) {
+ var toDisplay = new Array(values.length);
+ for (var i = 0, ii = values.length; i < ii; i++) {
+ locals[valueName] = values[i];
+ toDisplay[i] = displayFn(scope, locals);
+ }
+ return toDisplay;
+ }
+ }, scheduleRendering);
+
+ if (multiple) {
+ scope.$watchCollection(function() { return ctrl.$modelValue; }, scheduleRendering);
+ }
+
+
+ function getSelectedSet() {
+ var selectedSet = false;
+ if (multiple) {
+ var modelValue = ctrl.$modelValue;
+ if (trackFn && isArray(modelValue)) {
+ selectedSet = new HashMap([]);
+ var locals = {};
+ for (var trackIndex = 0; trackIndex < modelValue.length; trackIndex++) {
+ locals[valueName] = modelValue[trackIndex];
+ selectedSet.put(trackFn(scope, locals), modelValue[trackIndex]);
+ }
+ } else {
+ selectedSet = new HashMap(modelValue);
+ }
+ }
+ return selectedSet;
+ }
+
+
+ function scheduleRendering() {
+ if (!renderScheduled) {
+ scope.$$postDigest(render);
+ renderScheduled = true;
+ }
+ }
+
function render() {
+ renderScheduled = false;
+
// Temporary location for the option groups before we render them
var optionGroups = {'':[]},
optionGroupNames = [''],
@@ -23123,22 +24467,11 @@ var selectDirective = ['$compile', '$parse', function($compile, $parse) {
groupIndex, index,
locals = {},
selected,
- selectedSet = false, // nothing is selected yet
+ selectedSet = getSelectedSet(),
lastElement,
element,
label;
- if (multiple) {
- if (trackFn && isArray(modelValue)) {
- selectedSet = new HashMap([]);
- for (var trackIndex = 0; trackIndex < modelValue.length; trackIndex++) {
- locals[valueName] = modelValue[trackIndex];
- selectedSet.put(trackFn(scope, locals), modelValue[trackIndex]);
- }
- } else {
- selectedSet = new HashMap(modelValue);
- }
- }
// We now build up the list of options we need (we merge later)
for (index = 0; length = keys.length, index < length; index++) {
@@ -23234,7 +24567,7 @@ var selectDirective = ['$compile', '$parse', function($compile, $parse) {
lastElement.val(existingOption.id = option.id);
}
// lastElement.prop('selected') provided by jQuery has side-effects
- if (existingOption.selected !== option.selected) {
+ if (lastElement[0].selected !== option.selected) {
lastElement.prop('selected', (existingOption.selected = option.selected));
if (msie) {
// See #7692
@@ -23257,6 +24590,7 @@ var selectDirective = ['$compile', '$parse', function($compile, $parse) {
(element = optionTemplate.clone())
.val(option.id)
.prop('selected', option.selected)
+ .attr('selected', option.selected)
.text(option.label);
}
@@ -23352,7 +24686,7 @@ var styleDirective = valueFn({
return;
}
- //try to bind to jquery now so that one can write angular.element().read()
+ //try to bind to jquery now so that one can write jqLite(document).ready()
//but we will rebind on bootstrap again.
bindJQuery();
diff --git a/src/vendor/angular/bindonce.js b/src/vendor/angular/bindonce.js
index e08a36776a6..84c2c2f6c05 100644
--- a/src/vendor/angular/bindonce.js
+++ b/src/vendor/angular/bindonce.js
@@ -214,7 +214,7 @@
}
};
- return ctrl;
+ angular.extend(this, ctrl);
}],
link: function (scope, elm, attrs, bindonceController)
@@ -318,4 +318,4 @@
return bindonceDirective;
});
})
-})();
\ No newline at end of file
+})();