Improve this Doc

# Migrating an App to a newer version

Minor version releases in AngularJS introduce several breaking changes that may require changes to your application's source code; for instance from 1.0 to 1.2 and from 1.2 to 1.3.

Although we try to avoid breaking changes, there are some cases where it is unavoidable:

- AngularJS has undergone thorough security reviews to make applications safer by default, which drives many of these changes.
- Several new features, especially animations, would not be possible without a few changes.
- Finally, some outstanding bugs were best fixed by changing an existing API.

## Migrating from 1.5 to 1.6

AngularJS 1.6 fixes numerous bugs and adds new features, both in core and in external modules. In addition, it includes several security and performance improvements in commonly used services, such as `$compile`, `$injector`, `$parse`, `$animate`, and directives, such as `input`, `ngModel` and `select`.

The most notable changes are:

- Aligning jqLite with the latest version of jQuery (3.x).
- Implementing long awaited features, such as support for inputs of type `range` and the ability to bind to any type of values using `ngRepeat` with `select`.
- Disabling (by default) the pre-assignment of bindings on controller instances, which helps with support for native ES6 classes.
- Changing the default `$location` hash-prefix to `'!'`, as the previous empty string default was unconventional and confusing.
- Reporting possibly unhandled promise rejections that would otherwise go unnoticed.

Another major change is the removal of the Expression Sandbox. This should not require changes to your application (and may give it a small performance boost), but we strongly recommend reading the Sandbox Removal Blog Post to understand the implications behind the removal and whether any action is required on your part.

You may also notice that this release comes with a longer-than-usual list of breaking changes. Don't let this dishearten you though, since most of them are pretty minor - often not expected to affect real applications. These breaking changes were necessary in order to:

- Align with breaking changes in jQuery 3.
- Fix bugs that we wouldn't be able to fix otherwise.
- Introduce new features, performance improvements and security fixes.
- Make the behavior of existing features more consistent and predictable.

To give you a heads-up, here is a brief summary of the breaking changes that are expected to have the highest impact. Make sure you look them up in the full list below or check out the corresponding commits for more info.

- $location now uses `'!'` as the default hash-prefix for hash-bang URLs, instead of the empty string. (Details)

- $compile will (by default) not pre-assign bindings on component/directive controller instances. (Details)

- http imposes additional restrictions to JSONP requests for security reasons (see details below):

  - The request URL now needs to be trusted as a resource URL.
  - You can no longer use the `JSON_CALLBACK` placeholder for specifying the query parameter for the callback.

- jqLite is more aligned to jQuery 3, which required the following changes (see details below):
  - Keys passed to `.data()` and `.css()` are now camelCased in the same way as the jQuery methods do.
  - Getting/setting boolean attributes no longer takes the corresponding properties into account.
  - Setting boolean attributes to empty string no longer removes the attribute.
  - Calling `.val()` on a multiple select will always return an array, even if no option is selected.

- input[type=radio] now uses strict comparison (`===`) to determine its "checked" status. (Details)

- The improved support for input[type=range] means that the behaviour of range inputs (when bound to `ngModel`) has changed. (Details)

- ngTransclude now treats whitespace-only transclusion content as empty and uses the fallback content instead. (Details)

- ngAria/ngModel no longer overrides the default `$inEmpty()` method for custom `checkbox`-shaped controls. (Details)

Below is the full list of breaking changes:

- Core:
  - Directives
    - form
    - input[number]
    - input[radio]
    - input[range]
    - ngBind
    - ngModel
    - ngModelOptions
    - ngTransclude
    - select
  - Services
    - $compile
    - $http
    - $interpolate
    - $location
    - $q
  - Miscellaneous
    - jqLite
    - decorator()
- Modules:
  - ngAria
    - $aria
    - ngClick
    - ngModel
  - ngMock
    - $httpBackend
  - ngResource
    - $resource
  - ngRoute
    - $route

### Core: Directives

#### form:

Due to 9e24e7, `FormController` now defines its methods on its prototype, instead of on each instance. As a consequence, `FormController` methods always need to be called in the correct context. For example `$scope.$watch('something', myFormCtrl.$setDirty)` will no longer work, because the `$setDirty` method is passed without any context. The code must now be changed to:

    $scope.$watch('something', function() {
      myFormCtrl.$setDirty();
    })

or you can use `Function.prototype.bind` or `angular.bind`.

#### input[type=number]:

Due to e1da4be, number inputs that use `ngModel` and specify a `step` constraint (via `step`/`ngStep` attributes) will now have a new validator (`step`), which will verify that the current value is valid under the `step` constraint (according to the spec). Previously, the `step` constraint was ignored by `ngModel`, treating values as valid even when there was a step-mismatch.

If you want to restore the previous behavior (use the `step` attribute while disabling step validation), you can overwrite the built-in `step` validator with a custom directive. For example:

    // For all `input` elements...
    .directive('input', function() {
      return {
        restrict: 'E',
        require: '?ngModel',
        link: function (scope, elem, attrs, ngModelCtrl) {
          // ...that are of type "number" and have `ngModel`...
          if ((attrs.type === 'number') && ngModelCtrl) {
            // ...remove the `step` validator.
            delete ngModelCtrl.$validators.step;
          }
        }
      };
    })

#### input[type=radio]:

Due to 5ac7da, the "checked" status of radio inputs is now determined by doing a strict comparison (`===`) between the value of the input and the `ngModelController.$viewValue`. Previously, this was a non-strict comparison (`==`).

This means in the following examples the radio is no longer checked:

    <!-- this.selected = 0 -->
    <input type="radio" ng-model="$ctrl.selected" value="0" />

    <!-- this.selected = 0; this.value = false; -->
    <input type="radio" ng-model="$ctrl.selected" ng-value="$ctrl.value" />

If your code relied on the non-strict comparison, you need to convert the values so that they continue to match with strict comparison.

#### input[type=range]:

Due to 913016 and the built-in support for range inputs, the behavior of such elements when bound to `ngModel` will be different than before:

- Like `input[type=number]`, it requires the model to be a Number, and will set the model to a Number.
- It supports setting the min/max values only via the min/max attributes.
- It follows the browser behavior of never allowing an invalid value. That means, when the browser converts an invalid value (empty: `null`, `undefined`, `false` ..., out of bounds: greater than max, less than min) to a valid value, the input will in turn set the model to this new valid value via `$setViewValue`.
  - This means a range input will never have the required validation error and never have a non-Number model value, once the `ngModel` directive is initialized.
  - This behavior is supported when the model changes and when the min/max attributes change in a way that prompts the browser to update the input value.
- Browsers that do not support `input[type=range]` (IE9) handle the input like a number input (with validation etc).

#### ngBind:

Due to fa80a6, `ngBind` now uses the same logic as `$interpolate` (i.e. `{{ myObject }}`) when binding, which means values other than strings are now transformed as follows:

- `null`/`undefined` become the empty string.
- If an object is not Array, Number or Date and has a custom `toString()` function, use that.
- Otherwise use `JSON.stringify()`.

Previously, `ngBind` would always use `toString()`. The following examples show the difference:

    $scope.myPlainObject = {a: 1, b: 2};
    $scope.myCustomObject = {a: 1, b: 2, toString: function() { return 'a+b'; }};

Plain Object:

    <!-- Before: -->
    <span ng-bind="myPlainObject">[object Object]</span>

    <!-- After: -->
    <span ng-bind="myPlainObject">{'a':1,'b':2}</span>

Object with custom `toString()`:

    <!-- Before: -->
    <span ng-bind="myCustomObject">[object Object]</span>

    <!-- After: -->
    <span ng-bind="myCustomObject">a+b</span>

If you want the output of `toString()`, you can call it manually on the value in `ngBind`:

    <span ng-bind="myObject.toString()">[object Object]</span>

#### ngModel:

Due to 9e24e7, `NgModelController` now defines its methods on its prototype, instead of on each instance. As a consequence, `NgModelController` methods always need to be called in the correct context. For example `$scope.$watch('something', myNgModelCtrl.$setDirty)` will no longer work, because the `$setDirty` method is passed without any context. The code must now be changed to:

    $scope.$watch('something', function() {
      myNgModelCtrl.$setDirty();
    })

Due to 7bc71a, the values returned by synchronous validators are always treated as boolean. Previously, only a literal `false` return value would cause the validation to fail. Now, all falsy values will cause the validation to fail, as one would naturally expect.

Specifically, the values `0`, `null`, `NaN` and `''` (the empty string) used to cause the validation to pass and they will now cause it to fail. The value `undefined` was treated similarly to a pending asynchronous validator, causing the validation to be pending. `undefined` is now also treated as `false`.

If your synchronous validators are always returning boolean values (which should already be the case for most applications anyway), then this change does not affect you. If not, make sure you always return a boolean value (`true/false`) indicating whether the input is valid or not.

#### ngModelOptions:

Due to 296cfc, the programmatic API for `ngModelOptions` has changed. You must now read options via the `ngModelController.$options.getOption(name)` method, rather than accessing the option directly as a property of the `ngModelContoller.$options` object. One benefit of these changes, though, is that the `ngModelControler.$options` property is now guaranteed to be defined so there is no need to check before accessing.

This does not affect the usage in templates and only affects custom directives that might have been reading options for their own purposes. If you were programmatically accessing the options, you need to change your code as follows:

Before:

    var myOption = ngModelController.$options && ngModelController.$options['my-option'];

After:

    var myOption = ngModelController.$options.getOption('my-option');

#### ngTransclude:

Due to 32aa7e, if you only provide whitespace as the transclusion content, it will be assumed to be empty and the fallback content will be used instead. Previously, whitespace only transclusion would be treated as the transclusion being "not empty", which meant that fallback content was not used in that case.

If you actually want whitespace to appear as the transcluded content, then you can force it to be used by adding an HTML comment to the whitespace:

    <my-component>
      <!-- Use this as transclusion content even if empty. -->
    </my-component>

#### select:

Due to f02b70, using `ngValue` on `<option>` elements inside a `<select ng-model>` will automatically set values on them in hash form (used internally by `select` to map to the corresponding model value). I.e. `<option ng-value="myString">` will become `<option ng-value="myString" value="string:myString">`.

This is necessary in order to support binding options with values of any type to selects and should hardly affect any applications, as the values of options are usually not relevant to the application logic. (Although, it may affect tests that check the `value` attribute of `<option>` elements.)

Due to e8c2e1, `<option>` elements will no longer have their value attribute set from their text value when their `<select>` element doesn't have `ngModel` associated with it. Setting the value is only needed for the select directive to match model values and options. If `ngModel` is not present, the `select` directive doesn't need it.

This should not affect many applications as the behavior was undocumented and not part of the public API. It also has no effect on the usual HTML5 behavior that sets the select value to the option text if the option does not provide a value attribute.

### Core: Services

#### $compile:

Due to bcd0d4, pre-assigning bindings on component/directive controller instances is disabled by default, which means that they will no longer be available inside the constructors. It is still possible to turn it back on, which should help during the migration. Pre-assigning bindings has been deprecated and will be removed in a future version, so we strongly recommend migrating your applications to not rely on it as soon as possible.

Initialization logic that relies on bindings being present should be put in the controller's `$onInit()` method, which is guaranteed to always be called after the bindings have been assigned.

Before:

    .component('myComponent', {
      bindings: {value: '<'},
      controller: function() {
        // `this.value` might or might not be initialized,
        // based on whether `preAssignBindingsEnabled` is true or false.
        this.doubleValue = this.value * 2;
      }
    })

After:

    .component('myComponent', {
      bindings: {value: '<'},
      controller: function() {
        this.$onInit = function() {
          // `this.value` will always be initialized,
          // regardless of the value of `preAssignBindingsEnabled`.
          this.doubleValue = this.value * 2;
        };
      }
    })

If you need to, you can re-enabled this feature with the following configuration block:

    .config(function($compileProvider) {
      $compileProvider.preAssignBindingsEnabled(true);
    })

Note: This will re-enable the feature for the whole application, so only do it if you are in control of the whole application. If you are writing a library, you need to change your code as shown above. Furthermore, if your library also targets versions before 1.5 (which do not support the `$onInit()` lifecycle hook), you may need to manually call `$onInit()` from your constructor:

    .directive('myComponent', function() {
      return {
        scope: {value: '<'},
        controller: function() {
          // Put initialization logic inside `$onInit()`
          // to make sure bindings have been initialized.
          this.$onInit = function() {
            this.doubleValue = this.value * 2;
          };

          // Prior to v1.5, we need to call `$onInit()` manually.
          // (Bindings will always be pre-assigned in these versions.)
          if (angular.version.major === 1 && angular.version.minor < 5) {
            this.$onInit();
          }
        }
      };
    })

Due to 04cad4, `link[href]` attributes are now protected via `$sce`, which prevents interpolated values that fail the `RESOURCE_URL` context tests from being used in interpolation. For example if the application is running at `https://docs.angularjs.org` then the following will fail:

    <link href="{{ 'http://mydomain.org/unsafe.css' }}" rel="stylesheet" />

By default, only URLs with the same domain and protocol as the application document are considered safe in the `RESOURCE_URL` context. To use URLs from other domains and/or protocols, you may either whitelist them or wrap them into a trusted value by calling `$sce.trustAsResourceUrl(url)`.

Due to 97bbf8, whitespace in attributes is no longer trimmed automatically. This includes leading and trailing whitespace, and attributes that are purely whitespace. To migrate, attributes that require trimming must now be trimmed manually. A common case where stray whitespace can cause problems is when attribute values are compared, for example in `$observe`.

Before:

    $attrs.$observe('myAttr', function(newVal) {
      if (newVal === 'some value') ...
    });

After:

    $attrs.$observe('myAttr', function(newVal) {
      if (newVal.trim() === 'some value') ...
    });

Note that `$parse` trims expressions automatically, so attributes with expressions (e.g. directive bindings) should not be affected by this change.

Due to 13c252, on IE11 only, consecutive text nodes will always get merged. Previously, they would not get merged if they had no parent. The new behavior, which fixes an IE11 bug affecting interpolation under certain circumstances, might in some edge-cases have unexpected side effects that you should be aware of. Please, check the commit message for more details.

Due to b89c21, using interpolation in any `on*` event attribute (e.g. `<button onclick="{{myVar}}">`) will now throw the `nodomevents` error at compile time. Previously, the `nodomevents` was thrown at link time. This change is not expected to affect any applications, as it is related to incorrect API use that should not make it to production apps in the first place.

#### $http:

Due to fb6634, you can no longer use the `JSON_CALLBACK` placeholder in your JSONP requests. Instead you must provide the name of the query parameter that will pass the callback via the `jsonpCallbackParam` property of the config object, or app-wide via the `$http.defaults.jsonpCallbackParam` property, which is `"callback"` by default.

Before:

    $http.json('trusted/url?callback=JSON_CALLBACK');
    $http.json('other/trusted/url', {params: {cb: 'JSON_CALLBACK'}});

After:

    $http.json('trusted/url');
    $http.json('other/trusted/url', {jsonpCallbackParam: 'cb'});

Due to 6476af, all JSONP requests now require the URL to be trusted as a resource URL. There are two approaches to trust a URL:

1. Whitelisting with the `$sceDelegateProvider.resourceUrlWhitelist()` method. You configure this list in a module configuration block:

       appModule.config(['$sceDelegateProvider', function($sceDelegateProvider) {
         $sceDelegateProvider.resourceUrlWhitelist([
           // Allow same origin resource loads.
           'self',
           // Allow JSONP calls that match this pattern
           'https://some.dataserver.com/**.jsonp?**'
         ]);
       }]);

2. Explicitly trusting the URL via the `$sce.trustAsResourceUrl(url)` method. You can pass a trusted object instead of a string as a URL to the `$http` service:

       var promise = $http.jsonp($sce.trustAsResourceUrl(url));

Due to 4f6f2b, HTTP requests now update the outstanding request count synchronously. Previously, the request count would not have been updated until the request to the server was actually in flight. Now the request count is updated before any async interceptor is called.

The new behavior will also allow end-2-end tests to more correctly detect when AngularJS is stable, but there is a chance it may change the observed behaviour in cases where an async request interceptor is being used.

Due to b54a39, `$http`'s deprecated custom callback methods - `success()` and `error()` - have been removed. You can use the standard `then()`/`catch()` promise methods instead, but note that the method signatures and return values are different.

`success(fn)` can be replaced with `then(fn)`, and `error(fn)` can be replaced with either `then(null, fn)` or `catch(fn)`.

Before:

    $http(...).
    success(function onSuccess(data, status, headers, config) {
      // Handle success
      ...
    }).
    error(function onError(data, status, headers, config) {
      // Handle error
      ...
    });

After:

    $http(...).
      then(function onSuccess(response) {
        // Handle success
        var data = response.data;
        var status = response.status;
        var statusText = response.statusText;
        var headers = response.headers;
        var config = response.config;
        ...
      }, function onError(response) {
        // Handle error
        var data = response.data;
        var status = response.status;
        var statusText = response.statusText;
        var headers = response.headers;
        var config = response.config;
        ...
      });

    // or

    $http(...).
      then(function onSuccess(response) {
        // Handle success
        var data = response.data;
        var status = response.status;
        var statusText = response.statusText;
        var headers = response.headers;
        var config = response.config;
        ...
      }).
      catch(function onError(response) {
        // Handle error
        var data = response.data;
        var status = response.status;
        var statusText = response.statusText;
        var headers = response.headers;
        var config = response.config;
        ...
      });

Note: There is a subtle difference between the variations showed above. When using `$http(...).success(onSuccess).error(onError)` or `$http(...).then(onSuccess, onError)`, the `onError()` callback will only handle errors/rejections produced by the `$http()` call. If the `onSuccess()` callback produces an error/rejection, it won't be handled by `onError()` and might go unnoticed. In contrast, when using `$http(...).then(onSuccess).catch(onError)`, `onError()` will handle errors/rejections produced by both `$http()` and `onSuccess()`.

#### $interpolate:

Due to a5fd2e, when converting values to strings, interpolation now uses a custom `toString()` function on objects that are not Number, Array or Date (custom means that the `toString` function is not the same as `Object.prototype.toString`). Otherwise, interpolation uses `JSON.stringify()` as usual. If an object has a custom `toString()` function, but you still want the output of `JSON.stringify()`, you will need to manually convert to JSON (as shown below).

Before:

    <span>{{ myObject }}</span>

After:

    <span>{{ myObject | json }}</span>

#### $location:

Due to aa077e8, the default hash-prefix used for `$location` hash-bang URLs has changed from the empty string (`''`) to the bang (`'!'`). If your application does not use HTML5 mode or is being run on browsers that do not support HTML5 mode, and you have not specified your own hash-prefix then client side URLs will now contain a `!` prefix. For example, rather than `mydomain.com/#/a/b/c` the URL will become `mydomain.com/#!/a/b/c`.

If you actually want to have no hash-prefix, then you can restore the previous behavior by adding a configuration block to you application:

    appModule.config(['$locationProvider', function($locationProvider) {
      $locationProvider.hashPrefix('');
    }]);

#### $q:

Due to e13eea, an error thrown from a promise's `onFulfilled` or `onRejection` handlers is treated exactly the same as a regular rejection. Previously, it would also be passed to the `$exceptionHandler()` (in addition to rejecting the promise with the error as reason).

The new behavior applies to all services/controllers/filters etc that rely on `$q` (including built-in services, such as `$http` and `$route`). For example, `$http`'s `transformRequest/Response` functions or a route's `redirectTo` function as well as functions specified in a route's `resolve` object, will no longer result in a call to `$exceptionHandler()` if they throw an error. Other than that, everything will continue to behave in the same way; i.e. the promises will be rejected, route transition will be cancelled, `$routeChangeError` events will be broadcasted etc.

Due to c9dffde, possibly unhandled rejected promises will be logged to the `$exceptionHandler`. Normally, that means that an error will be logged to the console, but in tests `$exceptionHandler` will (by default) re-throw any exceptions. Tests that are affected by this change (e.g. tests that depend on specific order or number of messages in `$exceptionHandler`) will need to handle rejected promises.

### Core: Miscellaneous

#### jqLite:

Due to fc0c11, jqLite will camelCase the keys passed to the `.data()` method, in the same way as jQuery 3+ does; i.e. single hyphens followed by a lowercase letter will be converted to an uppercase letter. Previously, keys passed to `.data()` were left untouched.

For example, with this change, the keys `a-b` and `aB` will now represent the same data piece; writing to one of them will also be reflected when reading the value of the other one.

To migrate, you need to update your code as shown in the following examples:

Before:

    /* 1 */
    elem.data('my-key', 2);
    elem.data('myKey', 3);

    /* 2 */
    elem.data('foo-bar', 42);
    elem.data()['foo-bar']; // 42
    elem.data()['fooBar']; // undefined

    /* 3 */
    elem.data()['foo-bar'] = 1;
    elem.data()['fooBar'] = 2;
    elem.data('foo-bar'); // 1

After:

    /* 1 */
    // Rename one of the keys as they would now map to the same data slot.
    elem.data('my-key', 2);
    elem.data('my-key2', 3);

    /* 2 */
    elem.data('foo-bar', 42);
    elem.data()['foo-bar']; // undefined
    elem.data()['fooBar']; // 42

    /* 3 */
    elem.data()['foo-bar'] = 1;
    elem.data()['fooBar'] = 2;
    elem.data('foo-bar'); // 2

Due to 73050c, the way jqLite camelCases keys passed to `.css()` is aligned with jQuery. Previously, when using AngularJS without jQuery, `.css()` would camelCase keys more aggressively. Now, only a single hyphen followed by a lowercase letter is getting transformed. This change also affects other APIs that rely on the `.css()` method, such as `ngStyle`.

If you are using AngularJS with jQuery, your application is not affected by this change. If you are not using jQuery, then you need to update your code as shown in the following examples:

Before:

    <!-- HTML -->

    <!-- All five versions used to be equivalent. -->
    <div ng-style={background_color: 'blue'}></div>
    <div ng-style={'background:color': 'blue'}></div>
    <div ng-style={'background-color': 'blue'}></div>
    <div ng-style={'background--color': 'blue'}></div>
    <div ng-style={backgroundColor: 'blue'}></div>

    // JS

    // All five versions used to be equivalent.
    elem.css('background_color', 'blue');
    elem.css('background:color', 'blue');
    elem.css('background-color', 'blue');
    elem.css('background--color', 'blue');
    elem.css('backgroundColor', 'blue');

    // All five versions used to be equivalent.
    var bgColor = elem.css('background_color');
    var bgColor = elem.css('background:color');
    var bgColor = elem.css('background-color');
    var bgColor = elem.css('background--color');
    var bgColor = elem.css('backgroundColor');

After:

    <!-- HTML -->

    <!-- Only these two versions are still equivalent to the five shown above. -->
    <div ng-style={'background-color': 'blue'}></div>
    <div ng-style={backgroundColor: 'blue'}></div>

    // JS

    // Only these two versions are still equivalent to the five shown above.
    elem.css('background-color', 'blue');
    elem.css('backgroundColor', 'blue');

    // Only these two versions are still equivalent to the five shown above.
    var bgColor = elem.css('background-color');
    var bgColor = elem.css('backgroundColor');

Due to 7ceb5f, getting/setting boolean attributes will no longer take the corresponding properties into account. Previously, all boolean attributes were reflected into the corresponding property when calling a setter and from the corresponding property when calling a getter, even on elements that don't treat those attributes in a special way. Now AngularJS doesn't do it by itself, but relies on browsers to know when to reflect the property. Note that this browser-level conversion differs between browsers; if you need to dynamically change the state of an element, you should modify the property, not the attribute. See https://jquery.com/upgrade-guide/1.9/#attr-versus-prop- for a more detailed description about a related change in jQuery 1.9.

This change aligns jqLite with jQuery 3. To migrate the code follow the example below:

Before:

    /* CSS */

    input[checked="checked"] { ... }

    // JS

    elem1.attr('checked', 'checked');
    elem2.attr('checked', false);

After:

    /* CSS */

    input:checked { ... }

    // JS

    elem1.prop('checked', true);
    elem2.prop('checked', false);

Due to 3faf45, calling `.attr(attrName, '')` (with `attrName` being a boolean attribute) will no longer remove the attribute, but set it to its lowercase name as happens for every non-empty string. Previously, calling `.attr(attrName, '')` would remove the boolean attribute.

If you want to remove a boolean attribute now, you have to call `.attr()` with `false` or `null`. E.g.: `.attr(attrName, false)`

Due to 4e3624, calling `.attr(attrName, null)` will remove the attribute. Previously, it would set the `attrName` attribute value to the string `'null'`. If you want to set the attribute value to the string `'null'`, you have to explicitly call `.attr(attrName, 'null')`.

Due to d882fd, calling the `.val()` getter on a jqLite element representing a `<select multiple>` element with no options chosen will return an empty array. Previously, it would return `null`. If you relied on the returned value being `null` or falsy, you need to change your code to check for a length of 0 instead:

Before:

    <select multiple>...</select>

    var value = $element.val();
    if (value) { /* do something */ }

After:

    <select multiple>...</select>

    var value = $element.val();
    if (value.length > 0) { /* do something */ }

#### decorator():

Due to 6a2ebd, `module.decorator` declarations are now processed as part of the `module.config` queue and may result in providers being decorated in a different order if `module.config` blocks are also used to decorate providers via `$provide.decorator`.

For example, consider the following declaration order in which `'theFactory'` is decorated by both a `module.decorator` and a `$provide.decorator`:

    angular
    .module('theApp', [])
    .factory('theFactory', theFactoryFn)
    .config(function($provide) {
      $provide.decorator('theFactory', provideDecoratorFn);
    })
    .decorator('theFactory', moduleDecoratorFn);

Before this change, `'theFactory'` provider would be decorated in the following order:

1. `moduleDecoratorFn`
2. `provideDecoratorFn`

After this change, the order in which `'theFactory'` is decorated will be different, because now `module.decorator` declarations are processed in the same order as `module.config` declarations:

1. `provideDecoratorFn`
2. `moduleDecoratorFn`

### ngAria

#### $aria:

Due to ad41ba, if you were explicitly setting the value of the `bindKeypress` flag, you need to change your code to use `bindKeydown` instead.

Before: `$ariaProvider.config({bindKeypress: xyz})`
After: `$ariaProvider.config({bindKeydown: xyz})`

#### ngClick:

Due to ad41ba, `ngClick` will respond to the `keydown` keyboard event, instead of the `keypress`. Also, if the element already has any of the `ngKeydown`/`ngKeyup`/`ngKeypress` directives, `ngAria` will not bind to the `keydown` event, since it assumes that the developer has already taken care of keyboard interaction for that element. Although it is not expected to affect many applications, it might be desirable to keep the previous behavior of binding to the `keypress` event instead of the `keydown`. In that case, you need to manually use the `ngKeypress` directive (in addition to `ngClick`).

Before:

    <div ng-click="onClick()">
      I respond to `click` and `keypress` (not `keydown`)
    </div>

After:

    <div ng-click="onClick()" ng-keypress="onClick()">
      I respond to `click` and `keypress` (not `keydown`)
    </div>
    <!-- OR -->
    <div ng-click="onClick()">
      I respond to `click` and `keydown` (not `keypress`)
    </div>

Finally, it is possible that this change affects your unit or end-to-end tests. If you are currently expecting your custom buttons to automatically respond to the `keypress` event (due to `ngAria`), you need to change the tests to trigger `keydown` events instead.

#### ngModel:

Due to 975a61, custom `checkbox`-shaped controls (e.g. checkboxes, menuitemcheckboxes), no longer have a custom `$isEmpty()` method on their `NgModelController` that checks for `value === false`. Unless overwritten, the default `$isEmpty()` method will be used, which treats `undefined`, `null`, `NaN` and `''` as "empty".

Note: The `$isEmpty()` method is used to determine if the checkbox is checked ("not empty" means "checked"). Thus it can indirectly affect other things, such as the control's validity with respect to the `required` validator (e.g. "empty" + "required" --> "invalid").

Before:

    var template = '<my-checkbox role="checkbox" ng-model="value"></my-checkbox>';
    var customCheckbox = $compile(template)(scope);
    var ctrl = customCheckbox.controller('ngModel');

    scope.$apply('value = false');
    console.log(ctrl.$isEmpty());   //--> true

    scope.$apply('value = true');
    console.log(ctrl.$isEmpty());   //--> false

    scope.$apply('value = undefined'/* or null or NaN or '' */);
    console.log(ctrl.$isEmpty());   //--> false

After:

    var template = '<my-checkbox role="checkbox" ng-model="value"></my-checkbox>';
    var customCheckbox = $compile(template)(scope);
    var ctrl = customCheckbox.controller('ngModel');

    scope.$apply('value = false');
    console.log(ctrl.$isEmpty());   //--> false

    scope.$apply('value = true');
    console.log(ctrl.$isEmpty());   //--> false

    scope.$apply('value = undefined'/* or null or NaN or '' */);
    console.log(ctrl.$isEmpty());   //--> true

If you want to have a custom `$isEmpty()` method, you need to overwrite the default. For example:

    .directive('myCheckbox', function myCheckboxDirective() {
      return {
        require: 'ngModel',
        link: function myCheckboxPostLink(scope, elem, attrs, ngModelCtrl) {
          ngModelCtrl.$isEmpty = function myCheckboxIsEmpty(value) {
            return !value;   // Any falsy value means "empty"

            // Or to restore the previous behavior:
            // return value === false;
          };
        }
      };
    })

Due to 9978de1, the `role` attribute will no longer be added to native control elements (textarea, button, select, summary, details, a, and input). Previously, `role` was not added to `input`, but all others in the list. This should not affect accessibility, because native inputs are accessible by default, but it might affect applications that relied on the `role` attribute being present (e.g. for styling or as directive attributes).

### ngMock

#### $httpBackend:

Due to 267ee9, calling `$httpBackend.verifyNoOutstandingRequest()` will trigger a digest. This will ensure that requests fired asynchronously will also be detected (without the need to manually trigger a digest). This is not expected to affect the majority of test-suites. Most of the time, a digest is (directly or indirectly) triggered anyway, before calling `verifyNoOutstandingRequest()`. In the unlikely case that a test needs to verify the timing of a request with respect to the digest cycle, you should rely on other means, such as mocking and/or spying.

Due to 7551b8, it is no longer valid to explicitly pass `undefined` as the `url` argument to any of the `$httpBackend.when...()` and `$httpBackend.expect...()` methods. While this argument is optional, it must have a defined value if provided. Previously passing an explicit `undefined` value was ignored, but this lead to invalid tests passing unexpectedly.

### ngResource

#### $resource:

Due to acb545, all own properties of the `params` object that are not used to replace URL params, will be passed to `$http` as `config.params` (to be used as query parameters in the URL). Previously, parameters where omitted if `Object.prototype` had a property with the same name. E.g.:

Before:

    var Foo = $resource('/foo/:id');
    Foo.get({id: 42, bar: 'baz', toString: 'hmm'});
        // URL: /foo/42?bar=baz
        // Note that `toString` is _not_ included in the query,
        // because `Object.prototype.toString` is defined :(

After:

    var Foo = $resource('/foo/:id');
    Foo.get({id: 42, bar: 'baz', toString: 'hmm'});
        // URL: /foo/42?bar=baz&toString=hmm
        // Note that `toString` _is_ included in the query, as expected :)

Due to 2456ab, semicolon has been added to the list of delimiters that are not encoded in URL params. Although it shouldn't matter in practice (since both the encoded and the unencoded `;` character would be interpreted identically by the server), this change could break some tests: For example, where `$httpBackend` was set up to expect an encoded `;` character, but the request is made to the URL with an unencoded `;` character.

### ngRoute

#### $route:

Due to c13c66, `$route` (and its dependencies; e.g. `$location`) will - by default - be instantiated early on. Previously, in cases where `ngView` was loaded asynchronously, `$route` (and its dependencies) might also have been instantiated asynchronously.

Although this is not expected to have unwanted side-effects in normal application behavior, it may affect your unit tests: When testing a module that (directly or indirectly) depends on `ngRoute`, a request will be made for the default route's template. If not properly "trained", `$httpBackend` will complain about this unexpected request. You can restore the previous behavior (and avoid unexpected requests in tests), by using `$routeProvider.eagerInstantiationEnabled(false)`.

Due to e98656, if a `redirectTo` function throws an Error, a `$routeChangeError` event will be fired. Previously, execution would be aborted without firing a `$routeChangeError` event.

Due to 7f4b35, the `$route` service will no longer instantiate controllers nor call `resolve` or `template`/`templateUrl` functions for routes that successfully `redirectTo` other routes.

## Migrating from 1.4 to 1.5

AngularJS 1.5 takes a big step towards preparing developers for a smoother transition to Angular in the future. Architecting your applications using components, multi-slot transclusion, one-way bindings in isolate scopes, using lifecycle hooks in directive controllers and relying on native ES6 features (such as classes and arrow functions) are now all possible with AngularJS 1.5.

This release includes numerous bug and security fixes, as well as performance improvements to core services, directives, filters and helper functions. Existing applications can start enjoying the benefits of such changes in `$compile`, `$parse`, `$animate`, `$animateCss`, `$sanitize`, `ngOptions`, `currencyFilter`, `numberFilter`, `copy()` (to name but a few) without any change in code.

New features have been added to more than a dozen services, directives and filters across 8 modules. Among them, a few stand out:

- `angular.component()`: Introducing "components", a special sort of directive that are easy to configure and promote best practices (plus can bring AngularJS applications closer to Angular's style of architecture).
- Multi-slot transclusion: Enabling the design of more powerful and complex UI elements with a much simpler configuration and reduced boilerplate.
- `$onInit` lifecycle hook: Introducing a new lifecycle hook for directive controllers, called after all required controllers have been constructed. This enables access to required controllers from a directive's controller, without having to rely on the linking function.
- `ngAnimateSwap`: A new directive in `ngAnimate`, making it super easy to create rotating banner-like components.
- Testing helpers: New helper functions in `ngMock`, simplifying testing for animations, component controllers and routing.

Also, notable is the improved support for ES6 features, such as classes and arrow functions. These features are now more reliably detected and correctly handled within the core.

All this goodness doesn't come without a price, though. Below is a list of breaking changes (grouped by module) that need to be taken into account while migrating from 1.4. Fortunately, the majority of them should have a pretty low impact on most applications.

### Core

We tried to keep the breaking changes inside the core components to a bare minimum. Still, a few of them were unavoidable.

#### Services (`$parse`)

Due to 0ea53503, a new special property, `$locals`, will be available for accessing the locals from an expression. This is a breaking change, only if a `$locals` property does already exist (and needs to be referenced) either on the `scope` or on the `locals` object. Your expressions should be changed to access such existing properties as `this.$locals` and `$locals.$locals` respectively.

#### Directives (`ngOptions`)

A fair amount of work has been put into the `ngOptions` directive, fixing bugs and corner-cases and neutralizing browser quirks. A couple of breaking changes were made in the process:

Due to b71d7c3f, falsy values (`''`, `0`, `false` and `null`) are properly recognized as option group identifiers for options passed to `ngOptions`. Previously, all of these values were ignored and the option was not assigned to any group. `undefined` is still interpreted as "no group". If you have options with falsy group indentifiers that should still not be assigned to any group, then you must filter the values before passing them to `ngOptions`, converting falsy values to `undefined`.

Due to ded25187, `ngOptions` now explicitly requires `ngModel` on the same element, thus an error will be thrown if `ngModel` is not found. Previously, `ngOptions` would silently fail, which could lead to hard-to-debug errors. This is not expected to have any significant impact on applications, since `ngOptions` didn't work without `ngModel` before either. The main difference is that now it will fail with a more informative error message.

#### Filters (`orderBy`)

Due to 2a85a634, passing a non-array-like value (other than `undefined` or `null`) through the `orderBy` filter will throw an error. Previously, the input was returned unchanged, which could lead to hard-to-spot bugs and was not consistent with other filters (e.g. `filter`). Objects considered array-like include: arrays, array subclasses, strings, NodeLists, jqLite/jQuery collections

#### Helper Functions:

The `angular.lowercase` and `angular.uppercase` functions have been deprecated and will be removed in version 1.7.0. It is recommended to use String.prototype.toLowerCase and String.prototype.toUpperCase functions instead.

### ngAria

Due to d06431e, the `ngAria`-enhanced directives (e.g. `ngModel`, `ngDisabled` etc) will not apply ARIA attributes to native inputs, unless necessary. Previously, ARIA attributes were always applied to native inputs, despite this being unnecessary in most cases. In the context of `ngAria`, elements considered "native inputs" include: `<a>`, `<button>`, `<details>`, `<input>`, `<select>`, `<summary>`, `<textarea>`

This change will not affect the accessibility of your applications (since native inputs are accessible by default), but if you relied on ARIA attributes being present on native inputs (for whatever reason), you'll have to add and update them manually.

Additionally, the `aria-multiline` attribute, which was previously added to elements with a `type` or `role` of `textbox`, will not be added anymore, since there is no way `ngAria` can tell if the textbox element is multiline or not. If you relied on `aria-multiline="true"` being automatically added by `ngAria`, you need to apply it yourself. E.g. change your code from `<div role="textbox" ng-model="..." ...>` to `<div role="textbox" ng-model="..." ... aria-multiline="true">`.

### ngMessages (`ngMessage`)

Due to 4971ef12, the `ngMessage` directive is now compiled with a priority of 1, which means directives on the same element as `ngMessage` with a priority lower than 1 will be applied when `ngMessage` calls its `$transclude` function. Previously, they were applied during the initial compile phase and were passed the comment element created by the transclusion of `ngMessage`. If you have custom directives that relied on the previous behavior, you need to give them a priority of 1 or greater.

### ngResource (`$resource`)

The `$resource` service underwent a minor internal refactoring to finally solve a long-standing bug preventing requests from being cancelled using promises. Due to the nature of `$resource`'s configuration, it was not possible to follow the `$http` convention. A new `$cancelRequest()` method was introduced instead.

Due to 98528be3, using a promise as `timeout` in `$resource` is no longer supported and will log a warning. This is hardly expected to affect the behavior of your application, since a promise as `timeout` didn't work before either, but it will now warn you explicitly when trying to pass one. If you need to be able to cancel pending requests, you can now use the new `$cancelRequest()` that will be available on `$resource` instances.

### ngRoute (`ngView`)

Due to 983b0598, a new property will be available on the scope of the route, allowing easy access to the route's resolved values from the view's template. The default name for this property is `$resolve`. This is a breaking change, only if a `$resolve` property is already available on the scope, in which case the existing property will be hidden or overwritten. To fix this, you should choose a custom name for this property, that does not collide with other properties on the scope, by specifying the `resolveAs` property on the route.

### ngSanitize (`$sanitize`, `linky`)

The HTML sanitizer has been re-implemented using inert documents, increasing security, fixing some corner-cases that were difficult to handle and reducing its size by about 20% (in terms of loc). In order to make it more secure by default, a couple of breaking changes have been introduced:

Due to 181fc567, SVG support in `$sanitize` is now an opt-in feature (i.e. disabled by default), as it could make an application vulnerable to click-hijacking attacks. If your application relies on it, you can still turn it on with `$sanitizeProvider.enableSvg(true)`, but you extra precautions need to be taken in order to keep your application secure. Read the documentation for more information about the dangers and ways to mitigate them.

Due to 7a668cdd, the `$sanitize` service will now remove instances of the `<use>` tag from the content passed to it. This element is used to import external SVG resources, which is a security risk as the `$sanitize` service does not have access to the resource in order to sanitize it.

Similarly, due to 234053fc, the `$sanitize` service will now also remove instances of the `usemap` attribute from any elements passed to it. This attribute is used to reference another element by `name` or `id`. Since the `name` and `id` attributes are already blacklisted, a sanitized `usemap` attribute could only reference unsanitized content, which is a security risk.

Due to 98c2db7f, passing a non-string value (other than `undefined` or `null`) through the `linky` filter will throw an error. This is not expected to have any significant impact on applications, since the input was always assumed to be of type 'string', so passing non-string values never worked correctly anyway. The main difference is that now it will fail faster and with a more informative error message.

### ngTouch (`ngClick`)

Due to 0dfc1dfe, the `ngClick` override directive from the `ngTouch` module is deprecated and disabled by default. This means that on touch-based devices, users might now experience a 300ms delay before a click event is fired.

If you rely on this directive, you can still enable it using `$touchProvider.ngClickOverrideEnabled()`:

    angular.module('myApp').config(function($touchProvider) {
      $touchProvider.ngClickOverrideEnabled(true);
    });

Going forward, we recommend using FastClick or perhaps one of the AngularJS 3rd party touch-related modules that provide similar functionality.

Also note that modern browsers already remove the 300ms delay under some circumstances:

- Chrome and Firefox for Android remove the 300ms delay when the well-known `<meta name="viewport" content="width=device-width">` is set.
- Internet Explorer removes the delay, when the `touch-action` css property is set to `none` or `manipulation`.
- Since iOS 8, Safari removes the delay on so-called "slow taps".

For more info on the topic, you can take a look at this article by Telerik.

Note: This change does not affect the `ngSwipe` directive.

## Migrating from 1.3 to 1.4

AngularJS 1.4 fixes major animation issues and introduces a new API for `ngCookies`. Further, there are changes to `ngMessages`, `$compile`, `ngRepeat`, `ngOptions`, `ngPattern`, `pattern`, and some fixes to core filters: `limitTo` and `filter`.

The reason for the ngAnimate refactor was to fix timing issues and to expose new APIs to allow for developers to construct more versatile animations. We now have access to `$animateCss` and the many timing-oriented bugs were fixed which results in smoother animations. If animation is something of interest, then please read over the breaking changes below for animations when `ngAnimate` is used.

`ngMessages` has been upgraded to allow for dynamic message resolution. This handy feature allows for developers to render error messages with ngMessages that are listed with a directive such as ngRepeat. A great usecase for this involves pulling error message data from a server and then displaying that data via the mechanics of ngMessages. Be sure to read the breaking change involved with `ngMessagesInclude` to upgrade your template code.

Other changes, such as the ordering of elements with ngRepeat and ngOptions and the way ngPattern and pattern directives validate the regex, may also affect the behavior of your application. And be sure to also read up on the changes to `$cookies`. The migration jump from 1.3 to 1.4 should be relatively straightforward otherwise.

### Animation (`ngAnimate`)

Animations in 1.4 have been refactored internally, but the API has stayed much the same. There are, however, some breaking changes that need to be addressed when upgrading to 1.4.

Due to c8700f04, JavaScript and CSS animations can no longer be run in parallel. With earlier versions of ngAnimate, both CSS and JS animations would be run together when multiple animations were detected. This feature has been removed, however, the same effect, with even more possibilities, can be achieved by injecting `$animateCss` into a JavaScript-defined animation and creating custom CSS-based animations from there.

By using `$animateCss` inside of a JavaScript animation in AngularJS 1.4, we can trigger custom CSS-based animations directly from our JavaScript code.

    ngModule.animation('.slide-animation', ['$animateCss', function($animateCss) {
      return {
        enter: function(element, doneFn) {
          // this will trigger a `.ng-enter` and `.ng-enter-active` CSS animation
          var animation = $animateCss(element, {
            event: 'enter'
            // any other CSS-related properties
            //   addClass: 'some-class',
            //   removeClass: 'some-other-class',
            //   from: {},
            //   to: {}
          });

          // make sure to read the ngAnimate docs to understand how this works
          animation.start().done(doneFn);
        }
      }
    }]);

Click here to learn how to use $animateCss in your animation code

Due to c8700f04, animation-related callbacks are now fired on `$animate.on` instead of directly being on the element.

    // < 1.4
    element.on('$animate:before', function(e, data) {
      if (data.event === 'enter') { ... }
    });
    element.off('$animate:before', fn);

    // 1.4+
    $animate.on('enter', element, function(data) {
      //...
    });
    $animate.off('enter', element, fn);

Due to c8700f04, the function params for `$animate.enabled()` when an element is used are now flipped. This fix allows the function to act as a getter when a single element param is provided.

    // < 1.4
    $animate.enabled(false, element);

    // 1.4+
    $animate.enabled(element, false);

Due to c8700f04, in addition to disabling the children of the element, `$animate.enabled(element, false)` will now also disable animations on the element itself.

Due to c8700f04, there is no need to call `$scope.$apply` or `$scope.$digest` inside of a animation promise callback anymore since the promise is resolved within a digest automatically. (Not to worry, any extra digests will not be run unless the promise is used.)

    // < 1.4
    $animate.enter(element).then(function() {
      $scope.$apply(function() {
        $scope.explode = true;
      });
    });

    // 1.4+
    $animate.enter(element).then(function() {
      $scope.explode = true;
    });

Due to c8700f04, when an enter, leave or move animation is triggered then it will always end any pending or active parent class based animations (animations triggered via ngClass) in order to ensure that any CSS styles are resolved in time.

### Forms (`ngMessages`, `ngOptions`, `select`, `ngPattern` and `pattern`, `form`)

#### ngMessages

The ngMessages module has also been subject to an internal refactor to allow it to be more flexible and compatible with dynamic message data. The `ngMessage` directive now supports a new attribute called `ng-message-exp` which will evaluate an expression and will keep track of that expression as it changes in order to re-evaluate the listed messages.

Click here to learn more about dynamic ng-messages

There is only one breaking change. Please consider the following when including remote message templates via `ng-messages-include`:

Due to c9a4421f, the `ngMessagesInclude` attribute has now been removed and cannot be used in the same element containing the `ngMessages` directive. Instead, `ngMessagesInclude` is to be used on its own element inline with other inline messages situated as children within the `ngMessages` container directive.

    <!-- AngularJS 1.3.x -->
    <div ng-messages="model.$error" ng-messages-include="remote.html">
      <div ng-message="required">Your message is required</div>
    </div>

    <!-- AngularJS 1.4.x -->
    <div ng-messages="model.$error">
      <div ng-message="required">Your message is required</div>
      <div ng-messages-include="remote.html"></div>
    </div>

Depending on where the `ngMessagesInclude` directive is placed it will be prioritized inline with the other messages before and after it.

Also due to c9a4421f, it is no longer possible to use interpolation inside the `ngMessages` attribute expression. This technique is generally not recommended, and can easily break when a directive implementation changes. In cases where a simple expression is not possible, you can delegate accessing the object to a function:

    <div ng-messages="ctrl.form['field_{{$index}}'].$error">...</div>

would become

    <div ng-messages="ctrl.getMessages($index)">...</div>

where `ctrl.getMessages()`

    ctrl.getMessages = function($index) {
      return ctrl.form['field_' + $index].$error;
    }

#### ngOptions

The `ngOptions` directive has also been refactored and as a result some long-standing bugs have been fixed. The breaking changes are comparatively minor and should not affect most applications.

Due to 7fda214c, when `ngOptions` renders the option values within the DOM, the resulting HTML code is different. Normally this should not affect your application at all, however, if your code relies on inspecting the value property of `<option>` elements (that `ngOptions` generates) then be sure to read the details.

Due to 7fda214c, when iterating over an object's properties using the `(key, value) in obj` syntax the order of the elements used to be sorted alphabetically. This was an artificial attempt to create a deterministic ordering since browsers don't guarantee the order. But in practice this is not what people want and so this change iterates over properties in the order they are returned by Object.keys(obj), which is almost always the order in which the properties were defined.

Also due to 7fda214c, setting the ngOptions attribute expression after the element is compiled, will no longer trigger the ngOptions behavior. This worked previously because the ngOptions logic was part of the select directive, while it is now implemented in the ngOptions directive itself.

#### select

Due to 7fda214c, the `select` directive will now use strict comparison of the `ngModel` scope value against `option` values to determine which option is selected. This means non-string scope values (such as `Number` or `Boolean`) will not be matched against equivalent option strings (such as the strings `"123"`, `"true"` or `"false"`).

In AngularJS 1.3.x, setting `scope.x = 200` would select the option with the value 200 in the following `select`:

    <select ng-model="x">
      <option value="100">100</option>
      <option value="200">200</option>
    </select>

In AngularJS 1.4.x, the 'unknown option' will be selected.

To remedy this, you can initialize the model as a string: `scope.x = '200'`, or if you want to keep the model as a `Number`, you can do the conversion via `$formatters` and `$parsers` on `ngModel`:

    ngModelCtrl.$parsers.push(function(value) {
      return parseInt(value, 10); // Convert option value to number
    });

    ngModelCtrl.$formatters.push(function(value) {
      return value.toString(); // Convert scope value to string
    });

#### ngPattern and pattern

Due to 0e001084, The `ngPattern` and `pattern` directives will validate the regex against the `$viewValue` of `ngModel`, i.e. the value of the model before the $parsers are applied. Previously, the `$modelValue` (the result of the $parsers) was validated.

This fixes issues where `input[date]` and `input[number]` cannot be validated because the `$viewValue` string is parsed into `Date` and `Number` respectively (starting with AngularJS 1.3). It also brings the directives in line with HTML5 constraint validation, which validates against the input value.

This change is unlikely to cause applications to fail, because even in AngularJS 1.2, the value that was validated by pattern could have been manipulated by the $parsers, as all validation was done inside this pipeline.

If you rely on the pattern being validated against the `$modelValue`, you must create your own validator directive that overwrites the built-in pattern validator:

    .directive('patternModelOverwrite', function patternModelOverwriteDirective() {
      return {
        restrict: 'A',
        require: '?ngModel',
        priority: 1,
        compile: function() {
          var regexp, patternExp;

          return {
            pre: function(scope, elm, attr, ctrl) {
              if (!ctrl) return;

              attr.$observe('pattern', function(regex) {
                /**
                 * The built-in directive will call our overwritten validator
                 * (see below). We just need to update the regex.
                 * The preLink fn guaranetees our observer is called first.
                 */
                if (isString(regex) && regex.length > 0) {
                  regex = new RegExp('^' + regex + '$');
                }

                if (regex && !regex.test) {
                  //The built-in validator will throw at this point
                  return;
                }

                regexp = regex || undefined;
              });

            },
            post: function(scope, elm, attr, ctrl) {
              if (!ctrl) return;

              regexp, patternExp = attr.ngPattern || attr.pattern;

              //The postLink fn guarantees we overwrite the built-in pattern validator
              ctrl.$validators.pattern = function(value) {
                return ctrl.$isEmpty(value) ||
                  isUndefined(regexp) ||
                  regexp.test(value);
              };
            }
          };
        }
      };
    });

#### form

Due to 94533e57, the `name` attribute of `form` elements can now only contain characters that can be evaluated as part of an AngularJS expression. This is because AngularJS uses the value of `name` as an assignable expression to set the form on the `$scope`. For example, `name="myForm"` assigns the form to `$scope.myForm` and `name="myObj.myForm"` assigns it to `$scope.myObj.myForm`.

Previously, it was possible to also use names such `name="my:name"`, because AngularJS used a special setter function for the form name. Now the general, more robust `$parse` setter is used.

The easiest way to migrate your code is therefore to remove all special characters from the `name` attribute.

If you need to keep the special characters, you can use the following directive, which will replace the `name` with a value that can be evaluated as an expression in the compile function, and then re-set the original name in the postLink function. This ensures that (1), the form is published on the scope, and (2), the form has the original name, which might be important if you are doing server-side form submission.

    angular.module('myApp').directive('form', function() {
      return {
        restrict: 'E',
        priority: 1000,
        compile: function(element, attrs) {
          var unsupportedCharacter = ':'; // change accordingly
          var originalName = attrs.name;
          if (attrs.name && attrs.name.indexOf(unsupportedCharacter) > 0) {
            attrs.$set('name', 'this["' + originalName + '"]');
          }

          return postLinkFunction(scope, element) {
            // Don't trigger $observers
            element.setAttribute('name', originalName);
          }
        }
      };
    });

### Templating (`ngRepeat`, `$compile`, `ngInclude`)

#### ngRepeat

Due to c260e738, previously, the order of items when using ngRepeat to iterate over object properties was guaranteed to be consistent by sorting the keys into alphabetic order.

Now, the order of the items is browser dependent based on the order returned from iterating over the object using the `for key in obj` syntax.

It seems that browsers generally follow the strategy of providing keys in the order in which they were defined, although there are exceptions when keys are deleted and reinstated. See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/delete#Cross-browser_issues

The best approach is to convert Objects into Arrays by a filter such as https://github.com/petebacondarwin/angular-toArrayFilter or some other mechanism, and then sort them manually in the order you need.

#### $compile

Due to 6a38dbfd, previously, '&' expressions would always set up a function in the isolate scope. Now, if the binding is marked as optional and the attribute is not specified, no function will be added to the isolate scope.

Due to 62d514b, returning an object from a controller constructor function will now override the scope. Views that use the controllerAs method will no longer get the this reference, but the returned object.

#### ngInclude

Due to 3c6e8ce044446735eb2e70d0061db8c6db050289, the `src` attribute of ngInclude no longer accepts an expression that returns the result of `$sce.trustAsResourceUrl`. This will now cause an infinite digest:

Before:

    <div ng-include="findTemplate('https://example.com/templates/myTemplate.html')"></div>

    $scope.findTemplate = function(templateName) {
      return $sce.trustAsResourceUrl(templateName);
    };

To migrate, either cache the result of `trustAsResourceUrl()`, or put the template url in the resource whitelist in the `config()` function:

After:

    var templateCache = {};
    $scope.findTemplate = function(templateName) {
      if (!templateCache[templateName]) {
        templateCache[templateName] = $sce.trustAsResourceUrl(templateName);
      }

      return templateCache[templateName];
    };

    // Alternatively, use `$sceDelegateProvider.resourceUrlWhitelist()`, which means you don't
    // have to use `$sce.trustAsResourceUrl()` at all:

    angular.module('myApp', []).config(function($sceDelegateProvider) {
      $sceDelegateProvider.resourceUrlWhitelist(['self', 'https://example.com/templates/**'])
    });

### Cookies (`ngCookies`)

Due to 38fbe3ee, `$cookies` will no longer expose properties that represent the current browser cookie values. `$cookies` no longer polls the browser for changes to the cookies and no longer copies cookie values onto the `$cookies` object.

This was changed because the polling is expensive and caused issues with the `$cookies` properties not synchronizing correctly with the actual browser cookie values (The reason the polling was originally added was to allow communication between different tabs, but there are better ways to do this today, for example `localStorage`.)

The new API on `$cookies` is as follows:

- `get`
- `put`
- `getObject`
- `putObject`
- `getAll`
- `remove`

You must explicitly use the methods above in order to access cookie data. This also means that you can no longer watch the properties on `$cookies` to detect changes that occur on the browsers cookies.

This feature is generally only needed if a 3rd party library was programmatically changing the cookies at runtime. If you rely on this then you must either write code that can react to the 3rd party library making the changes to cookies or implement your own polling mechanism.

DEPRECATION NOTICE

`$cookieStore` is now deprecated as all the useful logic has been moved to `$cookies`, to which `$cookieStore` now simply delegates calls.

### Server Requests (`$http`)

Due to 5da1256, `transformRequest` functions can no longer modify request headers.

Before this commit `transformRequest` could modify request headers, ex.:

    function requestTransform(data, headers) {
        headers = angular.extend(headers(), {
          'X-MY_HEADER': 'abcd'
        });
      }
      return angular.toJson(data);
    }

This behavior was unintended and undocumented, so the change should affect very few applications. If one needs to dynamically add / remove headers it should be done in a header function, for example:

    $http.get(url, {
      headers: {
        'X-MY_HEADER': function(config) {
          return 'abcd'; //you've got access to a request config object to specify header value dynamically
        }
      }
    })

### Filters (`filter`, `limitTo`)

#### `filter` filter

Due to cea8e751, the `filter` filter will throw an error when used with a non-array. Beforehand it would silently return an empty array.

If necessary, this can be worked around by converting an object to an array, using a filter such as https://github.com/petebacondarwin/angular-toArrayFilter.

#### `limitTo` filter

Due to a3c3bf33, the limitTo filter has changed behavior when the provided limit value is invalid. Now, instead of returning empty object/array, it returns unchanged input.

## Migrating from 1.2 to 1.3

### Controllers

Due to 3f2232b5, `$controller` will no longer look for controllers on `window`. The old behavior of looking on `window` for controllers was originally intended for use in examples, demos, and toy apps. We found that allowing global controller functions encouraged poor practices, so we resolved to disable this behavior by default.

To migrate, register your controllers with modules rather than exposing them as globals:

Before:

    function MyController() {
      // ...
    }

After:

    angular.module('myApp', []).controller('MyController', [function() {
      // ...
    }]);

Although it's not recommended, you can re-enable the old behavior like this:

    angular.module('myModule').config(['$controllerProvider', function($controllerProvider) {
      // this option might be handy for migrating old apps, but please don't use it
      // in new ones!
      $controllerProvider.allowGlobals();
    }]);

### AngularJS Expression Parsing (`$parse` + `$interpolate`)

- due to 77ada4c8,

You can no longer invoke .bind, .call or .apply on a function in AngularJS expressions. This is to disallow changing the behaviour of existing functions in an unforeseen fashion.

- due to 6081f207,

The (deprecated) proto property does not work inside AngularJS expressions anymore.

- due to 48fa3aad,

This prevents the use of {define,lookup}{Getter,Setter} inside AngularJS expressions. If you really need them for some reason, please wrap/bind them to make them less dangerous, then make them available through the scope object.

- due to 528be29d,

This prevents the use of `Object` inside AngularJS expressions. If you need Object.keys, make it accessible in the scope.

- due to bdfc9c02, values 'f', '0', 'false', 'no', 'n', '[]' are no longer treated as falsy. Only JavaScript falsy values are now treated as falsy by the expression parser; there are six of them: false, null, undefined, NaN, 0 and "".

- due to fa6e411d, promise unwrapping has been removed. It has been deprecated since 1.2.0-rc.3. It can no longer be turned on. Two methods have been removed:
  - `$parseProvider.unwrapPromises`
  - `$parseProvider.logPromiseWarnings`

- $interpolate: due to 88c2193c, the function returned by `$interpolate` no longer has a `.parts` array set on it.

  Instead it has two arrays:

  - `.expressions`, an array of the expressions in the interpolated text. The expressions are parsed with `$parse`, with an extra layer converting them to strings when computed
  - `.separators`, an array of strings representing the separations between interpolations in the text. This array is always 1 item longer than the `.expressions` array for easy merging with it

### Miscellaneous AngularJS helpers

- Angular.copy: due to b59b04f9,

This changes `angular.copy` so that it applies the prototype of the original object to the copied object. Previously, `angular.copy` would copy properties of the original object's prototype chain directly onto the copied object.

This means that if you iterate over only the copied object's `hasOwnProperty` properties, it will no longer contain the properties from the prototype. This is actually much more reasonable behaviour and it is unlikely that applications are actually relying on this.

If this behaviour is relied upon, in an app, then one should simply iterate over all the properties on the object (and its inherited properties) and not filter them with `hasOwnProperty`.

Be aware that this change also uses a feature that is not compatible with IE8. If you need this to work on IE8 then you would need to provide a polyfill for `Object.create` and `Object.getPrototypeOf`.

- forEach: due to 55991e33, forEach will iterate only over the initial number of items in the array. So if items are added to the array during the iteration, these won't be iterated over during the initial forEach call.

This change also makes our forEach behave more like Array#forEach.

- angular.toJson: due to c054288c, `toJson()` will no longer strip properties starting with a single `$`. If you relied on `toJson()`'s stripping these types of properties before, you will have to do it manually now. It will still strip properties starting with `$$` though.

### jqLite / JQuery

- jqLite: due to a196c8bc, previously it was possible to set jqLite data on Text/Comment nodes, but now that is allowed only on Element and Document nodes just like in jQuery. We don't expect that app code actually depends on this accidental feature.

- jqLite: due to d71dbb1a, the jQuery `detach()` method does not trigger the `$destroy` event. If you want to destroy AngularJS data attached to the element, use `remove()`.

### AngularJS HTML Compiler (`$compile`)

- due to 2ee29c5d,

The isolated scope of a component directive no longer leaks into the template that contains the instance of the directive. This means that you can no longer access the isolated scope from attributes on the element where the isolated directive is defined.

See https://github.com/angular/angular.js/issues/10236 for an example.

- due to 2cde927e,

Requesting isolate scope and any other scope on a single element is an error. Before this change, the compiler let two directives request a child scope and an isolate scope if the compiler applied them in the order of non-isolate scope directive followed by isolate scope directive.

Now the compiler will error regardless of the order.

If you find that your code is now throwing a `$compile:multidir` error, check that you do not have directives on the same element that are trying to request both an isolate and a non-isolate scope and fix your code.

- due to eec6394a, The `replace` flag for defining directives that replace the element that they are on will be removed in the next major AngularJS version. This feature has difficult semantics (e.g. how attributes are merged) and leads to more problems compared to what it solves. Also, with Web Components it is normal to have custom elements in the DOM.

- due to 299b220f, calling `attr.$observe` no longer returns the observer function, but a deregistration function instead. To migrate the code follow the example below:

Before:

    directive('directiveName', function() {
      return {
        link: function(scope, elm, attr) {
          var observer = attr.$observe('someAttr', function(value) {
            console.log(value);
          });
        }
      };
    });

After:

    directive('directiveName', function() {
      return {
        link: function(scope, elm, attr) {
          var observer = function(value) {
            console.log(value);
          };

          attr.$observe('someAttr', observer);
        }
      };
    });

- due to 531a8de7, `$observe` no longer registers on undefined attributes. For example, if you were using `$observe` on an absent optional attribute to set a default value, the following would not work anymore:

    <my-dir></my-dir>

    // Link function for directive myDir
    link: function(scope, element, attr) {
      attr.$observe('myAttr', function(newVal) {
        scope.myValue = newVal ? newVal : 'myDefaultValue';
      })
    }

Instead, check if the attribute is set before registering the observer:

    link: function(scope, element, attr) {
      if (attr.myAttr) {
        // register the observer
      } else {
        // set the default
      }
    }

### Forms, Inputs and ngModel

- due to 1be9bb9d,

If an expression is used on ng-pattern (such as `ng-pattern="exp"`) or on the pattern attribute (something like on `pattern="{{ exp }}"`) and the expression itself evaluates to a string then the validator will not parse the string as a literal regular expression object (a value like `/abc/i`). Instead, the entire string will be created as the regular expression to test against. This means that any expression flags will not be placed on the RegExp object. To get around this limitation, use a regular expression object as the value for the expression.

    //before
    $scope.exp = '/abc/i';

    //after
    $scope.exp = /abc/i;

- ngModelOptions: due to adfc322b,

This commit changes the API on `NgModelController`, both semantically and in terms of adding and renaming methods.

- `$setViewValue(value)` - This method still changes the `$viewValue` but does not immediately commit this change through to the `$modelValue` as it did previously. Now the value is committed only when a trigger specified in an associated `ngModelOptions` directive occurs. If `ngModelOptions` also has a `debounce` delay specified for the trigger then the change will also be debounced before being committed. In most cases this should not have a significant impact on how `NgModelController` is used: If `updateOn` includes `default` then `$setViewValue` will trigger a (potentially debounced) commit immediately.
- `$cancelUpdate()` - is renamed to `$rollbackViewValue()` and has the same meaning, which is to revert the current `$viewValue` back to the `$lastCommittedViewValue`, to cancel any pending debounced updates and to re-render the input.

To migrate code that used `$cancelUpdate()` follow the example below:

Before:

    $scope.resetWithCancel = function (e) {
      if (e.keyCode === 27) {
        $scope.myForm.myInput1.$cancelUpdate();
        $scope.myValue = '';
      }
    };

After:

    $scope.resetWithCancel = function (e) {
      if (e.keyCode === 27) {
        $scope.myForm.myInput1.$rollbackViewValue();
        $scope.myValue = '';
      }
    }

- types date, time, datetime-local, month, week now always require a `Date` object as model (46bd6dc8, #5864)

- `input[checkbox]` now supports constant expressions in `ngTrueValue` and `ngFalseValue`, making it now possible to e.g. use boolean and integer values. Previously, these attributes would always be treated as strings, whereas they are now parsed as expressions, and will throw if an expression is non-constant. To convert non-constant strings into constant expressions, simply wrap them in an extra pair of quotes, like so:

  `<input type="checkbox" ng-model="..." ng-true-value="'truthyValue'">`

  See c90cefe1614

### Scopes and Digests (`$scope`)

- due to 8c6a8171, Scope#$id is now of type number rather than string. Since the id is primarily being used for debugging purposes this change should not affect anyone.

- due to 82f45aee, #7445, #7523 `$broadcast` and `$emit` will now reset the `currentScope` property of the event to null once the event finished propagating. If any code depends on asynchronously accessing their `currentScope` property, it should be migrated to use `targetScope` instead. All of these cases should be considered programming bugs.

### Server Requests (`$http`, `$resource`)

- $http: due to ad4336f9,

Previously, it was possible to register a response interceptor like so:

    // register the interceptor as a service
    $provide.factory('myHttpInterceptor', function($q, dependency1, dependency2) {
      return function(promise) {
        return promise.then(function(response) {
          // do something on success
          return response;
        }, function(response) {
          // do something on error
          if (canRecover(response)) {
            return responseOrNewPromise
          }
          return $q.reject(response);
        });
      }
    });

    $httpProvider.responseInterceptors.push('myHttpInterceptor');

Now, one must use the newer API introduced in v1.1.4 (4ae46814), like so:

    $provide.factory('myHttpInterceptor', function($q) {
      return {
        response: function(response) {
          // do something on success
          return response;
        },
        responseError: function(response) {
          // do something on error
          if (canRecover(response)) {
            return responseOrNewPromise
          }
          return $q.reject(response);
        }
      };
    });

    $httpProvider.interceptors.push('myHttpInterceptor');

More details on the new interceptors API (which has been around as of v1.1.4) can be found at interceptors

- $httpBackend: due to 6680b7b9, the JSONP behavior for erroneous and empty responses changed: Previously, a JSONP response was regarded as erroneous if it was empty. Now AngularJS is listening to the correct events to detect errors, i.e. even empty responses can be successful.

- $resource: due to d3c50c84,

  If you expected `$resource` to strip these types of properties before, you will have to manually do this yourself now.

### Modules and Injector (`$inject`)

- due to c0b4e2db,

Previously, config blocks would be able to control behaviour of provider registration, due to being invoked prior to provider registration. Now, provider registration always occurs prior to configuration for a given module, and therefore config blocks are not able to have any control over a providers registration.

Example:

Previously, the following:

    angular.module('foo', [])
    .provider('$rootProvider', function() {
      this.$get = function() { ... }
    })
    .config(function($rootProvider) {
      $rootProvider.dependentMode = "B";
    })
    .provider('$dependentProvider', function($rootProvider) {
       if ($rootProvider.dependentMode === "A") {
         this.$get = function() {
          // Special mode!
         }
       } else {
         this.$get = function() {
           // something else
         }
      }
    });

would have "worked", meaning behaviour of the config block between the registration of "$rootProvider" and "$dependentProvider" would have actually accomplished something and changed the behaviour of the app. This is no longer possible within a single module.

### Filters (`orderBy`)

- due to a097aa95, `orderBy` now treats `null` values (which in JavaScript have type `object`) as having a string representation of `'null'`.

### Animation (`ngAnimate`)

- due to 1cb8584e, `$animate` will no longer default the after parameter to the last element of the parent container. Instead, when after is not specified, the new element will be inserted as the first child of the parent container.

To update existing code, change all instances of `$animate.enter()` or `$animate.move()` from:

`$animate.enter(element, parent);`

to:

`$animate.enter(element, parent, angular.element(parent[0].lastChild));`

- due to 1bebe36a,

  Any class-based animation code that makes use of transitions and uses the setup CSS classes (such as class-add and class-remove) must now provide an empty transition value to ensure that its styling is applied right away. In other words if your animation code is expecting any styling to be applied that is defined in the setup class then it will not be applied "instantly" unless a `transition:0s none` value is present in the styling for that CSS class. This situation is only the case if a transition is already present on the base CSS class once the animation kicks off.

Before:

    .animated.my-class-add {
      opacity:0;
      transition:0.5s linear all;
    }
    .animated.my-class-add.my-class-add-active {
      opacity:1;
    }

After:

    .animated.my-class-add {
      transition:0s linear all;
      opacity:0;
    }
    .animated.my-class-add.my-class-add-active {
      transition:0.5s linear all;
      opacity:1;
    }

Please view the documentation for ngAnimate for more info.

### Testing

- due to 85880a64, some deprecated features of Protractor tests no longer work.

`by.binding(descriptor)` no longer allows using the surrounding interpolation markers in the descriptor (the default interpolation markers are `{{}}`). Previously, these were optional.

Before:

    var el = element(by.binding('{{foo}}'));

After:

    var el = element(by.binding('foo'));

Prefixes `ng_` and `x-ng-` are no longer allowed for models. Use `ng-model`.

`by.repeater` cannot find elements by row and column which are not children of the row. For example, if your template is

    <div ng-repeat="foo in foos">{{foo.name}}</div>

Before:

    var el = element(by.repeater('foo in foos').row(2).column('foo.name'))

After:

You may either enclose `{{foo.name}}` in a child element

    <div ng-repeat="foo in foos"><span>{{foo.name}}</span></div>

or simply use:

    var el = element(by.repeater('foo in foos').row(2))

### Internet Explorer 8

- due to eaa1d00b, As communicated before, IE8 is no longer supported.

## Migrating from 1.0 to 1.2

Note: AngularJS versions 1.1.x are considered "experimental" with breaking changes between minor releases. Version 1.2 is the result of several versions on the 1.1 branch, and has a stable API.

If you have an application on 1.1 and want to migrate it to 1.2, everything in the guide below should still apply, but you may want to consult the changelog as well.

### ngRoute has been moved into its own module

Just like `ngResource`, `ngRoute` is now its own module.

Applications that use `$route`, `ngView`, and/or `$routeParams` will now need to load an `angular-route.js` file and have their application's module dependency on the `ngRoute` module.

Before:

    <script src="angular.js"></script>

    var myApp = angular.module('myApp', ['someOtherModule']);

After:

    <script src="angular.js"></script>
    <script src="angular-route.js"></script>

    var myApp = angular.module('myApp', ['ngRoute', 'someOtherModule']);

See 5599b55b.

### Templates no longer automatically unwrap promises

`$parse` and templates in general will no longer automatically unwrap promises.

Before:

    $scope.foo = $http({method: 'GET', url: '/someUrl'});

    <p>{{foo}}</p>

After:

    $http({method: 'GET', url: '/someUrl'})
    .success(function(data) {
      $scope.foo = data;
    });

    <p>{{foo}}</p>

This feature has been deprecated. If absolutely needed, it can be reenabled for now via the `$parseProvider.unwrapPromises(true)` API.

See 5dc35b52, b6a37d11.

### Syntax for named wildcard parameters changed in `$route`

To migrate the code, follow the example below. Here, `*highlight` becomes `:highlight*`

Before:

    $routeProvider.when('/Book1/:book/Chapter/:chapter/*highlight/edit',
    {controller: noop, templateUrl: 'Chapter.html'});

After:

    $routeProvider.when('/Book1/:book/Chapter/:chapter/:highlight*/edit',
    {controller: noop, templateUrl: 'Chapter.html'});

See 04cebcc1.

### You can only bind one expression to `*[src]`, `*[ng-src]` or `action`

With the exception of `<a>` and `<img>` elements, you cannot bind more than one expression to the `src` or `action` attribute of elements.

This is one of several improvements to security introduces by AngularJS 1.2.

Concatenating expressions makes it hard to understand whether some combination of concatenated values are unsafe to use and potentially subject to XSS vulnerabilities. To simplify the task of auditing for XSS issues, we now require that a single expression be used for `*[src/ng-src]` bindings such as bindings for `iframe[src]`, `object[src]`, etc. In addition, this requirement is enforced for `form` tags with `action` attributes.

Examples
`<img src="{{a}}/{{b}}">` | ok
`<iframe src="{{a}}/{{b}}"></iframe>` | bad
`<iframe src="{{a}}"></iframe>` | ok

To migrate your code, you can combine multiple expressions using a method attached to your scope.

Before:

    scope.baseUrl = 'page';
    scope.a = 1;
    scope.b = 2;

    <!-- Are a and b properly escaped here? Is baseUrl controlled by user? -->
    <iframe src="{{baseUrl}}?a={{a}&b={{b}}">

After:

    var baseUrl = "page";
    scope.getIframeSrc = function() {

      // One should think about their particular case and sanitize accordingly
      var qs = ["a", "b"].map(function(value, name) {
          return encodeURIComponent(name) + "=" +
                 encodeURIComponent(value);
        }).join("&");

      // `baseUrl` isn't exposed to a user's control, so we don't have to worry about escaping it.
      return baseUrl + "?" + qs;
    };

    <iframe src="{{getIframeSrc()}}">

See 38deedd6.

### Interpolations inside DOM event handlers are now disallowed

DOM event handlers execute arbitrary JavaScript code. Using an interpolation for such handlers means that the interpolated value is a JS string that is evaluated. Storing or generating such strings is error prone and leads to XSS vulnerabilities. On the other hand, `ngClick` and other AngularJS specific event handlers evaluate AngularJS expressions in non-window (Scope) context which makes them much safer.

To migrate the code follow the example below:

Before:

    JS:   scope.foo = 'alert(1)';
    HTML: <div onclick="{{foo}}">

After:

    JS:   scope.foo = function() { alert(1); }
    HTML: <div ng-click="foo()">

See 39841f2e.

### Directives cannot end with -start or -end

This change was necessary to enable multi-element directives. The best fix is to rename existing directives so that they don't end with these suffixes.

See e46100f7.

### In $q, promise.always has been renamed promise.finally

The reason for this change is to align `$q` with the Q promise library, despite the fact that this makes it a bit more difficult to use with non-ES5 browsers, like IE8.

`finally` also goes well together with the `catch` API that was added to `$q` recently and is part of the DOM promises standard.

To migrate the code follow the example below.

Before:

    $http.get('/foo').always(doSomething);

After:

    $http.get('/foo').finally(doSomething);

Or for IE8-compatible code:

    $http.get('/foo')['finally'](doSomething);

See f078762d.

### ngMobile is now ngTouch

Many touch-enabled devices are not mobile devices, so we decided to rename this module to better reflect its concerns.

To migrate, replace all references to `ngMobile` with `ngTouch` and `angular-mobile.js` with `angular-touch.js`.

See 94ec84e7.

### resource.$then has been removed

Resource instances do not have a `$then` function anymore. Use the `$promise.then` instead.

Before:

    Resource.query().$then(callback);

After:

    Resource.query().$promise.then(callback);

See 05772e15.

### Resource methods return the promise

Methods of a resource instance return the promise rather than the instance itself.

Before:

    resource.$save().chaining = true;

After:

    resource.$save();
    resource.chaining = true;

See 05772e15.

### Resource promises are resolved with the resource instance

On success, the resource promise is resolved with the resource instance rather than HTTP response object.

Use interceptor API to access the HTTP response object.

Before:

    Resource.query().$then(function(response) {...});

After:

    var Resource = $resource('/url', {}, {
      get: {
        method: 'get',
        interceptor: {
          response: function(response) {
            // expose response
            return response;
          }
        }
      }
    });

See 05772e15.

### $location.search supports multiple keys

`$location.search` now supports multiple keys with the same value provided that the values are stored in an array.

Before this change:

- `parseKeyValue` only took the last key overwriting all the previous keys.
- `toKeyValue` joined the keys together in a comma delimited string.

This was deemed buggy behavior. If your server relied on this behavior then either the server should be fixed, or a simple serialization of the array should be done on the client before passing it to `$location`.

See 80739409.

### ngBindHtmlUnsafe has been removed and replaced by ngBindHtml

`ngBindHtml` provides `ngBindHtmlUnsafe` like behavior (evaluate an expression and innerHTML the result into the DOM) when bound to the result of `$sce.trustAsHtml(string)`. When bound to a plain string, the string is sanitized via `$sanitize` before being innerHTML'd. If the `$sanitize` service isn't available (`ngSanitize` module is not loaded) and the bound expression evaluates to a value that is not trusted an exception is thrown.

When using this directive you can either include `ngSanitize` in your module's dependencies (See the example at the `ngBindHtml` reference) or use the `$sce` service to set the value as trusted.

See dae69473.

### Form names that are expressions are evaluated

If you have form names that will evaluate as an expression:

    <form name="ctrl.form">

And if you are accessing the form from your controller:

Before:

    function($scope) {
      $scope['ctrl.form'] // form controller instance
    }

After:

    function($scope) {
      $scope.ctrl.form // form controller instance
    }

This makes it possible to access a form from a controller using the new "controller as" syntax. Supporting the previous behavior offers no benefit.

See 8ea802a1.

### hasOwnProperty disallowed as an input name

Inputs with name equal to `hasOwnProperty` are not allowed inside form or ngForm directives.

Before, inputs whose name was "hasOwnProperty" were quietly ignored and not added to the scope. Now a badname exception is thrown. Using "hasOwnProperty" for an input name would be very unusual and bad practice. To migrate, change your input name.

See 7a586e5c.

### Directives: Order of postLink functions reversed

The order of postLink fn is now mirror opposite of the order in which corresponding preLinking and compile functions execute.

Previously the compile/link fns executed in order, sorted by priority:

# | Step | Old Sort Order | New Sort Order
--- | --- | --- | ---
1 | Compile Fns | High → Low
2 | Compile child nodes
3 | PreLink Fns | High → Low
4 | Link child nodes
5 | PostLink Fns | High → Low | Low → High

"High → Low" here refers to the `priority` option of a directive.

Very few directives in practice rely on the order of postLinking functions (unlike on the order of compile functions), so in the rare case of this change affecting an existing directive, it might be necessary to convert it to a preLinking function or give it negative priority.

You can look at the diff of this commit to see how an internal attribute interpolation directive was adjusted.

See 31f190d4.

### Directive priority

the priority of ngRepeat, ngSwitchWhen, ngIf, ngInclude and ngView has changed. This could affect directives that explicitly specify their priority.

In order to make ngRepeat, ngSwitchWhen, ngIf, ngInclude and ngView work together in all common scenarios their directives are being adjusted to achieve the following precedence:

Directive | Old Priority | New Priority
--- | --- | ---
ngRepeat | 1000 | 1000
ngSwitchWhen | 500 | 800
ngIf | 1000 | 600
ngInclude | 1000 | 400
ngView | 1000 | 400

See b7af76b4.

### ngScenario

browserTrigger now uses an eventData object instead of direct parameters for mouse events. To migrate, place the `keys`,`x` and `y` parameters inside of an object and place that as the third parameter for the browserTrigger function.

See 28f56a38.

### ngInclude and ngView replace its entire element on update

Previously `ngInclude` and `ngView` only updated its element's content. Now these directives will recreate the element every time a new content is included.

This ensures that a single rootElement for all the included contents always exists, which makes definition of css styles for animations much easier.

See 7d69d52a, aa2133ad.

### URLs are now sanitized against a whitelist

A whitelist configured via `$compileProvider` can be used to configure what URLs are considered safe. By default all common protocol prefixes are whitelisted including `data:` URIs with mime types `image/*`. This change shouldn't impact apps that don't contain malicious image links.

See 1adf29af, 3e39ac7e.

### Isolate scope only exposed to directives with `scope` property

If you declare a scope option on a directive, that directive will have an isolate scope. In AngularJS 1.0, if a directive with an isolate scope is used on an element, all directives on that same element have access to the same isolate scope. For example, say we have the following directives:

    // This directive declares an isolate scope.
    .directive('isolateScope', function() {
      return {
        scope: {},
        link: function($scope) {
          console.log('one = ' + $scope.$id);
        }
      };
    })

    // This directive does not.
    .directive('nonIsolateScope', function() {
      return {
        link: function($scope) {
          console.log('two = ' + $scope.$id);
        }
      };
    });

Now what happens if we use both directives on the same element?

    <div isolate-scope non-isolate-scope></div>

In AngularJS 1.0, the nonIsolateScope directive will have access to the isolateScope directive’s scope. The log statements will print the same id, because the scope is the same. But in AngularJS 1.2, the nonIsolateScope will not use the same scope as isolateScope. Instead, it will inherit the parent scope. The log statements will print different id’s.

If your code depends on the AngularJS 1.0 behavior (non-isolate directive needs to access state from within the isolate scope), change the isolate directive to use scope locals to pass these explicitly:

Before

    <input ng-model="$parent.value" ng-isolate>

    .directive('ngIsolate', function() {
      return {
        scope: {},
        template: '{{value}}'
      };
    });

After

    <input ng-model="value" ng-isolate>

    .directive('ngIsolate', function() {
      return {
        scope: {value: '=ngModel'},
        template: '{{value}}
      };
    });

See 909cabd3, #1924 and #2500.

### Change to interpolation priority

Previously, the interpolation priority was `-100` in 1.2.0-rc.2, and `100` before 1.2.0-rc.2. Before this change the binding was setup in the post-linking phase.

Now the attribute interpolation (binding) executes as a directive with priority 100 and the binding is set up in the pre-linking phase.

See 79223eae, #4525, #4528, and #4649

### Underscore-prefixed/suffixed properties are non-bindable

Reverted: This breaking change has been reverted in 1.2.1, and so can be ignored if you're using version 1.2.1 or higher

This change introduces the notion of "private" properties (properties whose names begin and/or end with an underscore) on the scope chain. These properties will not be available to AngularJS expressions (i.e. {{ }} interpolation in templates and strings passed to `$parse`) They are freely available to JavaScript code (as before).

Motivation

AngularJS expressions execute in a limited context. They do not have direct access to the global scope, `window`, `document` or the Function constructor. However, they have direct access to names/properties on the scope chain. It has been a long standing best practice to keep sensitive APIs outside of the scope chain (in a closure or your controller.) That's easier said than done for two reasons:

1. JavaScript does not have a notion of private properties so if you need someone on the scope chain for JavaScript use, you also expose it to AngularJS expressions
2. The new `controller as` syntax that's now in increased usage exposes the entire controller on the scope chain greatly increasing the exposed surface.

Though AngularJS expressions are written and controlled by the developer, they:

1. Typically deal with user input
2. Don't get the kind of test coverage that JavaScript code would

This commit provides a way, via a naming convention, to allow restricting properties from controllers/scopes. This means AngularJS expressions can access only those properties that are actually needed by the expressions.

See 3d6a89e8.

### You cannot bind to select[multiple]

Switching between `select[single]` and `select[multiple]` has always been odd due to browser quirks. This feature never worked with two-way data-binding so it's not expected that anyone is using it.

If you are interested in properly adding this feature, please submit a pull request on Github.

See d87fa004.

### Uncommon region-specific local files were removed from i18n

AngularJS uses the Google Closure library's locale files. The following locales were removed from Closure, so AngularJS is not able to continue to support them:

`chr`, `cy`, `el-polyton`, `en-zz`, `fr-rw`, `fr-sn`, `fr-td`, `fr-tg`, `haw`, `it-ch`, `ln-cg`, `mo`, `ms-bn`, `nl-aw`, `nl-be`, `pt-ao`, `pt-gw`, `pt-mz`, `pt-st`, `ro-md`, `ru-md`, `ru-ua`, `sr-cyrl-ba`, `sr-cyrl-me`, `sr-cyrl`, `sr-latn-ba`, `sr-latn-me`, `sr-latn`, `sr-rs`, `sv-fi`, `sw-ke`, `ta-lk`, `tl-ph`, `ur-in`, `zh-hans-hk`, `zh-hans-mo`, `zh-hans-sg`, `zh-hans`, `zh-hant-hk`, `zh-hant-mo`, `zh-hant-tw`, `zh-hant`

Although these locales were removed from the official AngularJS repository, you can continue to load and use your copy of the locale file provided that you maintain it yourself.

See 6382e21f.

### Services can now return functions

Previously, the service constructor only returned objects regardless of whether a function was returned.

Now, `$injector.instantiate` (and thus `$provide.service`) behaves the same as the native `new` operator and allows functions to be returned as a service.

If using a JavaScript preprocessor it's quite possible when upgrading that services could start behaving incorrectly. Make sure your services return the correct type wanted.

Coffeescript example

    myApp.service 'applicationSrvc', ->
    @something = "value"
    @someFunct = ->
      "something else"

pre 1.2 this service would return the whole object as the service.

post 1.2 this service returns `someFunct` as the value of the service

you would need to change this services to

    myApp.service 'applicationSrvc', ->
    @something = "value"
    @someFunct = ->
      "something else"
    return

to continue to return the complete instance.

See c22adbf1.