You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

angular.js 1.1 MB

​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826
  1. /**
  2. * @license AngularJS v1.4.6
  3. * (c) 2010-2015 Google, Inc. http://angularjs.org
  4. * License: MIT
  5. */
  6. (function(window, document, undefined) {'use strict';
  7. /**
  8. * @description
  9. *
  10. * This object provides a utility for producing rich Error messages within
  11. * Angular. It can be called as follows:
  12. *
  13. * var exampleMinErr = minErr('example');
  14. * throw exampleMinErr('one', 'This {0} is {1}', foo, bar);
  15. *
  16. * The above creates an instance of minErr in the example namespace. The
  17. * resulting error will have a namespaced error code of example.one. The
  18. * resulting error will replace {0} with the value of foo, and {1} with the
  19. * value of bar. The object is not restricted in the number of arguments it can
  20. * take.
  21. *
  22. * If fewer arguments are specified than necessary for interpolation, the extra
  23. * interpolation markers will be preserved in the final string.
  24. *
  25. * Since data will be parsed statically during a build step, some restrictions
  26. * are applied with respect to how minErr instances are created and called.
  27. * Instances should have names of the form namespaceMinErr for a minErr created
  28. * using minErr('namespace') . Error codes, namespaces and template strings
  29. * should all be static strings, not variables or general expressions.
  30. *
  31. * @param {string} module The namespace to use for the new minErr instance.
  32. * @param {function} ErrorConstructor Custom error constructor to be instantiated when returning
  33. * error from returned function, for cases when a particular type of error is useful.
  34. * @returns {function(code:string, template:string, ...templateArgs): Error} minErr instance
  35. */
  36. function minErr(module, ErrorConstructor) {
  37. ErrorConstructor = ErrorConstructor || Error;
  38. return function() {
  39. var SKIP_INDEXES = 2;
  40. var templateArgs = arguments,
  41. code = templateArgs[0],
  42. message = '[' + (module ? module + ':' : '') + code + '] ',
  43. template = templateArgs[1],
  44. paramPrefix, i;
  45. message += template.replace(/\{\d+\}/g, function(match) {
  46. var index = +match.slice(1, -1),
  47. shiftedIndex = index + SKIP_INDEXES;
  48. if (shiftedIndex < templateArgs.length) {
  49. return toDebugString(templateArgs[shiftedIndex]);
  50. }
  51. return match;
  52. });
  53. message += '\nhttp://errors.angularjs.org/1.4.6/' +
  54. (module ? module + '/' : '') + code;
  55. for (i = SKIP_INDEXES, paramPrefix = '?'; i < templateArgs.length; i++, paramPrefix = '&') {
  56. message += paramPrefix + 'p' + (i - SKIP_INDEXES) + '=' +
  57. encodeURIComponent(toDebugString(templateArgs[i]));
  58. }
  59. return new ErrorConstructor(message);
  60. };
  61. }
  62. /* We need to tell jshint what variables are being exported */
  63. /* global angular: true,
  64. msie: true,
  65. jqLite: true,
  66. jQuery: true,
  67. slice: true,
  68. splice: true,
  69. push: true,
  70. toString: true,
  71. ngMinErr: true,
  72. angularModule: true,
  73. uid: true,
  74. REGEX_STRING_REGEXP: true,
  75. VALIDITY_STATE_PROPERTY: true,
  76. lowercase: true,
  77. uppercase: true,
  78. manualLowercase: true,
  79. manualUppercase: true,
  80. nodeName_: true,
  81. isArrayLike: true,
  82. forEach: true,
  83. forEachSorted: true,
  84. reverseParams: true,
  85. nextUid: true,
  86. setHashKey: true,
  87. extend: true,
  88. toInt: true,
  89. inherit: true,
  90. merge: true,
  91. noop: true,
  92. identity: true,
  93. valueFn: true,
  94. isUndefined: true,
  95. isDefined: true,
  96. isObject: true,
  97. isBlankObject: true,
  98. isString: true,
  99. isNumber: true,
  100. isDate: true,
  101. isArray: true,
  102. isFunction: true,
  103. isRegExp: true,
  104. isWindow: true,
  105. isScope: true,
  106. isFile: true,
  107. isFormData: true,
  108. isBlob: true,
  109. isBoolean: true,
  110. isPromiseLike: true,
  111. trim: true,
  112. escapeForRegexp: true,
  113. isElement: true,
  114. makeMap: true,
  115. includes: true,
  116. arrayRemove: true,
  117. copy: true,
  118. shallowCopy: true,
  119. equals: true,
  120. csp: true,
  121. jq: true,
  122. concat: true,
  123. sliceArgs: true,
  124. bind: true,
  125. toJsonReplacer: true,
  126. toJson: true,
  127. fromJson: true,
  128. convertTimezoneToLocal: true,
  129. timezoneToOffset: true,
  130. startingTag: true,
  131. tryDecodeURIComponent: true,
  132. parseKeyValue: true,
  133. toKeyValue: true,
  134. encodeUriSegment: true,
  135. encodeUriQuery: true,
  136. angularInit: true,
  137. bootstrap: true,
  138. getTestability: true,
  139. snake_case: true,
  140. bindJQuery: true,
  141. assertArg: true,
  142. assertArgFn: true,
  143. assertNotHasOwnProperty: true,
  144. getter: true,
  145. getBlockNodes: true,
  146. hasOwnProperty: true,
  147. createMap: true,
  148. NODE_TYPE_ELEMENT: true,
  149. NODE_TYPE_ATTRIBUTE: true,
  150. NODE_TYPE_TEXT: true,
  151. NODE_TYPE_COMMENT: true,
  152. NODE_TYPE_DOCUMENT: true,
  153. NODE_TYPE_DOCUMENT_FRAGMENT: true,
  154. */
  155. ////////////////////////////////////
  156. /**
  157. * @ngdoc module
  158. * @name ng
  159. * @module ng
  160. * @description
  161. *
  162. * # ng (core module)
  163. * The ng module is loaded by default when an AngularJS application is started. The module itself
  164. * contains the essential components for an AngularJS application to function. The table below
  165. * lists a high level breakdown of each of the services/factories, filters, directives and testing
  166. * components available within this core module.
  167. *
  168. * <div doc-module-components="ng"></div>
  169. */
  170. var REGEX_STRING_REGEXP = /^\/(.+)\/([a-z]*)$/;
  171. // The name of a form control's ValidityState property.
  172. // This is used so that it's possible for internal tests to create mock ValidityStates.
  173. var VALIDITY_STATE_PROPERTY = 'validity';
  174. /**
  175. * @ngdoc function
  176. * @name angular.lowercase
  177. * @module ng
  178. * @kind function
  179. *
  180. * @description Converts the specified string to lowercase.
  181. * @param {string} string String to be converted to lowercase.
  182. * @returns {string} Lowercased string.
  183. */
  184. var lowercase = function(string) {return isString(string) ? string.toLowerCase() : string;};
  185. var hasOwnProperty = Object.prototype.hasOwnProperty;
  186. /**
  187. * @ngdoc function
  188. * @name angular.uppercase
  189. * @module ng
  190. * @kind function
  191. *
  192. * @description Converts the specified string to uppercase.
  193. * @param {string} string String to be converted to uppercase.
  194. * @returns {string} Uppercased string.
  195. */
  196. var uppercase = function(string) {return isString(string) ? string.toUpperCase() : string;};
  197. var manualLowercase = function(s) {
  198. /* jshint bitwise: false */
  199. return isString(s)
  200. ? s.replace(/[A-Z]/g, function(ch) {return String.fromCharCode(ch.charCodeAt(0) | 32);})
  201. : s;
  202. };
  203. var manualUppercase = function(s) {
  204. /* jshint bitwise: false */
  205. return isString(s)
  206. ? s.replace(/[a-z]/g, function(ch) {return String.fromCharCode(ch.charCodeAt(0) & ~32);})
  207. : s;
  208. };
  209. // String#toLowerCase and String#toUpperCase don't produce correct results in browsers with Turkish
  210. // locale, for this reason we need to detect this case and redefine lowercase/uppercase methods
  211. // with correct but slower alternatives.
  212. if ('i' !== 'I'.toLowerCase()) {
  213. lowercase = manualLowercase;
  214. uppercase = manualUppercase;
  215. }
  216. var
  217. msie, // holds major version number for IE, or NaN if UA is not IE.
  218. jqLite, // delay binding since jQuery could be loaded after us.
  219. jQuery, // delay binding
  220. slice = [].slice,
  221. splice = [].splice,
  222. push = [].push,
  223. toString = Object.prototype.toString,
  224. getPrototypeOf = Object.getPrototypeOf,
  225. ngMinErr = minErr('ng'),
  226. /** @name angular */
  227. angular = window.angular || (window.angular = {}),
  228. angularModule,
  229. uid = 0;
  230. /**
  231. * documentMode is an IE-only property
  232. * http://msdn.microsoft.com/en-us/library/ie/cc196988(v=vs.85).aspx
  233. */
  234. msie = document.documentMode;
  235. /**
  236. * @private
  237. * @param {*} obj
  238. * @return {boolean} Returns true if `obj` is an array or array-like object (NodeList, Arguments,
  239. * String ...)
  240. */
  241. function isArrayLike(obj) {
  242. if (obj == null || isWindow(obj)) {
  243. return false;
  244. }
  245. // Support: iOS 8.2 (not reproducible in simulator)
  246. // "length" in obj used to prevent JIT error (gh-11508)
  247. var length = "length" in Object(obj) && obj.length;
  248. if (obj.nodeType === NODE_TYPE_ELEMENT && length) {
  249. return true;
  250. }
  251. return isString(obj) || isArray(obj) || length === 0 ||
  252. typeof length === 'number' && length > 0 && (length - 1) in obj;
  253. }
  254. /**
  255. * @ngdoc function
  256. * @name angular.forEach
  257. * @module ng
  258. * @kind function
  259. *
  260. * @description
  261. * Invokes the `iterator` function once for each item in `obj` collection, which can be either an
  262. * object or an array. The `iterator` function is invoked with `iterator(value, key, obj)`, where `value`
  263. * is the value of an object property or an array element, `key` is the object property key or
  264. * array element index and obj is the `obj` itself. Specifying a `context` for the function is optional.
  265. *
  266. * It is worth noting that `.forEach` does not iterate over inherited properties because it filters
  267. * using the `hasOwnProperty` method.
  268. *
  269. * Unlike ES262's
  270. * [Array.prototype.forEach](http://www.ecma-international.org/ecma-262/5.1/#sec-15.4.4.18),
  271. * Providing 'undefined' or 'null' values for `obj` will not throw a TypeError, but rather just
  272. * return the value provided.
  273. *
  274. ```js
  275. var values = {name: 'misko', gender: 'male'};
  276. var log = [];
  277. angular.forEach(values, function(value, key) {
  278. this.push(key + ': ' + value);
  279. }, log);
  280. expect(log).toEqual(['name: misko', 'gender: male']);
  281. ```
  282. *
  283. * @param {Object|Array} obj Object to iterate over.
  284. * @param {Function} iterator Iterator function.
  285. * @param {Object=} context Object to become context (`this`) for the iterator function.
  286. * @returns {Object|Array} Reference to `obj`.
  287. */
  288. function forEach(obj, iterator, context) {
  289. var key, length;
  290. if (obj) {
  291. if (isFunction(obj)) {
  292. for (key in obj) {
  293. // Need to check if hasOwnProperty exists,
  294. // as on IE8 the result of querySelectorAll is an object without a hasOwnProperty function
  295. if (key != 'prototype' && key != 'length' && key != 'name' && (!obj.hasOwnProperty || obj.hasOwnProperty(key))) {
  296. iterator.call(context, obj[key], key, obj);
  297. }
  298. }
  299. } else if (isArray(obj) || isArrayLike(obj)) {
  300. var isPrimitive = typeof obj !== 'object';
  301. for (key = 0, length = obj.length; key < length; key++) {
  302. if (isPrimitive || key in obj) {
  303. iterator.call(context, obj[key], key, obj);
  304. }
  305. }
  306. } else if (obj.forEach && obj.forEach !== forEach) {
  307. obj.forEach(iterator, context, obj);
  308. } else if (isBlankObject(obj)) {
  309. // createMap() fast path --- Safe to avoid hasOwnProperty check because prototype chain is empty
  310. for (key in obj) {
  311. iterator.call(context, obj[key], key, obj);
  312. }
  313. } else if (typeof obj.hasOwnProperty === 'function') {
  314. // Slow path for objects inheriting Object.prototype, hasOwnProperty check needed
  315. for (key in obj) {
  316. if (obj.hasOwnProperty(key)) {
  317. iterator.call(context, obj[key], key, obj);
  318. }
  319. }
  320. } else {
  321. // Slow path for objects which do not have a method `hasOwnProperty`
  322. for (key in obj) {
  323. if (hasOwnProperty.call(obj, key)) {
  324. iterator.call(context, obj[key], key, obj);
  325. }
  326. }
  327. }
  328. }
  329. return obj;
  330. }
  331. function forEachSorted(obj, iterator, context) {
  332. var keys = Object.keys(obj).sort();
  333. for (var i = 0; i < keys.length; i++) {
  334. iterator.call(context, obj[keys[i]], keys[i]);
  335. }
  336. return keys;
  337. }
  338. /**
  339. * when using forEach the params are value, key, but it is often useful to have key, value.
  340. * @param {function(string, *)} iteratorFn
  341. * @returns {function(*, string)}
  342. */
  343. function reverseParams(iteratorFn) {
  344. return function(value, key) { iteratorFn(key, value); };
  345. }
  346. /**
  347. * A consistent way of creating unique IDs in angular.
  348. *
  349. * Using simple numbers allows us to generate 28.6 million unique ids per second for 10 years before
  350. * we hit number precision issues in JavaScript.
  351. *
  352. * Math.pow(2,53) / 60 / 60 / 24 / 365 / 10 = 28.6M
  353. *
  354. * @returns {number} an unique alpha-numeric string
  355. */
  356. function nextUid() {
  357. return ++uid;
  358. }
  359. /**
  360. * Set or clear the hashkey for an object.
  361. * @param obj object
  362. * @param h the hashkey (!truthy to delete the hashkey)
  363. */
  364. function setHashKey(obj, h) {
  365. if (h) {
  366. obj.$$hashKey = h;
  367. } else {
  368. delete obj.$$hashKey;
  369. }
  370. }
  371. function baseExtend(dst, objs, deep) {
  372. var h = dst.$$hashKey;
  373. for (var i = 0, ii = objs.length; i < ii; ++i) {
  374. var obj = objs[i];
  375. if (!isObject(obj) && !isFunction(obj)) continue;
  376. var keys = Object.keys(obj);
  377. for (var j = 0, jj = keys.length; j < jj; j++) {
  378. var key = keys[j];
  379. var src = obj[key];
  380. if (deep && isObject(src)) {
  381. if (isDate(src)) {
  382. dst[key] = new Date(src.valueOf());
  383. } else if (isRegExp(src)) {
  384. dst[key] = new RegExp(src);
  385. } else {
  386. if (!isObject(dst[key])) dst[key] = isArray(src) ? [] : {};
  387. baseExtend(dst[key], [src], true);
  388. }
  389. } else {
  390. dst[key] = src;
  391. }
  392. }
  393. }
  394. setHashKey(dst, h);
  395. return dst;
  396. }
  397. /**
  398. * @ngdoc function
  399. * @name angular.extend
  400. * @module ng
  401. * @kind function
  402. *
  403. * @description
  404. * Extends the destination object `dst` by copying own enumerable properties from the `src` object(s)
  405. * to `dst`. You can specify multiple `src` objects. If you want to preserve original objects, you can do so
  406. * by passing an empty object as the target: `var object = angular.extend({}, object1, object2)`.
  407. *
  408. * **Note:** Keep in mind that `angular.extend` does not support recursive merge (deep copy). Use
  409. * {@link angular.merge} for this.
  410. *
  411. * @param {Object} dst Destination object.
  412. * @param {...Object} src Source object(s).
  413. * @returns {Object} Reference to `dst`.
  414. */
  415. function extend(dst) {
  416. return baseExtend(dst, slice.call(arguments, 1), false);
  417. }
  418. /**
  419. * @ngdoc function
  420. * @name angular.merge
  421. * @module ng
  422. * @kind function
  423. *
  424. * @description
  425. * Deeply extends the destination object `dst` by copying own enumerable properties from the `src` object(s)
  426. * to `dst`. You can specify multiple `src` objects. If you want to preserve original objects, you can do so
  427. * by passing an empty object as the target: `var object = angular.merge({}, object1, object2)`.
  428. *
  429. * Unlike {@link angular.extend extend()}, `merge()` recursively descends into object properties of source
  430. * objects, performing a deep copy.
  431. *
  432. * @param {Object} dst Destination object.
  433. * @param {...Object} src Source object(s).
  434. * @returns {Object} Reference to `dst`.
  435. */
  436. function merge(dst) {
  437. return baseExtend(dst, slice.call(arguments, 1), true);
  438. }
  439. function toInt(str) {
  440. return parseInt(str, 10);
  441. }
  442. function inherit(parent, extra) {
  443. return extend(Object.create(parent), extra);
  444. }
  445. /**
  446. * @ngdoc function
  447. * @name angular.noop
  448. * @module ng
  449. * @kind function
  450. *
  451. * @description
  452. * A function that performs no operations. This function can be useful when writing code in the
  453. * functional style.
  454. ```js
  455. function foo(callback) {
  456. var result = calculateResult();
  457. (callback || angular.noop)(result);
  458. }
  459. ```
  460. */
  461. function noop() {}
  462. noop.$inject = [];
  463. /**
  464. * @ngdoc function
  465. * @name angular.identity
  466. * @module ng
  467. * @kind function
  468. *
  469. * @description
  470. * A function that returns its first argument. This function is useful when writing code in the
  471. * functional style.
  472. *
  473. ```js
  474. function transformer(transformationFn, value) {
  475. return (transformationFn || angular.identity)(value);
  476. };
  477. ```
  478. * @param {*} value to be returned.
  479. * @returns {*} the value passed in.
  480. */
  481. function identity($) {return $;}
  482. identity.$inject = [];
  483. function valueFn(value) {return function() {return value;};}
  484. function hasCustomToString(obj) {
  485. return isFunction(obj.toString) && obj.toString !== Object.prototype.toString;
  486. }
  487. /**
  488. * @ngdoc function
  489. * @name angular.isUndefined
  490. * @module ng
  491. * @kind function
  492. *
  493. * @description
  494. * Determines if a reference is undefined.
  495. *
  496. * @param {*} value Reference to check.
  497. * @returns {boolean} True if `value` is undefined.
  498. */
  499. function isUndefined(value) {return typeof value === 'undefined';}
  500. /**
  501. * @ngdoc function
  502. * @name angular.isDefined
  503. * @module ng
  504. * @kind function
  505. *
  506. * @description
  507. * Determines if a reference is defined.
  508. *
  509. * @param {*} value Reference to check.
  510. * @returns {boolean} True if `value` is defined.
  511. */
  512. function isDefined(value) {return typeof value !== 'undefined';}
  513. /**
  514. * @ngdoc function
  515. * @name angular.isObject
  516. * @module ng
  517. * @kind function
  518. *
  519. * @description
  520. * Determines if a reference is an `Object`. Unlike `typeof` in JavaScript, `null`s are not
  521. * considered to be objects. Note that JavaScript arrays are objects.
  522. *
  523. * @param {*} value Reference to check.
  524. * @returns {boolean} True if `value` is an `Object` but not `null`.
  525. */
  526. function isObject(value) {
  527. // http://jsperf.com/isobject4
  528. return value !== null && typeof value === 'object';
  529. }
  530. /**
  531. * Determine if a value is an object with a null prototype
  532. *
  533. * @returns {boolean} True if `value` is an `Object` with a null prototype
  534. */
  535. function isBlankObject(value) {
  536. return value !== null && typeof value === 'object' && !getPrototypeOf(value);
  537. }
  538. /**
  539. * @ngdoc function
  540. * @name angular.isString
  541. * @module ng
  542. * @kind function
  543. *
  544. * @description
  545. * Determines if a reference is a `String`.
  546. *
  547. * @param {*} value Reference to check.
  548. * @returns {boolean} True if `value` is a `String`.
  549. */
  550. function isString(value) {return typeof value === 'string';}
  551. /**
  552. * @ngdoc function
  553. * @name angular.isNumber
  554. * @module ng
  555. * @kind function
  556. *
  557. * @description
  558. * Determines if a reference is a `Number`.
  559. *
  560. * This includes the "special" numbers `NaN`, `+Infinity` and `-Infinity`.
  561. *
  562. * If you wish to exclude these then you can use the native
  563. * [`isFinite'](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/isFinite)
  564. * method.
  565. *
  566. * @param {*} value Reference to check.
  567. * @returns {boolean} True if `value` is a `Number`.
  568. */
  569. function isNumber(value) {return typeof value === 'number';}
  570. /**
  571. * @ngdoc function
  572. * @name angular.isDate
  573. * @module ng
  574. * @kind function
  575. *
  576. * @description
  577. * Determines if a value is a date.
  578. *
  579. * @param {*} value Reference to check.
  580. * @returns {boolean} True if `value` is a `Date`.
  581. */
  582. function isDate(value) {
  583. return toString.call(value) === '[object Date]';
  584. }
  585. /**
  586. * @ngdoc function
  587. * @name angular.isArray
  588. * @module ng
  589. * @kind function
  590. *
  591. * @description
  592. * Determines if a reference is an `Array`.
  593. *
  594. * @param {*} value Reference to check.
  595. * @returns {boolean} True if `value` is an `Array`.
  596. */
  597. var isArray = Array.isArray;
  598. /**
  599. * @ngdoc function
  600. * @name angular.isFunction
  601. * @module ng
  602. * @kind function
  603. *
  604. * @description
  605. * Determines if a reference is a `Function`.
  606. *
  607. * @param {*} value Reference to check.
  608. * @returns {boolean} True if `value` is a `Function`.
  609. */
  610. function isFunction(value) {return typeof value === 'function';}
  611. /**
  612. * Determines if a value is a regular expression object.
  613. *
  614. * @private
  615. * @param {*} value Reference to check.
  616. * @returns {boolean} True if `value` is a `RegExp`.
  617. */
  618. function isRegExp(value) {
  619. return toString.call(value) === '[object RegExp]';
  620. }
  621. /**
  622. * Checks if `obj` is a window object.
  623. *
  624. * @private
  625. * @param {*} obj Object to check
  626. * @returns {boolean} True if `obj` is a window obj.
  627. */
  628. function isWindow(obj) {
  629. return obj && obj.window === obj;
  630. }
  631. function isScope(obj) {
  632. return obj && obj.$evalAsync && obj.$watch;
  633. }
  634. function isFile(obj) {
  635. return toString.call(obj) === '[object File]';
  636. }
  637. function isFormData(obj) {
  638. return toString.call(obj) === '[object FormData]';
  639. }
  640. function isBlob(obj) {
  641. return toString.call(obj) === '[object Blob]';
  642. }
  643. function isBoolean(value) {
  644. return typeof value === 'boolean';
  645. }
  646. function isPromiseLike(obj) {
  647. return obj && isFunction(obj.then);
  648. }
  649. var TYPED_ARRAY_REGEXP = /^\[object (Uint8(Clamped)?)|(Uint16)|(Uint32)|(Int8)|(Int16)|(Int32)|(Float(32)|(64))Array\]$/;
  650. function isTypedArray(value) {
  651. return TYPED_ARRAY_REGEXP.test(toString.call(value));
  652. }
  653. var trim = function(value) {
  654. return isString(value) ? value.trim() : value;
  655. };
  656. // Copied from:
  657. // http://docs.closure-library.googlecode.com/git/local_closure_goog_string_string.js.source.html#line1021
  658. // Prereq: s is a string.
  659. var escapeForRegexp = function(s) {
  660. return s.replace(/([-()\[\]{}+?*.$\^|,:#<!\\])/g, '\\$1').
  661. replace(/\x08/g, '\\x08');
  662. };
  663. /**
  664. * @ngdoc function
  665. * @name angular.isElement
  666. * @module ng
  667. * @kind function
  668. *
  669. * @description
  670. * Determines if a reference is a DOM element (or wrapped jQuery element).
  671. *
  672. * @param {*} value Reference to check.
  673. * @returns {boolean} True if `value` is a DOM element (or wrapped jQuery element).
  674. */
  675. function isElement(node) {
  676. return !!(node &&
  677. (node.nodeName // we are a direct element
  678. || (node.prop && node.attr && node.find))); // we have an on and find method part of jQuery API
  679. }
  680. /**
  681. * @param str 'key1,key2,...'
  682. * @returns {object} in the form of {key1:true, key2:true, ...}
  683. */
  684. function makeMap(str) {
  685. var obj = {}, items = str.split(","), i;
  686. for (i = 0; i < items.length; i++) {
  687. obj[items[i]] = true;
  688. }
  689. return obj;
  690. }
  691. function nodeName_(element) {
  692. return lowercase(element.nodeName || (element[0] && element[0].nodeName));
  693. }
  694. function includes(array, obj) {
  695. return Array.prototype.indexOf.call(array, obj) != -1;
  696. }
  697. function arrayRemove(array, value) {
  698. var index = array.indexOf(value);
  699. if (index >= 0) {
  700. array.splice(index, 1);
  701. }
  702. return index;
  703. }
  704. /**
  705. * @ngdoc function
  706. * @name angular.copy
  707. * @module ng
  708. * @kind function
  709. *
  710. * @description
  711. * Creates a deep copy of `source`, which should be an object or an array.
  712. *
  713. * * If no destination is supplied, a copy of the object or array is created.
  714. * * If a destination is provided, all of its elements (for arrays) or properties (for objects)
  715. * are deleted and then all elements/properties from the source are copied to it.
  716. * * If `source` is not an object or array (inc. `null` and `undefined`), `source` is returned.
  717. * * If `source` is identical to 'destination' an exception will be thrown.
  718. *
  719. * @param {*} source The source that will be used to make a copy.
  720. * Can be any type, including primitives, `null`, and `undefined`.
  721. * @param {(Object|Array)=} destination Destination into which the source is copied. If
  722. * provided, must be of the same type as `source`.
  723. * @returns {*} The copy or updated `destination`, if `destination` was specified.
  724. *
  725. * @example
  726. <example module="copyExample">
  727. <file name="index.html">
  728. <div ng-controller="ExampleController">
  729. <form novalidate class="simple-form">
  730. Name: <input type="text" ng-model="user.name" /><br />
  731. E-mail: <input type="email" ng-model="user.email" /><br />
  732. Gender: <input type="radio" ng-model="user.gender" value="male" />male
  733. <input type="radio" ng-model="user.gender" value="female" />female<br />
  734. <button ng-click="reset()">RESET</button>
  735. <button ng-click="update(user)">SAVE</button>
  736. </form>
  737. <pre>form = {{user | json}}</pre>
  738. <pre>master = {{master | json}}</pre>
  739. </div>
  740. <script>
  741. angular.module('copyExample', [])
  742. .controller('ExampleController', ['$scope', function($scope) {
  743. $scope.master= {};
  744. $scope.update = function(user) {
  745. // Example with 1 argument
  746. $scope.master= angular.copy(user);
  747. };
  748. $scope.reset = function() {
  749. // Example with 2 arguments
  750. angular.copy($scope.master, $scope.user);
  751. };
  752. $scope.reset();
  753. }]);
  754. </script>
  755. </file>
  756. </example>
  757. */
  758. function copy(source, destination, stackSource, stackDest) {
  759. if (isWindow(source) || isScope(source)) {
  760. throw ngMinErr('cpws',
  761. "Can't copy! Making copies of Window or Scope instances is not supported.");
  762. }
  763. if (isTypedArray(destination)) {
  764. throw ngMinErr('cpta',
  765. "Can't copy! TypedArray destination cannot be mutated.");
  766. }
  767. if (!destination) {
  768. destination = source;
  769. if (isObject(source)) {
  770. var index;
  771. if (stackSource && (index = stackSource.indexOf(source)) !== -1) {
  772. return stackDest[index];
  773. }
  774. // TypedArray, Date and RegExp have specific copy functionality and must be
  775. // pushed onto the stack before returning.
  776. // Array and other objects create the base object and recurse to copy child
  777. // objects. The array/object will be pushed onto the stack when recursed.
  778. if (isArray(source)) {
  779. return copy(source, [], stackSource, stackDest);
  780. } else if (isTypedArray(source)) {
  781. destination = new source.constructor(source);
  782. } else if (isDate(source)) {
  783. destination = new Date(source.getTime());
  784. } else if (isRegExp(source)) {
  785. destination = new RegExp(source.source, source.toString().match(/[^\/]*$/)[0]);
  786. destination.lastIndex = source.lastIndex;
  787. } else if (isFunction(source.cloneNode)) {
  788. destination = source.cloneNode(true);
  789. } else {
  790. var emptyObject = Object.create(getPrototypeOf(source));
  791. return copy(source, emptyObject, stackSource, stackDest);
  792. }
  793. if (stackDest) {
  794. stackSource.push(source);
  795. stackDest.push(destination);
  796. }
  797. }
  798. } else {
  799. if (source === destination) throw ngMinErr('cpi',
  800. "Can't copy! Source and destination are identical.");
  801. stackSource = stackSource || [];
  802. stackDest = stackDest || [];
  803. if (isObject(source)) {
  804. stackSource.push(source);
  805. stackDest.push(destination);
  806. }
  807. var result, key;
  808. if (isArray(source)) {
  809. destination.length = 0;
  810. for (var i = 0; i < source.length; i++) {
  811. destination.push(copy(source[i], null, stackSource, stackDest));
  812. }
  813. } else {
  814. var h = destination.$$hashKey;
  815. if (isArray(destination)) {
  816. destination.length = 0;
  817. } else {
  818. forEach(destination, function(value, key) {
  819. delete destination[key];
  820. });
  821. }
  822. if (isBlankObject(source)) {
  823. // createMap() fast path --- Safe to avoid hasOwnProperty check because prototype chain is empty
  824. for (key in source) {
  825. destination[key] = copy(source[key], null, stackSource, stackDest);
  826. }
  827. } else if (source && typeof source.hasOwnProperty === 'function') {
  828. // Slow path, which must rely on hasOwnProperty
  829. for (key in source) {
  830. if (source.hasOwnProperty(key)) {
  831. destination[key] = copy(source[key], null, stackSource, stackDest);
  832. }
  833. }
  834. } else {
  835. // Slowest path --- hasOwnProperty can't be called as a method
  836. for (key in source) {
  837. if (hasOwnProperty.call(source, key)) {
  838. destination[key] = copy(source[key], null, stackSource, stackDest);
  839. }
  840. }
  841. }
  842. setHashKey(destination,h);
  843. }
  844. }
  845. return destination;
  846. }
  847. /**
  848. * Creates a shallow copy of an object, an array or a primitive.
  849. *
  850. * Assumes that there are no proto properties for objects.
  851. */
  852. function shallowCopy(src, dst) {
  853. if (isArray(src)) {
  854. dst = dst || [];
  855. for (var i = 0, ii = src.length; i < ii; i++) {
  856. dst[i] = src[i];
  857. }
  858. } else if (isObject(src)) {
  859. dst = dst || {};
  860. for (var key in src) {
  861. if (!(key.charAt(0) === '$' && key.charAt(1) === '$')) {
  862. dst[key] = src[key];
  863. }
  864. }
  865. }
  866. return dst || src;
  867. }
  868. /**
  869. * @ngdoc function
  870. * @name angular.equals
  871. * @module ng
  872. * @kind function
  873. *
  874. * @description
  875. * Determines if two objects or two values are equivalent. Supports value types, regular
  876. * expressions, arrays and objects.
  877. *
  878. * Two objects or values are considered equivalent if at least one of the following is true:
  879. *
  880. * * Both objects or values pass `===` comparison.
  881. * * Both objects or values are of the same type and all of their properties are equal by
  882. * comparing them with `angular.equals`.
  883. * * Both values are NaN. (In JavaScript, NaN == NaN => false. But we consider two NaN as equal)
  884. * * Both values represent the same regular expression (In JavaScript,
  885. * /abc/ == /abc/ => false. But we consider two regular expressions as equal when their textual
  886. * representation matches).
  887. *
  888. * During a property comparison, properties of `function` type and properties with names
  889. * that begin with `$` are ignored.
  890. *
  891. * Scope and DOMWindow objects are being compared only by identify (`===`).
  892. *
  893. * @param {*} o1 Object or value to compare.
  894. * @param {*} o2 Object or value to compare.
  895. * @returns {boolean} True if arguments are equal.
  896. */
  897. function equals(o1, o2) {
  898. if (o1 === o2) return true;
  899. if (o1 === null || o2 === null) return false;
  900. if (o1 !== o1 && o2 !== o2) return true; // NaN === NaN
  901. var t1 = typeof o1, t2 = typeof o2, length, key, keySet;
  902. if (t1 == t2) {
  903. if (t1 == 'object') {
  904. if (isArray(o1)) {
  905. if (!isArray(o2)) return false;
  906. if ((length = o1.length) == o2.length) {
  907. for (key = 0; key < length; key++) {
  908. if (!equals(o1[key], o2[key])) return false;
  909. }
  910. return true;
  911. }
  912. } else if (isDate(o1)) {
  913. if (!isDate(o2)) return false;
  914. return equals(o1.getTime(), o2.getTime());
  915. } else if (isRegExp(o1)) {
  916. return isRegExp(o2) ? o1.toString() == o2.toString() : false;
  917. } else {
  918. if (isScope(o1) || isScope(o2) || isWindow(o1) || isWindow(o2) ||
  919. isArray(o2) || isDate(o2) || isRegExp(o2)) return false;
  920. keySet = createMap();
  921. for (key in o1) {
  922. if (key.charAt(0) === '$' || isFunction(o1[key])) continue;
  923. if (!equals(o1[key], o2[key])) return false;
  924. keySet[key] = true;
  925. }
  926. for (key in o2) {
  927. if (!(key in keySet) &&
  928. key.charAt(0) !== '$' &&
  929. isDefined(o2[key]) &&
  930. !isFunction(o2[key])) return false;
  931. }
  932. return true;
  933. }
  934. }
  935. }
  936. return false;
  937. }
  938. var csp = function() {
  939. if (!isDefined(csp.rules)) {
  940. var ngCspElement = (document.querySelector('[ng-csp]') ||
  941. document.querySelector('[data-ng-csp]'));
  942. if (ngCspElement) {
  943. var ngCspAttribute = ngCspElement.getAttribute('ng-csp') ||
  944. ngCspElement.getAttribute('data-ng-csp');
  945. csp.rules = {
  946. noUnsafeEval: !ngCspAttribute || (ngCspAttribute.indexOf('no-unsafe-eval') !== -1),
  947. noInlineStyle: !ngCspAttribute || (ngCspAttribute.indexOf('no-inline-style') !== -1)
  948. };
  949. } else {
  950. csp.rules = {
  951. noUnsafeEval: noUnsafeEval(),
  952. noInlineStyle: false
  953. };
  954. }
  955. }
  956. return csp.rules;
  957. function noUnsafeEval() {
  958. try {
  959. /* jshint -W031, -W054 */
  960. new Function('');
  961. /* jshint +W031, +W054 */
  962. return false;
  963. } catch (e) {
  964. return true;
  965. }
  966. }
  967. };
  968. /**
  969. * @ngdoc directive
  970. * @module ng
  971. * @name ngJq
  972. *
  973. * @element ANY
  974. * @param {string=} ngJq the name of the library available under `window`
  975. * to be used for angular.element
  976. * @description
  977. * Use this directive to force the angular.element library. This should be
  978. * used to force either jqLite by leaving ng-jq blank or setting the name of
  979. * the jquery variable under window (eg. jQuery).
  980. *
  981. * Since angular looks for this directive when it is loaded (doesn't wait for the
  982. * DOMContentLoaded event), it must be placed on an element that comes before the script
  983. * which loads angular. Also, only the first instance of `ng-jq` will be used and all
  984. * others ignored.
  985. *
  986. * @example
  987. * This example shows how to force jqLite using the `ngJq` directive to the `html` tag.
  988. ```html
  989. <!doctype html>
  990. <html ng-app ng-jq>
  991. ...
  992. ...
  993. </html>
  994. ```
  995. * @example
  996. * This example shows how to use a jQuery based library of a different name.
  997. * The library name must be available at the top most 'window'.
  998. ```html
  999. <!doctype html>
  1000. <html ng-app ng-jq="jQueryLib">
  1001. ...
  1002. ...
  1003. </html>
  1004. ```
  1005. */
  1006. var jq = function() {
  1007. if (isDefined(jq.name_)) return jq.name_;
  1008. var el;
  1009. var i, ii = ngAttrPrefixes.length, prefix, name;
  1010. for (i = 0; i < ii; ++i) {
  1011. prefix = ngAttrPrefixes[i];
  1012. if (el = document.querySelector('[' + prefix.replace(':', '\\:') + 'jq]')) {
  1013. name = el.getAttribute(prefix + 'jq');
  1014. break;
  1015. }
  1016. }
  1017. return (jq.name_ = name);
  1018. };
  1019. function concat(array1, array2, index) {
  1020. return array1.concat(slice.call(array2, index));
  1021. }
  1022. function sliceArgs(args, startIndex) {
  1023. return slice.call(args, startIndex || 0);
  1024. }
  1025. /* jshint -W101 */
  1026. /**
  1027. * @ngdoc function
  1028. * @name angular.bind
  1029. * @module ng
  1030. * @kind function
  1031. *
  1032. * @description
  1033. * Returns a function which calls function `fn` bound to `self` (`self` becomes the `this` for
  1034. * `fn`). You can supply optional `args` that are prebound to the function. This feature is also
  1035. * known as [partial application](http://en.wikipedia.org/wiki/Partial_application), as
  1036. * distinguished from [function currying](http://en.wikipedia.org/wiki/Currying#Contrast_with_partial_function_application).
  1037. *
  1038. * @param {Object} self Context which `fn` should be evaluated in.
  1039. * @param {function()} fn Function to be bound.
  1040. * @param {...*} args Optional arguments to be prebound to the `fn` function call.
  1041. * @returns {function()} Function that wraps the `fn` with all the specified bindings.
  1042. */
  1043. /* jshint +W101 */
  1044. function bind(self, fn) {
  1045. var curryArgs = arguments.length > 2 ? sliceArgs(arguments, 2) : [];
  1046. if (isFunction(fn) && !(fn instanceof RegExp)) {
  1047. return curryArgs.length
  1048. ? function() {
  1049. return arguments.length
  1050. ? fn.apply(self, concat(curryArgs, arguments, 0))
  1051. : fn.apply(self, curryArgs);
  1052. }
  1053. : function() {
  1054. return arguments.length
  1055. ? fn.apply(self, arguments)
  1056. : fn.call(self);
  1057. };
  1058. } else {
  1059. // in IE, native methods are not functions so they cannot be bound (note: they don't need to be)
  1060. return fn;
  1061. }
  1062. }
  1063. function toJsonReplacer(key, value) {
  1064. var val = value;
  1065. if (typeof key === 'string' && key.charAt(0) === '$' && key.charAt(1) === '$') {
  1066. val = undefined;
  1067. } else if (isWindow(value)) {
  1068. val = '$WINDOW';
  1069. } else if (value && document === value) {
  1070. val = '$DOCUMENT';
  1071. } else if (isScope(value)) {
  1072. val = '$SCOPE';
  1073. }
  1074. return val;
  1075. }
  1076. /**
  1077. * @ngdoc function
  1078. * @name angular.toJson
  1079. * @module ng
  1080. * @kind function
  1081. *
  1082. * @description
  1083. * Serializes input into a JSON-formatted string. Properties with leading $$ characters will be
  1084. * stripped since angular uses this notation internally.
  1085. *
  1086. * @param {Object|Array|Date|string|number} obj Input to be serialized into JSON.
  1087. * @param {boolean|number} [pretty=2] If set to true, the JSON output will contain newlines and whitespace.
  1088. * If set to an integer, the JSON output will contain that many spaces per indentation.
  1089. * @returns {string|undefined} JSON-ified string representing `obj`.
  1090. */
  1091. function toJson(obj, pretty) {
  1092. if (typeof obj === 'undefined') return undefined;
  1093. if (!isNumber(pretty)) {
  1094. pretty = pretty ? 2 : null;
  1095. }
  1096. return JSON.stringify(obj, toJsonReplacer, pretty);
  1097. }
  1098. /**
  1099. * @ngdoc function
  1100. * @name angular.fromJson
  1101. * @module ng
  1102. * @kind function
  1103. *
  1104. * @description
  1105. * Deserializes a JSON string.
  1106. *
  1107. * @param {string} json JSON string to deserialize.
  1108. * @returns {Object|Array|string|number} Deserialized JSON string.
  1109. */
  1110. function fromJson(json) {
  1111. return isString(json)
  1112. ? JSON.parse(json)
  1113. : json;
  1114. }
  1115. function timezoneToOffset(timezone, fallback) {
  1116. var requestedTimezoneOffset = Date.parse('Jan 01, 1970 00:00:00 ' + timezone) / 60000;
  1117. return isNaN(requestedTimezoneOffset) ? fallback : requestedTimezoneOffset;
  1118. }
  1119. function addDateMinutes(date, minutes) {
  1120. date = new Date(date.getTime());
  1121. date.setMinutes(date.getMinutes() + minutes);
  1122. return date;
  1123. }
  1124. function convertTimezoneToLocal(date, timezone, reverse) {
  1125. reverse = reverse ? -1 : 1;
  1126. var timezoneOffset = timezoneToOffset(timezone, date.getTimezoneOffset());
  1127. return addDateMinutes(date, reverse * (timezoneOffset - date.getTimezoneOffset()));
  1128. }
  1129. /**
  1130. * @returns {string} Returns the string representation of the element.
  1131. */
  1132. function startingTag(element) {
  1133. element = jqLite(element).clone();
  1134. try {
  1135. // turns out IE does not let you set .html() on elements which
  1136. // are not allowed to have children. So we just ignore it.
  1137. element.empty();
  1138. } catch (e) {}
  1139. var elemHtml = jqLite('<div>').append(element).html();
  1140. try {
  1141. return element[0].nodeType === NODE_TYPE_TEXT ? lowercase(elemHtml) :
  1142. elemHtml.
  1143. match(/^(<[^>]+>)/)[1].
  1144. replace(/^<([\w\-]+)/, function(match, nodeName) { return '<' + lowercase(nodeName); });
  1145. } catch (e) {
  1146. return lowercase(elemHtml);
  1147. }
  1148. }
  1149. /////////////////////////////////////////////////
  1150. /**
  1151. * Tries to decode the URI component without throwing an exception.
  1152. *
  1153. * @private
  1154. * @param str value potential URI component to check.
  1155. * @returns {boolean} True if `value` can be decoded
  1156. * with the decodeURIComponent function.
  1157. */
  1158. function tryDecodeURIComponent(value) {
  1159. try {
  1160. return decodeURIComponent(value);
  1161. } catch (e) {
  1162. // Ignore any invalid uri component
  1163. }
  1164. }
  1165. /**
  1166. * Parses an escaped url query string into key-value pairs.
  1167. * @returns {Object.<string,boolean|Array>}
  1168. */
  1169. function parseKeyValue(/**string*/keyValue) {
  1170. var obj = {};
  1171. forEach((keyValue || "").split('&'), function(keyValue) {
  1172. var splitPoint, key, val;
  1173. if (keyValue) {
  1174. key = keyValue = keyValue.replace(/\+/g,'%20');
  1175. splitPoint = keyValue.indexOf('=');
  1176. if (splitPoint !== -1) {
  1177. key = keyValue.substring(0, splitPoint);
  1178. val = keyValue.substring(splitPoint + 1);
  1179. }
  1180. key = tryDecodeURIComponent(key);
  1181. if (isDefined(key)) {
  1182. val = isDefined(val) ? tryDecodeURIComponent(val) : true;
  1183. if (!hasOwnProperty.call(obj, key)) {
  1184. obj[key] = val;
  1185. } else if (isArray(obj[key])) {
  1186. obj[key].push(val);
  1187. } else {
  1188. obj[key] = [obj[key],val];
  1189. }
  1190. }
  1191. }
  1192. });
  1193. return obj;
  1194. }
  1195. function toKeyValue(obj) {
  1196. var parts = [];
  1197. forEach(obj, function(value, key) {
  1198. if (isArray(value)) {
  1199. forEach(value, function(arrayValue) {
  1200. parts.push(encodeUriQuery(key, true) +
  1201. (arrayValue === true ? '' : '=' + encodeUriQuery(arrayValue, true)));
  1202. });
  1203. } else {
  1204. parts.push(encodeUriQuery(key, true) +
  1205. (value === true ? '' : '=' + encodeUriQuery(value, true)));
  1206. }
  1207. });
  1208. return parts.length ? parts.join('&') : '';
  1209. }
  1210. /**
  1211. * We need our custom method because encodeURIComponent is too aggressive and doesn't follow
  1212. * http://www.ietf.org/rfc/rfc3986.txt with regards to the character set (pchar) allowed in path
  1213. * segments:
  1214. * segment = *pchar
  1215. * pchar = unreserved / pct-encoded / sub-delims / ":" / "@"
  1216. * pct-encoded = "%" HEXDIG HEXDIG
  1217. * unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
  1218. * sub-delims = "!" / "$" / "&" / "'" / "(" / ")"
  1219. * / "*" / "+" / "," / ";" / "="
  1220. */
  1221. function encodeUriSegment(val) {
  1222. return encodeUriQuery(val, true).
  1223. replace(/%26/gi, '&').
  1224. replace(/%3D/gi, '=').
  1225. replace(/%2B/gi, '+');
  1226. }
  1227. /**
  1228. * This method is intended for encoding *key* or *value* parts of query component. We need a custom
  1229. * method because encodeURIComponent is too aggressive and encodes stuff that doesn't have to be
  1230. * encoded per http://tools.ietf.org/html/rfc3986:
  1231. * query = *( pchar / "/" / "?" )
  1232. * pchar = unreserved / pct-encoded / sub-delims / ":" / "@"
  1233. * unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
  1234. * pct-encoded = "%" HEXDIG HEXDIG
  1235. * sub-delims = "!" / "$" / "&" / "'" / "(" / ")"
  1236. * / "*" / "+" / "," / ";" / "="
  1237. */
  1238. function encodeUriQuery(val, pctEncodeSpaces) {
  1239. return encodeURIComponent(val).
  1240. replace(/%40/gi, '@').
  1241. replace(/%3A/gi, ':').
  1242. replace(/%24/g, '$').
  1243. replace(/%2C/gi, ',').
  1244. replace(/%3B/gi, ';').
  1245. replace(/%20/g, (pctEncodeSpaces ? '%20' : '+'));
  1246. }
  1247. var ngAttrPrefixes = ['ng-', 'data-ng-', 'ng:', 'x-ng-'];
  1248. function getNgAttribute(element, ngAttr) {
  1249. var attr, i, ii = ngAttrPrefixes.length;
  1250. for (i = 0; i < ii; ++i) {
  1251. attr = ngAttrPrefixes[i] + ngAttr;
  1252. if (isString(attr = element.getAttribute(attr))) {
  1253. return attr;
  1254. }
  1255. }
  1256. return null;
  1257. }
  1258. /**
  1259. * @ngdoc directive
  1260. * @name ngApp
  1261. * @module ng
  1262. *
  1263. * @element ANY
  1264. * @param {angular.Module} ngApp an optional application
  1265. * {@link angular.module module} name to load.
  1266. * @param {boolean=} ngStrictDi if this attribute is present on the app element, the injector will be
  1267. * created in "strict-di" mode. This means that the application will fail to invoke functions which
  1268. * do not use explicit function annotation (and are thus unsuitable for minification), as described
  1269. * in {@link guide/di the Dependency Injection guide}, and useful debugging info will assist in
  1270. * tracking down the root of these bugs.
  1271. *
  1272. * @description
  1273. *
  1274. * Use this directive to **auto-bootstrap** an AngularJS application. The `ngApp` directive
  1275. * designates the **root element** of the application and is typically placed near the root element
  1276. * of the page - e.g. on the `<body>` or `<html>` tags.
  1277. *
  1278. * Only one AngularJS application can be auto-bootstrapped per HTML document. The first `ngApp`
  1279. * found in the document will be used to define the root element to auto-bootstrap as an
  1280. * application. To run multiple applications in an HTML document you must manually bootstrap them using
  1281. * {@link angular.bootstrap} instead. AngularJS applications cannot be nested within each other.
  1282. *
  1283. * You can specify an **AngularJS module** to be used as the root module for the application. This
  1284. * module will be loaded into the {@link auto.$injector} when the application is bootstrapped. It
  1285. * should contain the application code needed or have dependencies on other modules that will
  1286. * contain the code. See {@link angular.module} for more information.
  1287. *
  1288. * In the example below if the `ngApp` directive were not placed on the `html` element then the
  1289. * document would not be compiled, the `AppController` would not be instantiated and the `{{ a+b }}`
  1290. * would not be resolved to `3`.
  1291. *
  1292. * `ngApp` is the easiest, and most common way to bootstrap an application.
  1293. *
  1294. <example module="ngAppDemo">
  1295. <file name="index.html">
  1296. <div ng-controller="ngAppDemoController">
  1297. I can add: {{a}} + {{b}} = {{ a+b }}
  1298. </div>
  1299. </file>
  1300. <file name="script.js">
  1301. angular.module('ngAppDemo', []).controller('ngAppDemoController', function($scope) {
  1302. $scope.a = 1;
  1303. $scope.b = 2;
  1304. });
  1305. </file>
  1306. </example>
  1307. *
  1308. * Using `ngStrictDi`, you would see something like this:
  1309. *
  1310. <example ng-app-included="true">
  1311. <file name="index.html">
  1312. <div ng-app="ngAppStrictDemo" ng-strict-di>
  1313. <div ng-controller="GoodController1">
  1314. I can add: {{a}} + {{b}} = {{ a+b }}
  1315. <p>This renders because the controller does not fail to
  1316. instantiate, by using explicit annotation style (see
  1317. script.js for details)
  1318. </p>
  1319. </div>
  1320. <div ng-controller="GoodController2">
  1321. Name: <input ng-model="name"><br />
  1322. Hello, {{name}}!
  1323. <p>This renders because the controller does not fail to
  1324. instantiate, by using explicit annotation style
  1325. (see script.js for details)
  1326. </p>
  1327. </div>
  1328. <div ng-controller="BadController">
  1329. I can add: {{a}} + {{b}} = {{ a+b }}
  1330. <p>The controller could not be instantiated, due to relying
  1331. on automatic function annotations (which are disabled in
  1332. strict mode). As such, the content of this section is not
  1333. interpolated, and there should be an error in your web console.
  1334. </p>
  1335. </div>
  1336. </div>
  1337. </file>
  1338. <file name="script.js">
  1339. angular.module('ngAppStrictDemo', [])
  1340. // BadController will fail to instantiate, due to relying on automatic function annotation,
  1341. // rather than an explicit annotation
  1342. .controller('BadController', function($scope) {
  1343. $scope.a = 1;
  1344. $scope.b = 2;
  1345. })
  1346. // Unlike BadController, GoodController1 and GoodController2 will not fail to be instantiated,
  1347. // due to using explicit annotations using the array style and $inject property, respectively.
  1348. .controller('GoodController1', ['$scope', function($scope) {
  1349. $scope.a = 1;
  1350. $scope.b = 2;
  1351. }])
  1352. .controller('GoodController2', GoodController2);
  1353. function GoodController2($scope) {
  1354. $scope.name = "World";
  1355. }
  1356. GoodController2.$inject = ['$scope'];
  1357. </file>
  1358. <file name="style.css">
  1359. div[ng-controller] {
  1360. margin-bottom: 1em;
  1361. -webkit-border-radius: 4px;
  1362. border-radius: 4px;
  1363. border: 1px solid;
  1364. padding: .5em;
  1365. }
  1366. div[ng-controller^=Good] {
  1367. border-color: #d6e9c6;
  1368. background-color: #dff0d8;
  1369. color: #3c763d;
  1370. }
  1371. div[ng-controller^=Bad] {
  1372. border-color: #ebccd1;
  1373. background-color: #f2dede;
  1374. color: #a94442;
  1375. margin-bottom: 0;
  1376. }
  1377. </file>
  1378. </example>
  1379. */
  1380. function angularInit(element, bootstrap) {
  1381. var appElement,
  1382. module,
  1383. config = {};
  1384. // The element `element` has priority over any other element
  1385. forEach(ngAttrPrefixes, function(prefix) {
  1386. var name = prefix + 'app';
  1387. if (!appElement && element.hasAttribute && element.hasAttribute(name)) {
  1388. appElement = element;
  1389. module = element.getAttribute(name);
  1390. }
  1391. });
  1392. forEach(ngAttrPrefixes, function(prefix) {
  1393. var name = prefix + 'app';
  1394. var candidate;
  1395. if (!appElement && (candidate = element.querySelector('[' + name.replace(':', '\\:') + ']'))) {
  1396. appElement = candidate;
  1397. module = candidate.getAttribute(name);
  1398. }
  1399. });
  1400. if (appElement) {
  1401. config.strictDi = getNgAttribute(appElement, "strict-di") !== null;
  1402. bootstrap(appElement, module ? [module] : [], config);
  1403. }
  1404. }
  1405. /**
  1406. * @ngdoc function
  1407. * @name angular.bootstrap
  1408. * @module ng
  1409. * @description
  1410. * Use this function to manually start up angular application.
  1411. *
  1412. * See: {@link guide/bootstrap Bootstrap}
  1413. *
  1414. * Note that Protractor based end-to-end tests cannot use this function to bootstrap manually.
  1415. * They must use {@link ng.directive:ngApp ngApp}.
  1416. *
  1417. * Angular will detect if it has been loaded into the browser more than once and only allow the
  1418. * first loaded script to be bootstrapped and will report a warning to the browser console for
  1419. * each of the subsequent scripts. This prevents strange results in applications, where otherwise
  1420. * multiple instances of Angular try to work on the DOM.
  1421. *
  1422. * ```html
  1423. * <!doctype html>
  1424. * <html>
  1425. * <body>
  1426. * <div ng-controller="WelcomeController">
  1427. * {{greeting}}
  1428. * </div>
  1429. *
  1430. * <script src="angular.js"></script>
  1431. * <script>
  1432. * var app = angular.module('demo', [])
  1433. * .controller('WelcomeController', function($scope) {
  1434. * $scope.greeting = 'Welcome!';
  1435. * });
  1436. * angular.bootstrap(document, ['demo']);
  1437. * </script>
  1438. * </body>
  1439. * </html>
  1440. * ```
  1441. *
  1442. * @param {DOMElement} element DOM element which is the root of angular application.
  1443. * @param {Array<String|Function|Array>=} modules an array of modules to load into the application.
  1444. * Each item in the array should be the name of a predefined module or a (DI annotated)
  1445. * function that will be invoked by the injector as a `config` block.
  1446. * See: {@link angular.module modules}
  1447. * @param {Object=} config an object for defining configuration options for the application. The
  1448. * following keys are supported:
  1449. *
  1450. * * `strictDi` - disable automatic function annotation for the application. This is meant to
  1451. * assist in finding bugs which break minified code. Defaults to `false`.
  1452. *
  1453. * @returns {auto.$injector} Returns the newly created injector for this app.
  1454. */
  1455. function bootstrap(element, modules, config) {
  1456. if (!isObject(config)) config = {};
  1457. var defaultConfig = {
  1458. strictDi: false
  1459. };
  1460. config = extend(defaultConfig, config);
  1461. var doBootstrap = function() {
  1462. element = jqLite(element);
  1463. if (element.injector()) {
  1464. var tag = (element[0] === document) ? 'document' : startingTag(element);
  1465. //Encode angle brackets to prevent input from being sanitized to empty string #8683
  1466. throw ngMinErr(
  1467. 'btstrpd',
  1468. "App Already Bootstrapped with this Element '{0}'",
  1469. tag.replace(/</,'&lt;').replace(/>/,'&gt;'));
  1470. }
  1471. modules = modules || [];
  1472. modules.unshift(['$provide', function($provide) {
  1473. $provide.value('$rootElement', element);
  1474. }]);
  1475. if (config.debugInfoEnabled) {
  1476. // Pushing so that this overrides `debugInfoEnabled` setting defined in user's `modules`.
  1477. modules.push(['$compileProvider', function($compileProvider) {
  1478. $compileProvider.debugInfoEnabled(true);
  1479. }]);
  1480. }
  1481. modules.unshift('ng');
  1482. var injector = createInjector(modules, config.strictDi);
  1483. injector.invoke(['$rootScope', '$rootElement', '$compile', '$injector',
  1484. function bootstrapApply(scope, element, compile, injector) {
  1485. scope.$apply(function() {
  1486. element.data('$injector', injector);
  1487. compile(element)(scope);
  1488. });
  1489. }]
  1490. );
  1491. return injector;
  1492. };
  1493. var NG_ENABLE_DEBUG_INFO = /^NG_ENABLE_DEBUG_INFO!/;
  1494. var NG_DEFER_BOOTSTRAP = /^NG_DEFER_BOOTSTRAP!/;
  1495. if (window && NG_ENABLE_DEBUG_INFO.test(window.name)) {
  1496. config.debugInfoEnabled = true;
  1497. window.name = window.name.replace(NG_ENABLE_DEBUG_INFO, '');
  1498. }
  1499. if (window && !NG_DEFER_BOOTSTRAP.test(window.name)) {
  1500. return doBootstrap();
  1501. }
  1502. window.name = window.name.replace(NG_DEFER_BOOTSTRAP, '');
  1503. angular.resumeBootstrap = function(extraModules) {
  1504. forEach(extraModules, function(module) {
  1505. modules.push(module);
  1506. });
  1507. return doBootstrap();
  1508. };
  1509. if (isFunction(angular.resumeDeferredBootstrap)) {
  1510. angular.resumeDeferredBootstrap();
  1511. }
  1512. }
  1513. /**
  1514. * @ngdoc function
  1515. * @name angular.reloadWithDebugInfo
  1516. * @module ng
  1517. * @description
  1518. * Use this function to reload the current application with debug information turned on.
  1519. * This takes precedence over a call to `$compileProvider.debugInfoEnabled(false)`.
  1520. *
  1521. * See {@link ng.$compileProvider#debugInfoEnabled} for more.
  1522. */
  1523. function reloadWithDebugInfo() {
  1524. window.name = 'NG_ENABLE_DEBUG_INFO!' + window.name;
  1525. window.location.reload();
  1526. }
  1527. /**
  1528. * @name angular.getTestability
  1529. * @module ng
  1530. * @description
  1531. * Get the testability service for the instance of Angular on the given
  1532. * element.
  1533. * @param {DOMElement} element DOM element which is the root of angular application.
  1534. */
  1535. function getTestability(rootElement) {
  1536. var injector = angular.element(rootElement).injector();
  1537. if (!injector) {
  1538. throw ngMinErr('test',
  1539. 'no injector found for element argument to getTestability');
  1540. }
  1541. return injector.get('$$testability');
  1542. }
  1543. var SNAKE_CASE_REGEXP = /[A-Z]/g;
  1544. function snake_case(name, separator) {
  1545. separator = separator || '_';
  1546. return name.replace(SNAKE_CASE_REGEXP, function(letter, pos) {
  1547. return (pos ? separator : '') + letter.toLowerCase();
  1548. });
  1549. }
  1550. var bindJQueryFired = false;
  1551. var skipDestroyOnNextJQueryCleanData;
  1552. function bindJQuery() {
  1553. var originalCleanData;
  1554. if (bindJQueryFired) {
  1555. return;
  1556. }
  1557. // bind to jQuery if present;
  1558. var jqName = jq();
  1559. jQuery = isUndefined(jqName) ? window.jQuery : // use jQuery (if present)
  1560. !jqName ? undefined : // use jqLite
  1561. window[jqName]; // use jQuery specified by `ngJq`
  1562. // Use jQuery if it exists with proper functionality, otherwise default to us.
  1563. // Angular 1.2+ requires jQuery 1.7+ for on()/off() support.
  1564. // Angular 1.3+ technically requires at least jQuery 2.1+ but it may work with older
  1565. // versions. It will not work for sure with jQuery <1.7, though.
  1566. if (jQuery && jQuery.fn.on) {
  1567. jqLite = jQuery;
  1568. extend(jQuery.fn, {
  1569. scope: JQLitePrototype.scope,
  1570. isolateScope: JQLitePrototype.isolateScope,
  1571. controller: JQLitePrototype.controller,
  1572. injector: JQLitePrototype.injector,
  1573. inheritedData: JQLitePrototype.inheritedData
  1574. });
  1575. // All nodes removed from the DOM via various jQuery APIs like .remove()
  1576. // are passed through jQuery.cleanData. Monkey-patch this method to fire
  1577. // the $destroy event on all removed nodes.
  1578. originalCleanData = jQuery.cleanData;
  1579. jQuery.cleanData = function(elems) {
  1580. var events;
  1581. if (!skipDestroyOnNextJQueryCleanData) {
  1582. for (var i = 0, elem; (elem = elems[i]) != null; i++) {
  1583. events = jQuery._data(elem, "events");
  1584. if (events && events.$destroy) {
  1585. jQuery(elem).triggerHandler('$destroy');
  1586. }
  1587. }
  1588. } else {
  1589. skipDestroyOnNextJQueryCleanData = false;
  1590. }
  1591. originalCleanData(elems);
  1592. };
  1593. } else {
  1594. jqLite = JQLite;
  1595. }
  1596. angular.element = jqLite;
  1597. // Prevent double-proxying.
  1598. bindJQueryFired = true;
  1599. }
  1600. /**
  1601. * throw error if the argument is falsy.
  1602. */
  1603. function assertArg(arg, name, reason) {
  1604. if (!arg) {
  1605. throw ngMinErr('areq', "Argument '{0}' is {1}", (name || '?'), (reason || "required"));
  1606. }
  1607. return arg;
  1608. }
  1609. function assertArgFn(arg, name, acceptArrayAnnotation) {
  1610. if (acceptArrayAnnotation && isArray(arg)) {
  1611. arg = arg[arg.length - 1];
  1612. }
  1613. assertArg(isFunction(arg), name, 'not a function, got ' +
  1614. (arg && typeof arg === 'object' ? arg.constructor.name || 'Object' : typeof arg));
  1615. return arg;
  1616. }
  1617. /**
  1618. * throw error if the name given is hasOwnProperty
  1619. * @param {String} name the name to test
  1620. * @param {String} context the context in which the name is used, such as module or directive
  1621. */
  1622. function assertNotHasOwnProperty(name, context) {
  1623. if (name === 'hasOwnProperty') {
  1624. throw ngMinErr('badname', "hasOwnProperty is not a valid {0} name", context);
  1625. }
  1626. }
  1627. /**
  1628. * Return the value accessible from the object by path. Any undefined traversals are ignored
  1629. * @param {Object} obj starting object
  1630. * @param {String} path path to traverse
  1631. * @param {boolean} [bindFnToScope=true]
  1632. * @returns {Object} value as accessible by path
  1633. */
  1634. //TODO(misko): this function needs to be removed
  1635. function getter(obj, path, bindFnToScope) {
  1636. if (!path) return obj;
  1637. var keys = path.split('.');
  1638. var key;
  1639. var lastInstance = obj;
  1640. var len = keys.length;
  1641. for (var i = 0; i < len; i++) {
  1642. key = keys[i];
  1643. if (obj) {
  1644. obj = (lastInstance = obj)[key];
  1645. }
  1646. }
  1647. if (!bindFnToScope && isFunction(obj)) {
  1648. return bind(lastInstance, obj);
  1649. }
  1650. return obj;
  1651. }
  1652. /**
  1653. * Return the DOM siblings between the first and last node in the given array.
  1654. * @param {Array} array like object
  1655. * @returns {Array} the inputted object or a jqLite collection containing the nodes
  1656. */
  1657. function getBlockNodes(nodes) {
  1658. // TODO(perf): update `nodes` instead of creating a new object?
  1659. var node = nodes[0];
  1660. var endNode = nodes[nodes.length - 1];
  1661. var blockNodes;
  1662. for (var i = 1; node !== endNode && (node = node.nextSibling); i++) {
  1663. if (blockNodes || nodes[i] !== node) {
  1664. if (!blockNodes) {
  1665. blockNodes = jqLite(slice.call(nodes, 0, i));
  1666. }
  1667. blockNodes.push(node);
  1668. }
  1669. }
  1670. return blockNodes || nodes;
  1671. }
  1672. /**
  1673. * Creates a new object without a prototype. This object is useful for lookup without having to
  1674. * guard against prototypically inherited properties via hasOwnProperty.
  1675. *
  1676. * Related micro-benchmarks:
  1677. * - http://jsperf.com/object-create2
  1678. * - http://jsperf.com/proto-map-lookup/2
  1679. * - http://jsperf.com/for-in-vs-object-keys2
  1680. *
  1681. * @returns {Object}
  1682. */
  1683. function createMap() {
  1684. return Object.create(null);
  1685. }
  1686. var NODE_TYPE_ELEMENT = 1;
  1687. var NODE_TYPE_ATTRIBUTE = 2;
  1688. var NODE_TYPE_TEXT = 3;
  1689. var NODE_TYPE_COMMENT = 8;
  1690. var NODE_TYPE_DOCUMENT = 9;
  1691. var NODE_TYPE_DOCUMENT_FRAGMENT = 11;
  1692. /**
  1693. * @ngdoc type
  1694. * @name angular.Module
  1695. * @module ng
  1696. * @description
  1697. *
  1698. * Interface for configuring angular {@link angular.module modules}.
  1699. */
  1700. function setupModuleLoader(window) {
  1701. var $injectorMinErr = minErr('$injector');
  1702. var ngMinErr = minErr('ng');
  1703. function ensure(obj, name, factory) {
  1704. return obj[name] || (obj[name] = factory());
  1705. }
  1706. var angular = ensure(window, 'angular', Object);
  1707. // We need to expose `angular.$$minErr` to modules such as `ngResource` that reference it during bootstrap
  1708. angular.$$minErr = angular.$$minErr || minErr;
  1709. return ensure(angular, 'module', function() {
  1710. /** @type {Object.<string, angular.Module>} */
  1711. var modules = {};
  1712. /**
  1713. * @ngdoc function
  1714. * @name angular.module
  1715. * @module ng
  1716. * @description
  1717. *
  1718. * The `angular.module` is a global place for creating, registering and retrieving Angular
  1719. * modules.
  1720. * All modules (angular core or 3rd party) that should be available to an application must be
  1721. * registered using this mechanism.
  1722. *
  1723. * Passing one argument retrieves an existing {@link angular.Module},
  1724. * whereas passing more than one argument creates a new {@link angular.Module}
  1725. *
  1726. *
  1727. * # Module
  1728. *
  1729. * A module is a collection of services, directives, controllers, filters, and configuration information.
  1730. * `angular.module` is used to configure the {@link auto.$injector $injector}.
  1731. *
  1732. * ```js
  1733. * // Create a new module
  1734. * var myModule = angular.module('myModule', []);
  1735. *
  1736. * // register a new service
  1737. * myModule.value('appName', 'MyCoolApp');
  1738. *
  1739. * // configure existing services inside initialization blocks.
  1740. * myModule.config(['$locationProvider', function($locationProvider) {
  1741. * // Configure existing providers
  1742. * $locationProvider.hashPrefix('!');
  1743. * }]);
  1744. * ```
  1745. *
  1746. * Then you can create an injector and load your modules like this:
  1747. *
  1748. * ```js
  1749. * var injector = angular.injector(['ng', 'myModule'])
  1750. * ```
  1751. *
  1752. * However it's more likely that you'll just use
  1753. * {@link ng.directive:ngApp ngApp} or
  1754. * {@link angular.bootstrap} to simplify this process for you.
  1755. *
  1756. * @param {!string} name The name of the module to create or retrieve.
  1757. * @param {!Array.<string>=} requires If specified then new module is being created. If
  1758. * unspecified then the module is being retrieved for further configuration.
  1759. * @param {Function=} configFn Optional configuration function for the module. Same as
  1760. * {@link angular.Module#config Module#config()}.
  1761. * @returns {module} new module with the {@link angular.Module} api.
  1762. */
  1763. return function module(name, requires, configFn) {
  1764. var assertNotHasOwnProperty = function(name, context) {
  1765. if (name === 'hasOwnProperty') {
  1766. throw ngMinErr('badname', 'hasOwnProperty is not a valid {0} name', context);
  1767. }
  1768. };
  1769. assertNotHasOwnProperty(name, 'module');
  1770. if (requires && modules.hasOwnProperty(name)) {
  1771. modules[name] = null;
  1772. }
  1773. return ensure(modules, name, function() {
  1774. if (!requires) {
  1775. throw $injectorMinErr('nomod', "Module '{0}' is not available! You either misspelled " +
  1776. "the module name or forgot to load it. If registering a module ensure that you " +
  1777. "specify the dependencies as the second argument.", name);
  1778. }
  1779. /** @type {!Array.<Array.<*>>} */
  1780. var invokeQueue = [];
  1781. /** @type {!Array.<Function>} */
  1782. var configBlocks = [];
  1783. /** @type {!Array.<Function>} */
  1784. var runBlocks = [];
  1785. var config = invokeLater('$injector', 'invoke', 'push', configBlocks);
  1786. /** @type {angular.Module} */
  1787. var moduleInstance = {
  1788. // Private state
  1789. _invokeQueue: invokeQueue,
  1790. _configBlocks: configBlocks,
  1791. _runBlocks: runBlocks,
  1792. /**
  1793. * @ngdoc property
  1794. * @name angular.Module#requires
  1795. * @module ng
  1796. *
  1797. * @description
  1798. * Holds the list of modules which the injector will load before the current module is
  1799. * loaded.
  1800. */
  1801. requires: requires,
  1802. /**
  1803. * @ngdoc property
  1804. * @name angular.Module#name
  1805. * @module ng
  1806. *
  1807. * @description
  1808. * Name of the module.
  1809. */
  1810. name: name,
  1811. /**
  1812. * @ngdoc method
  1813. * @name angular.Module#provider
  1814. * @module ng
  1815. * @param {string} name service name
  1816. * @param {Function} providerType Construction function for creating new instance of the
  1817. * service.
  1818. * @description
  1819. * See {@link auto.$provide#provider $provide.provider()}.
  1820. */
  1821. provider: invokeLaterAndSetModuleName('$provide', 'provider'),
  1822. /**
  1823. * @ngdoc method
  1824. * @name angular.Module#factory
  1825. * @module ng
  1826. * @param {string} name service name
  1827. * @param {Function} providerFunction Function for creating new instance of the service.
  1828. * @description
  1829. * See {@link auto.$provide#factory $provide.factory()}.
  1830. */
  1831. factory: invokeLaterAndSetModuleName('$provide', 'factory'),
  1832. /**
  1833. * @ngdoc method
  1834. * @name angular.Module#service
  1835. * @module ng
  1836. * @param {string} name service name
  1837. * @param {Function} constructor A constructor function that will be instantiated.
  1838. * @description
  1839. * See {@link auto.$provide#service $provide.service()}.
  1840. */
  1841. service: invokeLaterAndSetModuleName('$provide', 'service'),
  1842. /**
  1843. * @ngdoc method
  1844. * @name angular.Module#value
  1845. * @module ng
  1846. * @param {string} name service name
  1847. * @param {*} object Service instance object.
  1848. * @description
  1849. * See {@link auto.$provide#value $provide.value()}.
  1850. */
  1851. value: invokeLater('$provide', 'value'),
  1852. /**
  1853. * @ngdoc method
  1854. * @name angular.Module#constant
  1855. * @module ng
  1856. * @param {string} name constant name
  1857. * @param {*} object Constant value.
  1858. * @description
  1859. * Because the constant are fixed, they get applied before other provide methods.
  1860. * See {@link auto.$provide#constant $provide.constant()}.
  1861. */
  1862. constant: invokeLater('$provide', 'constant', 'unshift'),
  1863. /**
  1864. * @ngdoc method
  1865. * @name angular.Module#decorator
  1866. * @module ng
  1867. * @param {string} The name of the service to decorate.
  1868. * @param {Function} This function will be invoked when the service needs to be
  1869. * instantiated and should return the decorated service instance.
  1870. * @description
  1871. * See {@link auto.$provide#decorator $provide.decorator()}.
  1872. */
  1873. decorator: invokeLaterAndSetModuleName('$provide', 'decorator'),
  1874. /**
  1875. * @ngdoc method
  1876. * @name angular.Module#animation
  1877. * @module ng
  1878. * @param {string} name animation name
  1879. * @param {Function} animationFactory Factory function for creating new instance of an
  1880. * animation.
  1881. * @description
  1882. *
  1883. * **NOTE**: animations take effect only if the **ngAnimate** module is loaded.
  1884. *
  1885. *
  1886. * Defines an animation hook that can be later used with
  1887. * {@link $animate $animate} service and directives that use this service.
  1888. *
  1889. * ```js
  1890. * module.animation('.animation-name', function($inject1, $inject2) {
  1891. * return {
  1892. * eventName : function(element, done) {
  1893. * //code to run the animation
  1894. * //once complete, then run done()
  1895. * return function cancellationFunction(element) {
  1896. * //code to cancel the animation
  1897. * }
  1898. * }
  1899. * }
  1900. * })
  1901. * ```
  1902. *
  1903. * See {@link ng.$animateProvider#register $animateProvider.register()} and
  1904. * {@link ngAnimate ngAnimate module} for more information.
  1905. */
  1906. animation: invokeLaterAndSetModuleName('$animateProvider', 'register'),
  1907. /**
  1908. * @ngdoc method
  1909. * @name angular.Module#filter
  1910. * @module ng
  1911. * @param {string} name Filter name - this must be a valid angular expression identifier
  1912. * @param {Function} filterFactory Factory function for creating new instance of filter.
  1913. * @description
  1914. * See {@link ng.$filterProvider#register $filterProvider.register()}.
  1915. *
  1916. * <div class="alert alert-warning">
  1917. * **Note:** Filter names must be valid angular {@link expression} identifiers, such as `uppercase` or `orderBy`.
  1918. * Names with special characters, such as hyphens and dots, are not allowed. If you wish to namespace
  1919. * your filters, then you can use capitalization (`myappSubsectionFilterx`) or underscores
  1920. * (`myapp_subsection_filterx`).
  1921. * </div>
  1922. */
  1923. filter: invokeLaterAndSetModuleName('$filterProvider', 'register'),
  1924. /**
  1925. * @ngdoc method
  1926. * @name angular.Module#controller
  1927. * @module ng
  1928. * @param {string|Object} name Controller name, or an object map of controllers where the
  1929. * keys are the names and the values are the constructors.
  1930. * @param {Function} constructor Controller constructor function.
  1931. * @description
  1932. * See {@link ng.$controllerProvider#register $controllerProvider.register()}.
  1933. */
  1934. controller: invokeLaterAndSetModuleName('$controllerProvider', 'register'),
  1935. /**
  1936. * @ngdoc method
  1937. * @name angular.Module#directive
  1938. * @module ng
  1939. * @param {string|Object} name Directive name, or an object map of directives where the
  1940. * keys are the names and the values are the factories.
  1941. * @param {Function} directiveFactory Factory function for creating new instance of
  1942. * directives.
  1943. * @description
  1944. * See {@link ng.$compileProvider#directive $compileProvider.directive()}.
  1945. */
  1946. directive: invokeLaterAndSetModuleName('$compileProvider', 'directive'),
  1947. /**
  1948. * @ngdoc method
  1949. * @name angular.Module#config
  1950. * @module ng
  1951. * @param {Function} configFn Execute this function on module load. Useful for service
  1952. * configuration.
  1953. * @description
  1954. * Use this method to register work which needs to be performed on module loading.
  1955. * For more about how to configure services, see
  1956. * {@link providers#provider-recipe Provider Recipe}.
  1957. */
  1958. config: config,
  1959. /**
  1960. * @ngdoc method
  1961. * @name angular.Module#run
  1962. * @module ng
  1963. * @param {Function} initializationFn Execute this function after injector creation.
  1964. * Useful for application initialization.
  1965. * @description
  1966. * Use this method to register work which should be performed when the injector is done
  1967. * loading all modules.
  1968. */
  1969. run: function(block) {
  1970. runBlocks.push(block);
  1971. return this;
  1972. }
  1973. };
  1974. if (configFn) {
  1975. config(configFn);
  1976. }
  1977. return moduleInstance;
  1978. /**
  1979. * @param {string} provider
  1980. * @param {string} method
  1981. * @param {String=} insertMethod
  1982. * @returns {angular.Module}
  1983. */
  1984. function invokeLater(provider, method, insertMethod, queue) {
  1985. if (!queue) queue = invokeQueue;
  1986. return function() {
  1987. queue[insertMethod || 'push']([provider, method, arguments]);
  1988. return moduleInstance;
  1989. };
  1990. }
  1991. /**
  1992. * @param {string} provider
  1993. * @param {string} method
  1994. * @returns {angular.Module}
  1995. */
  1996. function invokeLaterAndSetModuleName(provider, method) {
  1997. return function(recipeName, factoryFunction) {
  1998. if (factoryFunction && isFunction(factoryFunction)) factoryFunction.$$moduleName = name;
  1999. invokeQueue.push([provider, method, arguments]);
  2000. return moduleInstance;
  2001. };
  2002. }
  2003. });
  2004. };
  2005. });
  2006. }
  2007. /* global: toDebugString: true */
  2008. function serializeObject(obj) {
  2009. var seen = [];
  2010. return JSON.stringify(obj, function(key, val) {
  2011. val = toJsonReplacer(key, val);
  2012. if (isObject(val)) {
  2013. if (seen.indexOf(val) >= 0) return '...';
  2014. seen.push(val);
  2015. }
  2016. return val;
  2017. });
  2018. }
  2019. function toDebugString(obj) {
  2020. if (typeof obj === 'function') {
  2021. return obj.toString().replace(/ \{[\s\S]*$/, '');
  2022. } else if (isUndefined(obj)) {
  2023. return 'undefined';
  2024. } else if (typeof obj !== 'string') {
  2025. return serializeObject(obj);
  2026. }
  2027. return obj;
  2028. }
  2029. /* global angularModule: true,
  2030. version: true,
  2031. $CompileProvider,
  2032. htmlAnchorDirective,
  2033. inputDirective,
  2034. inputDirective,
  2035. formDirective,
  2036. scriptDirective,
  2037. selectDirective,
  2038. styleDirective,
  2039. optionDirective,
  2040. ngBindDirective,
  2041. ngBindHtmlDirective,
  2042. ngBindTemplateDirective,
  2043. ngClassDirective,
  2044. ngClassEvenDirective,
  2045. ngClassOddDirective,
  2046. ngCloakDirective,
  2047. ngControllerDirective,
  2048. ngFormDirective,
  2049. ngHideDirective,
  2050. ngIfDirective,
  2051. ngIncludeDirective,
  2052. ngIncludeFillContentDirective,
  2053. ngInitDirective,
  2054. ngNonBindableDirective,
  2055. ngPluralizeDirective,
  2056. ngRepeatDirective,
  2057. ngShowDirective,
  2058. ngStyleDirective,
  2059. ngSwitchDirective,
  2060. ngSwitchWhenDirective,
  2061. ngSwitchDefaultDirective,
  2062. ngOptionsDirective,
  2063. ngTranscludeDirective,
  2064. ngModelDirective,
  2065. ngListDirective,
  2066. ngChangeDirective,
  2067. patternDirective,
  2068. patternDirective,
  2069. requiredDirective,
  2070. requiredDirective,
  2071. minlengthDirective,
  2072. minlengthDirective,
  2073. maxlengthDirective,
  2074. maxlengthDirective,
  2075. ngValueDirective,
  2076. ngModelOptionsDirective,
  2077. ngAttributeAliasDirectives,
  2078. ngEventDirectives,
  2079. $AnchorScrollProvider,
  2080. $AnimateProvider,
  2081. $CoreAnimateCssProvider,
  2082. $$CoreAnimateQueueProvider,
  2083. $$CoreAnimateRunnerProvider,
  2084. $BrowserProvider,
  2085. $CacheFactoryProvider,
  2086. $ControllerProvider,
  2087. $DocumentProvider,
  2088. $ExceptionHandlerProvider,
  2089. $FilterProvider,
  2090. $$ForceReflowProvider,
  2091. $InterpolateProvider,
  2092. $IntervalProvider,
  2093. $$HashMapProvider,
  2094. $HttpProvider,
  2095. $HttpParamSerializerProvider,
  2096. $HttpParamSerializerJQLikeProvider,
  2097. $HttpBackendProvider,
  2098. $LocationProvider,
  2099. $LogProvider,
  2100. $ParseProvider,
  2101. $RootScopeProvider,
  2102. $QProvider,
  2103. $$QProvider,
  2104. $$SanitizeUriProvider,
  2105. $SceProvider,
  2106. $SceDelegateProvider,
  2107. $SnifferProvider,
  2108. $TemplateCacheProvider,
  2109. $TemplateRequestProvider,
  2110. $$TestabilityProvider,
  2111. $TimeoutProvider,
  2112. $$RAFProvider,
  2113. $WindowProvider,
  2114. $$jqLiteProvider,
  2115. $$CookieReaderProvider
  2116. */
  2117. /**
  2118. * @ngdoc object
  2119. * @name angular.version
  2120. * @module ng
  2121. * @description
  2122. * An object that contains information about the current AngularJS version.
  2123. *
  2124. * This object has the following properties:
  2125. *
  2126. * - `full` – `{string}` – Full version string, such as "0.9.18".
  2127. * - `major` – `{number}` – Major version number, such as "0".
  2128. * - `minor` – `{number}` – Minor version number, such as "9".
  2129. * - `dot` – `{number}` – Dot version number, such as "18".
  2130. * - `codeName` – `{string}` – Code name of the release, such as "jiggling-armfat".
  2131. */
  2132. var version = {
  2133. full: '1.4.6', // all of these placeholder strings will be replaced by grunt's
  2134. major: 1, // package task
  2135. minor: 4,
  2136. dot: 6,
  2137. codeName: 'multiplicative-elevation'
  2138. };
  2139. function publishExternalAPI(angular) {
  2140. extend(angular, {
  2141. 'bootstrap': bootstrap,
  2142. 'copy': copy,
  2143. 'extend': extend,
  2144. 'merge': merge,
  2145. 'equals': equals,
  2146. 'element': jqLite,
  2147. 'forEach': forEach,
  2148. 'injector': createInjector,
  2149. 'noop': noop,
  2150. 'bind': bind,
  2151. 'toJson': toJson,
  2152. 'fromJson': fromJson,
  2153. 'identity': identity,
  2154. 'isUndefined': isUndefined,
  2155. 'isDefined': isDefined,
  2156. 'isString': isString,
  2157. 'isFunction': isFunction,
  2158. 'isObject': isObject,
  2159. 'isNumber': isNumber,
  2160. 'isElement': isElement,
  2161. 'isArray': isArray,
  2162. 'version': version,
  2163. 'isDate': isDate,
  2164. 'lowercase': lowercase,
  2165. 'uppercase': uppercase,
  2166. 'callbacks': {counter: 0},
  2167. 'getTestability': getTestability,
  2168. '$$minErr': minErr,
  2169. '$$csp': csp,
  2170. 'reloadWithDebugInfo': reloadWithDebugInfo
  2171. });
  2172. angularModule = setupModuleLoader(window);
  2173. angularModule('ng', ['ngLocale'], ['$provide',
  2174. function ngModule($provide) {
  2175. // $$sanitizeUriProvider needs to be before $compileProvider as it is used by it.
  2176. $provide.provider({
  2177. $$sanitizeUri: $$SanitizeUriProvider
  2178. });
  2179. $provide.provider('$compile', $CompileProvider).
  2180. directive({
  2181. a: htmlAnchorDirective,
  2182. input: inputDirective,
  2183. textarea: inputDirective,
  2184. form: formDirective,
  2185. script: scriptDirective,
  2186. select: selectDirective,
  2187. style: styleDirective,
  2188. option: optionDirective,
  2189. ngBind: ngBindDirective,
  2190. ngBindHtml: ngBindHtmlDirective,
  2191. ngBindTemplate: ngBindTemplateDirective,
  2192. ngClass: ngClassDirective,
  2193. ngClassEven: ngClassEvenDirective,
  2194. ngClassOdd: ngClassOddDirective,
  2195. ngCloak: ngCloakDirective,
  2196. ngController: ngControllerDirective,
  2197. ngForm: ngFormDirective,
  2198. ngHide: ngHideDirective,
  2199. ngIf: ngIfDirective,
  2200. ngInclude: ngIncludeDirective,
  2201. ngInit: ngInitDirective,
  2202. ngNonBindable: ngNonBindableDirective,
  2203. ngPluralize: ngPluralizeDirective,
  2204. ngRepeat: ngRepeatDirective,
  2205. ngShow: ngShowDirective,
  2206. ngStyle: ngStyleDirective,
  2207. ngSwitch: ngSwitchDirective,
  2208. ngSwitchWhen: ngSwitchWhenDirective,
  2209. ngSwitchDefault: ngSwitchDefaultDirective,
  2210. ngOptions: ngOptionsDirective,
  2211. ngTransclude: ngTranscludeDirective,
  2212. ngModel: ngModelDirective,
  2213. ngList: ngListDirective,
  2214. ngChange: ngChangeDirective,
  2215. pattern: patternDirective,
  2216. ngPattern: patternDirective,
  2217. required: requiredDirective,
  2218. ngRequired: requiredDirective,
  2219. minlength: minlengthDirective,
  2220. ngMinlength: minlengthDirective,
  2221. maxlength: maxlengthDirective,
  2222. ngMaxlength: maxlengthDirective,
  2223. ngValue: ngValueDirective,
  2224. ngModelOptions: ngModelOptionsDirective
  2225. }).
  2226. directive({
  2227. ngInclude: ngIncludeFillContentDirective
  2228. }).
  2229. directive(ngAttributeAliasDirectives).
  2230. directive(ngEventDirectives);
  2231. $provide.provider({
  2232. $anchorScroll: $AnchorScrollProvider,
  2233. $animate: $AnimateProvider,
  2234. $animateCss: $CoreAnimateCssProvider,
  2235. $$animateQueue: $$CoreAnimateQueueProvider,
  2236. $$AnimateRunner: $$CoreAnimateRunnerProvider,
  2237. $browser: $BrowserProvider,
  2238. $cacheFactory: $CacheFactoryProvider,
  2239. $controller: $ControllerProvider,
  2240. $document: $DocumentProvider,
  2241. $exceptionHandler: $ExceptionHandlerProvider,
  2242. $filter: $FilterProvider,
  2243. $$forceReflow: $$ForceReflowProvider,
  2244. $interpolate: $InterpolateProvider,
  2245. $interval: $IntervalProvider,
  2246. $http: $HttpProvider,
  2247. $httpParamSerializer: $HttpParamSerializerProvider,
  2248. $httpParamSerializerJQLike: $HttpParamSerializerJQLikeProvider,
  2249. $httpBackend: $HttpBackendProvider,
  2250. $location: $LocationProvider,
  2251. $log: $LogProvider,
  2252. $parse: $ParseProvider,
  2253. $rootScope: $RootScopeProvider,
  2254. $q: $QProvider,
  2255. $$q: $$QProvider,
  2256. $sce: $SceProvider,
  2257. $sceDelegate: $SceDelegateProvider,
  2258. $sniffer: $SnifferProvider,
  2259. $templateCache: $TemplateCacheProvider,
  2260. $templateRequest: $TemplateRequestProvider,
  2261. $$testability: $$TestabilityProvider,
  2262. $timeout: $TimeoutProvider,
  2263. $window: $WindowProvider,
  2264. $$rAF: $$RAFProvider,
  2265. $$jqLite: $$jqLiteProvider,
  2266. $$HashMap: $$HashMapProvider,
  2267. $$cookieReader: $$CookieReaderProvider
  2268. });
  2269. }
  2270. ]);
  2271. }
  2272. /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
  2273. * Any commits to this file should be reviewed with security in mind. *
  2274. * Changes to this file can potentially create security vulnerabilities. *
  2275. * An approval from 2 Core members with history of modifying *
  2276. * this file is required. *
  2277. * *
  2278. * Does the change somehow allow for arbitrary javascript to be executed? *
  2279. * Or allows for someone to change the prototype of built-in objects? *
  2280. * Or gives undesired access to variables likes document or window? *
  2281. * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
  2282. /* global JQLitePrototype: true,
  2283. addEventListenerFn: true,
  2284. removeEventListenerFn: true,
  2285. BOOLEAN_ATTR: true,
  2286. ALIASED_ATTR: true,
  2287. */
  2288. //////////////////////////////////
  2289. //JQLite
  2290. //////////////////////////////////
  2291. /**
  2292. * @ngdoc function
  2293. * @name angular.element
  2294. * @module ng
  2295. * @kind function
  2296. *
  2297. * @description
  2298. * Wraps a raw DOM element or HTML string as a [jQuery](http://jquery.com) element.
  2299. *
  2300. * If jQuery is available, `angular.element` is an alias for the
  2301. * [jQuery](http://api.jquery.com/jQuery/) function. If jQuery is not available, `angular.element`
  2302. * delegates to Angular's built-in subset of jQuery, called "jQuery lite" or "jqLite."
  2303. *
  2304. * <div class="alert alert-success">jqLite is a tiny, API-compatible subset of jQuery that allows
  2305. * Angular to manipulate the DOM in a cross-browser compatible way. **jqLite** implements only the most
  2306. * commonly needed functionality with the goal of having a very small footprint.</div>
  2307. *
  2308. * To use `jQuery`, simply ensure it is loaded before the `angular.js` file.
  2309. *
  2310. * <div class="alert">**Note:** all element references in Angular are always wrapped with jQuery or
  2311. * jqLite; they are never raw DOM references.</div>
  2312. *
  2313. * ## Angular's jqLite
  2314. * jqLite provides only the following jQuery methods:
  2315. *
  2316. * - [`addClass()`](http://api.jquery.com/addClass/)
  2317. * - [`after()`](http://api.jquery.com/after/)
  2318. * - [`append()`](http://api.jquery.com/append/)
  2319. * - [`attr()`](http://api.jquery.com/attr/) - Does not support functions as parameters
  2320. * - [`bind()`](http://api.jquery.com/bind/) - Does not support namespaces, selectors or eventData
  2321. * - [`children()`](http://api.jquery.com/children/) - Does not support selectors
  2322. * - [`clone()`](http://api.jquery.com/clone/)
  2323. * - [`contents()`](http://api.jquery.com/contents/)
  2324. * - [`css()`](http://api.jquery.com/css/) - Only retrieves inline-styles, does not call `getComputedStyle()`. As a setter, does not convert numbers to strings or append 'px'.
  2325. * - [`data()`](http://api.jquery.com/data/)
  2326. * - [`detach()`](http://api.jquery.com/detach/)
  2327. * - [`empty()`](http://api.jquery.com/empty/)
  2328. * - [`eq()`](http://api.jquery.com/eq/)
  2329. * - [`find()`](http://api.jquery.com/find/) - Limited to lookups by tag name
  2330. * - [`hasClass()`](http://api.jquery.com/hasClass/)
  2331. * - [`html()`](http://api.jquery.com/html/)
  2332. * - [`next()`](http://api.jquery.com/next/) - Does not support selectors
  2333. * - [`on()`](http://api.jquery.com/on/) - Does not support namespaces, selectors or eventData
  2334. * - [`off()`](http://api.jquery.com/off/) - Does not support namespaces, selectors or event object as parameter
  2335. * - [`one()`](http://api.jquery.com/one/) - Does not support namespaces or selectors
  2336. * - [`parent()`](http://api.jquery.com/parent/) - Does not support selectors
  2337. * - [`prepend()`](http://api.jquery.com/prepend/)
  2338. * - [`prop()`](http://api.jquery.com/prop/)
  2339. * - [`ready()`](http://api.jquery.com/ready/)
  2340. * - [`remove()`](http://api.jquery.com/remove/)
  2341. * - [`removeAttr()`](http://api.jquery.com/removeAttr/)
  2342. * - [`removeClass()`](http://api.jquery.com/removeClass/)
  2343. * - [`removeData()`](http://api.jquery.com/removeData/)
  2344. * - [`replaceWith()`](http://api.jquery.com/replaceWith/)
  2345. * - [`text()`](http://api.jquery.com/text/)
  2346. * - [`toggleClass()`](http://api.jquery.com/toggleClass/)
  2347. * - [`triggerHandler()`](http://api.jquery.com/triggerHandler/) - Passes a dummy event object to handlers.
  2348. * - [`unbind()`](http://api.jquery.com/unbind/) - Does not support namespaces or event object as parameter
  2349. * - [`val()`](http://api.jquery.com/val/)
  2350. * - [`wrap()`](http://api.jquery.com/wrap/)
  2351. *
  2352. * ## jQuery/jqLite Extras
  2353. * Angular also provides the following additional methods and events to both jQuery and jqLite:
  2354. *
  2355. * ### Events
  2356. * - `$destroy` - AngularJS intercepts all jqLite/jQuery's DOM destruction apis and fires this event
  2357. * on all DOM nodes being removed. This can be used to clean up any 3rd party bindings to the DOM
  2358. * element before it is removed.
  2359. *
  2360. * ### Methods
  2361. * - `controller(name)` - retrieves the controller of the current element or its parent. By default
  2362. * retrieves controller associated with the `ngController` directive. If `name` is provided as
  2363. * camelCase directive name, then the controller for this directive will be retrieved (e.g.
  2364. * `'ngModel'`).
  2365. * - `injector()` - retrieves the injector of the current element or its parent.
  2366. * - `scope()` - retrieves the {@link ng.$rootScope.Scope scope} of the current
  2367. * element or its parent. Requires {@link guide/production#disabling-debug-data Debug Data} to
  2368. * be enabled.
  2369. * - `isolateScope()` - retrieves an isolate {@link ng.$rootScope.Scope scope} if one is attached directly to the
  2370. * current element. This getter should be used only on elements that contain a directive which starts a new isolate
  2371. * scope. Calling `scope()` on this element always returns the original non-isolate scope.
  2372. * Requires {@link guide/production#disabling-debug-data Debug Data} to be enabled.
  2373. * - `inheritedData()` - same as `data()`, but walks up the DOM until a value is found or the top
  2374. * parent element is reached.
  2375. *
  2376. * @param {string|DOMElement} element HTML string or DOMElement to be wrapped into jQuery.
  2377. * @returns {Object} jQuery object.
  2378. */
  2379. JQLite.expando = 'ng339';
  2380. var jqCache = JQLite.cache = {},
  2381. jqId = 1,
  2382. addEventListenerFn = function(element, type, fn) {
  2383. element.addEventListener(type, fn, false);
  2384. },
  2385. removeEventListenerFn = function(element, type, fn) {
  2386. element.removeEventListener(type, fn, false);
  2387. };
  2388. /*
  2389. * !!! This is an undocumented "private" function !!!
  2390. */
  2391. JQLite._data = function(node) {
  2392. //jQuery always returns an object on cache miss
  2393. return this.cache[node[this.expando]] || {};
  2394. };
  2395. function jqNextId() { return ++jqId; }
  2396. var SPECIAL_CHARS_REGEXP = /([\:\-\_]+(.))/g;
  2397. var MOZ_HACK_REGEXP = /^moz([A-Z])/;
  2398. var MOUSE_EVENT_MAP= { mouseleave: "mouseout", mouseenter: "mouseover"};
  2399. var jqLiteMinErr = minErr('jqLite');
  2400. /**
  2401. * Converts snake_case to camelCase.
  2402. * Also there is special case for Moz prefix starting with upper case letter.
  2403. * @param name Name to normalize
  2404. */
  2405. function camelCase(name) {
  2406. return name.
  2407. replace(SPECIAL_CHARS_REGEXP, function(_, separator, letter, offset) {
  2408. return offset ? letter.toUpperCase() : letter;
  2409. }).
  2410. replace(MOZ_HACK_REGEXP, 'Moz$1');
  2411. }
  2412. var SINGLE_TAG_REGEXP = /^<(\w+)\s*\/?>(?:<\/\1>|)$/;
  2413. var HTML_REGEXP = /<|&#?\w+;/;
  2414. var TAG_NAME_REGEXP = /<([\w:]+)/;
  2415. var XHTML_TAG_REGEXP = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi;
  2416. var wrapMap = {
  2417. 'option': [1, '<select multiple="multiple">', '</select>'],
  2418. 'thead': [1, '<table>', '</table>'],
  2419. 'col': [2, '<table><colgroup>', '</colgroup></table>'],
  2420. 'tr': [2, '<table><tbody>', '</tbody></table>'],
  2421. 'td': [3, '<table><tbody><tr>', '</tr></tbody></table>'],
  2422. '_default': [0, "", ""]
  2423. };
  2424. wrapMap.optgroup = wrapMap.option;
  2425. wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead;
  2426. wrapMap.th = wrapMap.td;
  2427. function jqLiteIsTextNode(html) {
  2428. return !HTML_REGEXP.test(html);
  2429. }
  2430. function jqLiteAcceptsData(node) {
  2431. // The window object can accept data but has no nodeType
  2432. // Otherwise we are only interested in elements (1) and documents (9)
  2433. var nodeType = node.nodeType;
  2434. return nodeType === NODE_TYPE_ELEMENT || !nodeType || nodeType === NODE_TYPE_DOCUMENT;
  2435. }
  2436. function jqLiteHasData(node) {
  2437. for (var key in jqCache[node.ng339]) {
  2438. return true;
  2439. }
  2440. return false;
  2441. }
  2442. function jqLiteBuildFragment(html, context) {
  2443. var tmp, tag, wrap,
  2444. fragment = context.createDocumentFragment(),
  2445. nodes = [], i;
  2446. if (jqLiteIsTextNode(html)) {
  2447. // Convert non-html into a text node
  2448. nodes.push(context.createTextNode(html));
  2449. } else {
  2450. // Convert html into DOM nodes
  2451. tmp = tmp || fragment.appendChild(context.createElement("div"));
  2452. tag = (TAG_NAME_REGEXP.exec(html) || ["", ""])[1].toLowerCase();
  2453. wrap = wrapMap[tag] || wrapMap._default;
  2454. tmp.innerHTML = wrap[1] + html.replace(XHTML_TAG_REGEXP, "<$1></$2>") + wrap[2];
  2455. // Descend through wrappers to the right content
  2456. i = wrap[0];
  2457. while (i--) {
  2458. tmp = tmp.lastChild;
  2459. }
  2460. nodes = concat(nodes, tmp.childNodes);
  2461. tmp = fragment.firstChild;
  2462. tmp.textContent = "";
  2463. }
  2464. // Remove wrapper from fragment
  2465. fragment.textContent = "";
  2466. fragment.innerHTML = ""; // Clear inner HTML
  2467. forEach(nodes, function(node) {
  2468. fragment.appendChild(node);
  2469. });
  2470. return fragment;
  2471. }
  2472. function jqLiteParseHTML(html, context) {
  2473. context = context || document;
  2474. var parsed;
  2475. if ((parsed = SINGLE_TAG_REGEXP.exec(html))) {
  2476. return [context.createElement(parsed[1])];
  2477. }
  2478. if ((parsed = jqLiteBuildFragment(html, context))) {
  2479. return parsed.childNodes;
  2480. }
  2481. return [];
  2482. }
  2483. /////////////////////////////////////////////
  2484. function JQLite(element) {
  2485. if (element instanceof JQLite) {
  2486. return element;
  2487. }
  2488. var argIsString;
  2489. if (isString(element)) {
  2490. element = trim(element);
  2491. argIsString = true;
  2492. }
  2493. if (!(this instanceof JQLite)) {
  2494. if (argIsString && element.charAt(0) != '<') {
  2495. throw jqLiteMinErr('nosel', 'Looking up elements via selectors is not supported by jqLite! See: http://docs.angularjs.org/api/angular.element');
  2496. }
  2497. return new JQLite(element);
  2498. }
  2499. if (argIsString) {
  2500. jqLiteAddNodes(this, jqLiteParseHTML(element));
  2501. } else {
  2502. jqLiteAddNodes(this, element);
  2503. }
  2504. }
  2505. function jqLiteClone(element) {
  2506. return element.cloneNode(true);
  2507. }
  2508. function jqLiteDealoc(element, onlyDescendants) {
  2509. if (!onlyDescendants) jqLiteRemoveData(element);
  2510. if (element.querySelectorAll) {
  2511. var descendants = element.querySelectorAll('*');
  2512. for (var i = 0, l = descendants.length; i < l; i++) {
  2513. jqLiteRemoveData(descendants[i]);
  2514. }
  2515. }
  2516. }
  2517. function jqLiteOff(element, type, fn, unsupported) {
  2518. if (isDefined(unsupported)) throw jqLiteMinErr('offargs', 'jqLite#off() does not support the `selector` argument');
  2519. var expandoStore = jqLiteExpandoStore(element);
  2520. var events = expandoStore && expandoStore.events;
  2521. var handle = expandoStore && expandoStore.handle;
  2522. if (!handle) return; //no listeners registered
  2523. if (!type) {
  2524. for (type in events) {
  2525. if (type !== '$destroy') {
  2526. removeEventListenerFn(element, type, handle);
  2527. }
  2528. delete events[type];
  2529. }
  2530. } else {
  2531. forEach(type.split(' '), function(type) {
  2532. if (isDefined(fn)) {
  2533. var listenerFns = events[type];
  2534. arrayRemove(listenerFns || [], fn);
  2535. if (listenerFns && listenerFns.length > 0) {
  2536. return;
  2537. }
  2538. }
  2539. removeEventListenerFn(element, type, handle);
  2540. delete events[type];
  2541. });
  2542. }
  2543. }
  2544. function jqLiteRemoveData(element, name) {
  2545. var expandoId = element.ng339;
  2546. var expandoStore = expandoId && jqCache[expandoId];
  2547. if (expandoStore) {
  2548. if (name) {
  2549. delete expandoStore.data[name];
  2550. return;
  2551. }
  2552. if (expandoStore.handle) {
  2553. if (expandoStore.events.$destroy) {
  2554. expandoStore.handle({}, '$destroy');
  2555. }
  2556. jqLiteOff(element);
  2557. }
  2558. delete jqCache[expandoId];
  2559. element.ng339 = undefined; // don't delete DOM expandos. IE and Chrome don't like it
  2560. }
  2561. }
  2562. function jqLiteExpandoStore(element, createIfNecessary) {
  2563. var expandoId = element.ng339,
  2564. expandoStore = expandoId && jqCache[expandoId];
  2565. if (createIfNecessary && !expandoStore) {
  2566. element.ng339 = expandoId = jqNextId();
  2567. expandoStore = jqCache[expandoId] = {events: {}, data: {}, handle: undefined};
  2568. }
  2569. return expandoStore;
  2570. }
  2571. function jqLiteData(element, key, value) {
  2572. if (jqLiteAcceptsData(element)) {
  2573. var isSimpleSetter = isDefined(value);
  2574. var isSimpleGetter = !isSimpleSetter && key && !isObject(key);
  2575. var massGetter = !key;
  2576. var expandoStore = jqLiteExpandoStore(element, !isSimpleGetter);
  2577. var data = expandoStore && expandoStore.data;
  2578. if (isSimpleSetter) { // data('key', value)
  2579. data[key] = value;
  2580. } else {
  2581. if (massGetter) { // data()
  2582. return data;
  2583. } else {
  2584. if (isSimpleGetter) { // data('key')
  2585. // don't force creation of expandoStore if it doesn't exist yet
  2586. return data && data[key];
  2587. } else { // mass-setter: data({key1: val1, key2: val2})
  2588. extend(data, key);
  2589. }
  2590. }
  2591. }
  2592. }
  2593. }
  2594. function jqLiteHasClass(element, selector) {
  2595. if (!element.getAttribute) return false;
  2596. return ((" " + (element.getAttribute('class') || '') + " ").replace(/[\n\t]/g, " ").
  2597. indexOf(" " + selector + " ") > -1);
  2598. }
  2599. function jqLiteRemoveClass(element, cssClasses) {
  2600. if (cssClasses && element.setAttribute) {
  2601. forEach(cssClasses.split(' '), function(cssClass) {
  2602. element.setAttribute('class', trim(
  2603. (" " + (element.getAttribute('class') || '') + " ")
  2604. .replace(/[\n\t]/g, " ")
  2605. .replace(" " + trim(cssClass) + " ", " "))
  2606. );
  2607. });
  2608. }
  2609. }
  2610. function jqLiteAddClass(element, cssClasses) {
  2611. if (cssClasses && element.setAttribute) {
  2612. var existingClasses = (' ' + (element.getAttribute('class') || '') + ' ')
  2613. .replace(/[\n\t]/g, " ");
  2614. forEach(cssClasses.split(' '), function(cssClass) {
  2615. cssClass = trim(cssClass);
  2616. if (existingClasses.indexOf(' ' + cssClass + ' ') === -1) {
  2617. existingClasses += cssClass + ' ';
  2618. }
  2619. });
  2620. element.setAttribute('class', trim(existingClasses));
  2621. }
  2622. }
  2623. function jqLiteAddNodes(root, elements) {
  2624. // THIS CODE IS VERY HOT. Don't make changes without benchmarking.
  2625. if (elements) {
  2626. // if a Node (the most common case)
  2627. if (elements.nodeType) {
  2628. root[root.length++] = elements;
  2629. } else {
  2630. var length = elements.length;
  2631. // if an Array or NodeList and not a Window
  2632. if (typeof length === 'number' && elements.window !== elements) {
  2633. if (length) {
  2634. for (var i = 0; i < length; i++) {
  2635. root[root.length++] = elements[i];
  2636. }
  2637. }
  2638. } else {
  2639. root[root.length++] = elements;
  2640. }
  2641. }
  2642. }
  2643. }
  2644. function jqLiteController(element, name) {
  2645. return jqLiteInheritedData(element, '$' + (name || 'ngController') + 'Controller');
  2646. }
  2647. function jqLiteInheritedData(element, name, value) {
  2648. // if element is the document object work with the html element instead
  2649. // this makes $(document).scope() possible
  2650. if (element.nodeType == NODE_TYPE_DOCUMENT) {
  2651. element = element.documentElement;
  2652. }
  2653. var names = isArray(name) ? name : [name];
  2654. while (element) {
  2655. for (var i = 0, ii = names.length; i < ii; i++) {
  2656. if (isDefined(value = jqLite.data(element, names[i]))) return value;
  2657. }
  2658. // If dealing with a document fragment node with a host element, and no parent, use the host
  2659. // element as the parent. This enables directives within a Shadow DOM or polyfilled Shadow DOM
  2660. // to lookup parent controllers.
  2661. element = element.parentNode || (element.nodeType === NODE_TYPE_DOCUMENT_FRAGMENT && element.host);
  2662. }
  2663. }
  2664. function jqLiteEmpty(element) {
  2665. jqLiteDealoc(element, true);
  2666. while (element.firstChild) {
  2667. element.removeChild(element.firstChild);
  2668. }
  2669. }
  2670. function jqLiteRemove(element, keepData) {
  2671. if (!keepData) jqLiteDealoc(element);
  2672. var parent = element.parentNode;
  2673. if (parent) parent.removeChild(element);
  2674. }
  2675. function jqLiteDocumentLoaded(action, win) {
  2676. win = win || window;
  2677. if (win.document.readyState === 'complete') {
  2678. // Force the action to be run async for consistent behaviour
  2679. // from the action's point of view
  2680. // i.e. it will definitely not be in a $apply
  2681. win.setTimeout(action);
  2682. } else {
  2683. // No need to unbind this handler as load is only ever called once
  2684. jqLite(win).on('load', action);
  2685. }
  2686. }
  2687. //////////////////////////////////////////
  2688. // Functions which are declared directly.
  2689. //////////////////////////////////////////
  2690. var JQLitePrototype = JQLite.prototype = {
  2691. ready: function(fn) {
  2692. var fired = false;
  2693. function trigger() {
  2694. if (fired) return;
  2695. fired = true;
  2696. fn();
  2697. }
  2698. // check if document is already loaded
  2699. if (document.readyState === 'complete') {
  2700. setTimeout(trigger);
  2701. } else {
  2702. this.on('DOMContentLoaded', trigger); // works for modern browsers and IE9
  2703. // we can not use jqLite since we are not done loading and jQuery could be loaded later.
  2704. // jshint -W064
  2705. JQLite(window).on('load', trigger); // fallback to window.onload for others
  2706. // jshint +W064
  2707. }
  2708. },
  2709. toString: function() {
  2710. var value = [];
  2711. forEach(this, function(e) { value.push('' + e);});
  2712. return '[' + value.join(', ') + ']';
  2713. },
  2714. eq: function(index) {
  2715. return (index >= 0) ? jqLite(this[index]) : jqLite(this[this.length + index]);
  2716. },
  2717. length: 0,
  2718. push: push,
  2719. sort: [].sort,
  2720. splice: [].splice
  2721. };
  2722. //////////////////////////////////////////
  2723. // Functions iterating getter/setters.
  2724. // these functions return self on setter and
  2725. // value on get.
  2726. //////////////////////////////////////////
  2727. var BOOLEAN_ATTR = {};
  2728. forEach('multiple,selected,checked,disabled,readOnly,required,open'.split(','), function(value) {
  2729. BOOLEAN_ATTR[lowercase(value)] = value;
  2730. });
  2731. var BOOLEAN_ELEMENTS = {};
  2732. forEach('input,select,option,textarea,button,form,details'.split(','), function(value) {
  2733. BOOLEAN_ELEMENTS[value] = true;
  2734. });
  2735. var ALIASED_ATTR = {
  2736. 'ngMinlength': 'minlength',
  2737. 'ngMaxlength': 'maxlength',
  2738. 'ngMin': 'min',
  2739. 'ngMax': 'max',
  2740. 'ngPattern': 'pattern'
  2741. };
  2742. function getBooleanAttrName(element, name) {
  2743. // check dom last since we will most likely fail on name
  2744. var booleanAttr = BOOLEAN_ATTR[name.toLowerCase()];
  2745. // booleanAttr is here twice to minimize DOM access
  2746. return booleanAttr && BOOLEAN_ELEMENTS[nodeName_(element)] && booleanAttr;
  2747. }
  2748. function getAliasedAttrName(name) {
  2749. return ALIASED_ATTR[name];
  2750. }
  2751. forEach({
  2752. data: jqLiteData,
  2753. removeData: jqLiteRemoveData,
  2754. hasData: jqLiteHasData
  2755. }, function(fn, name) {
  2756. JQLite[name] = fn;
  2757. });
  2758. forEach({
  2759. data: jqLiteData,
  2760. inheritedData: jqLiteInheritedData,
  2761. scope: function(element) {
  2762. // Can't use jqLiteData here directly so we stay compatible with jQuery!
  2763. return jqLite.data(element, '$scope') || jqLiteInheritedData(element.parentNode || element, ['$isolateScope', '$scope']);
  2764. },
  2765. isolateScope: function(element) {
  2766. // Can't use jqLiteData here directly so we stay compatible with jQuery!
  2767. return jqLite.data(element, '$isolateScope') || jqLite.data(element, '$isolateScopeNoTemplate');
  2768. },
  2769. controller: jqLiteController,
  2770. injector: function(element) {
  2771. return jqLiteInheritedData(element, '$injector');
  2772. },
  2773. removeAttr: function(element, name) {
  2774. element.removeAttribute(name);
  2775. },
  2776. hasClass: jqLiteHasClass,
  2777. css: function(element, name, value) {
  2778. name = camelCase(name);
  2779. if (isDefined(value)) {
  2780. element.style[name] = value;
  2781. } else {
  2782. return element.style[name];
  2783. }
  2784. },
  2785. attr: function(element, name, value) {
  2786. var nodeType = element.nodeType;
  2787. if (nodeType === NODE_TYPE_TEXT || nodeType === NODE_TYPE_ATTRIBUTE || nodeType === NODE_TYPE_COMMENT) {
  2788. return;
  2789. }
  2790. var lowercasedName = lowercase(name);
  2791. if (BOOLEAN_ATTR[lowercasedName]) {
  2792. if (isDefined(value)) {
  2793. if (!!value) {
  2794. element[name] = true;
  2795. element.setAttribute(name, lowercasedName);
  2796. } else {
  2797. element[name] = false;
  2798. element.removeAttribute(lowercasedName);
  2799. }
  2800. } else {
  2801. return (element[name] ||
  2802. (element.attributes.getNamedItem(name) || noop).specified)
  2803. ? lowercasedName
  2804. : undefined;
  2805. }
  2806. } else if (isDefined(value)) {
  2807. element.setAttribute(name, value);
  2808. } else if (element.getAttribute) {
  2809. // the extra argument "2" is to get the right thing for a.href in IE, see jQuery code
  2810. // some elements (e.g. Document) don't have get attribute, so return undefined
  2811. var ret = element.getAttribute(name, 2);
  2812. // normalize non-existing attributes to undefined (as jQuery)
  2813. return ret === null ? undefined : ret;
  2814. }
  2815. },
  2816. prop: function(element, name, value) {
  2817. if (isDefined(value)) {
  2818. element[name] = value;
  2819. } else {
  2820. return element[name];
  2821. }
  2822. },
  2823. text: (function() {
  2824. getText.$dv = '';
  2825. return getText;
  2826. function getText(element, value) {
  2827. if (isUndefined(value)) {
  2828. var nodeType = element.nodeType;
  2829. return (nodeType === NODE_TYPE_ELEMENT || nodeType === NODE_TYPE_TEXT) ? element.textContent : '';
  2830. }
  2831. element.textContent = value;
  2832. }
  2833. })(),
  2834. val: function(element, value) {
  2835. if (isUndefined(value)) {
  2836. if (element.multiple && nodeName_(element) === 'select') {
  2837. var result = [];
  2838. forEach(element.options, function(option) {
  2839. if (option.selected) {
  2840. result.push(option.value || option.text);
  2841. }
  2842. });
  2843. return result.length === 0 ? null : result;
  2844. }
  2845. return element.value;
  2846. }
  2847. element.value = value;
  2848. },
  2849. html: function(element, value) {
  2850. if (isUndefined(value)) {
  2851. return element.innerHTML;
  2852. }
  2853. jqLiteDealoc(element, true);
  2854. element.innerHTML = value;
  2855. },
  2856. empty: jqLiteEmpty
  2857. }, function(fn, name) {
  2858. /**
  2859. * Properties: writes return selection, reads return first value
  2860. */
  2861. JQLite.prototype[name] = function(arg1, arg2) {
  2862. var i, key;
  2863. var nodeCount = this.length;
  2864. // jqLiteHasClass has only two arguments, but is a getter-only fn, so we need to special-case it
  2865. // in a way that survives minification.
  2866. // jqLiteEmpty takes no arguments but is a setter.
  2867. if (fn !== jqLiteEmpty &&
  2868. (isUndefined((fn.length == 2 && (fn !== jqLiteHasClass && fn !== jqLiteController)) ? arg1 : arg2))) {
  2869. if (isObject(arg1)) {
  2870. // we are a write, but the object properties are the key/values
  2871. for (i = 0; i < nodeCount; i++) {
  2872. if (fn === jqLiteData) {
  2873. // data() takes the whole object in jQuery
  2874. fn(this[i], arg1);
  2875. } else {
  2876. for (key in arg1) {
  2877. fn(this[i], key, arg1[key]);
  2878. }
  2879. }
  2880. }
  2881. // return self for chaining
  2882. return this;
  2883. } else {
  2884. // we are a read, so read the first child.
  2885. // TODO: do we still need this?
  2886. var value = fn.$dv;
  2887. // Only if we have $dv do we iterate over all, otherwise it is just the first element.
  2888. var jj = (isUndefined(value)) ? Math.min(nodeCount, 1) : nodeCount;
  2889. for (var j = 0; j < jj; j++) {
  2890. var nodeValue = fn(this[j], arg1, arg2);
  2891. value = value ? value + nodeValue : nodeValue;
  2892. }
  2893. return value;
  2894. }
  2895. } else {
  2896. // we are a write, so apply to all children
  2897. for (i = 0; i < nodeCount; i++) {
  2898. fn(this[i], arg1, arg2);
  2899. }
  2900. // return self for chaining
  2901. return this;
  2902. }
  2903. };
  2904. });
  2905. function createEventHandler(element, events) {
  2906. var eventHandler = function(event, type) {
  2907. // jQuery specific api
  2908. event.isDefaultPrevented = function() {
  2909. return event.defaultPrevented;
  2910. };
  2911. var eventFns = events[type || event.type];
  2912. var eventFnsLength = eventFns ? eventFns.length : 0;
  2913. if (!eventFnsLength) return;
  2914. if (isUndefined(event.immediatePropagationStopped)) {
  2915. var originalStopImmediatePropagation = event.stopImmediatePropagation;
  2916. event.stopImmediatePropagation = function() {
  2917. event.immediatePropagationStopped = true;
  2918. if (event.stopPropagation) {
  2919. event.stopPropagation();
  2920. }
  2921. if (originalStopImmediatePropagation) {
  2922. originalStopImmediatePropagation.call(event);
  2923. }
  2924. };
  2925. }
  2926. event.isImmediatePropagationStopped = function() {
  2927. return event.immediatePropagationStopped === true;
  2928. };
  2929. // Copy event handlers in case event handlers array is modified during execution.
  2930. if ((eventFnsLength > 1)) {
  2931. eventFns = shallowCopy(eventFns);
  2932. }
  2933. for (var i = 0; i < eventFnsLength; i++) {
  2934. if (!event.isImmediatePropagationStopped()) {
  2935. eventFns[i].call(element, event);
  2936. }
  2937. }
  2938. };
  2939. // TODO: this is a hack for angularMocks/clearDataCache that makes it possible to deregister all
  2940. // events on `element`
  2941. eventHandler.elem = element;
  2942. return eventHandler;
  2943. }
  2944. //////////////////////////////////////////
  2945. // Functions iterating traversal.
  2946. // These functions chain results into a single
  2947. // selector.
  2948. //////////////////////////////////////////
  2949. forEach({
  2950. removeData: jqLiteRemoveData,
  2951. on: function jqLiteOn(element, type, fn, unsupported) {
  2952. if (isDefined(unsupported)) throw jqLiteMinErr('onargs', 'jqLite#on() does not support the `selector` or `eventData` parameters');
  2953. // Do not add event handlers to non-elements because they will not be cleaned up.
  2954. if (!jqLiteAcceptsData(element)) {
  2955. return;
  2956. }
  2957. var expandoStore = jqLiteExpandoStore(element, true);
  2958. var events = expandoStore.events;
  2959. var handle = expandoStore.handle;
  2960. if (!handle) {
  2961. handle = expandoStore.handle = createEventHandler(element, events);
  2962. }
  2963. // http://jsperf.com/string-indexof-vs-split
  2964. var types = type.indexOf(' ') >= 0 ? type.split(' ') : [type];
  2965. var i = types.length;
  2966. while (i--) {
  2967. type = types[i];
  2968. var eventFns = events[type];
  2969. if (!eventFns) {
  2970. events[type] = [];
  2971. if (type === 'mouseenter' || type === 'mouseleave') {
  2972. // Refer to jQuery's implementation of mouseenter & mouseleave
  2973. // Read about mouseenter and mouseleave:
  2974. // http://www.quirksmode.org/js/events_mouse.html#link8
  2975. jqLiteOn(element, MOUSE_EVENT_MAP[type], function(event) {
  2976. var target = this, related = event.relatedTarget;
  2977. // For mousenter/leave call the handler if related is outside the target.
  2978. // NB: No relatedTarget if the mouse left/entered the browser window
  2979. if (!related || (related !== target && !target.contains(related))) {
  2980. handle(event, type);
  2981. }
  2982. });
  2983. } else {
  2984. if (type !== '$destroy') {
  2985. addEventListenerFn(element, type, handle);
  2986. }
  2987. }
  2988. eventFns = events[type];
  2989. }
  2990. eventFns.push(fn);
  2991. }
  2992. },
  2993. off: jqLiteOff,
  2994. one: function(element, type, fn) {
  2995. element = jqLite(element);
  2996. //add the listener twice so that when it is called
  2997. //you can remove the original function and still be
  2998. //able to call element.off(ev, fn) normally
  2999. element.on(type, function onFn() {
  3000. element.off(type, fn);
  3001. element.off(type, onFn);
  3002. });
  3003. element.on(type, fn);
  3004. },
  3005. replaceWith: function(element, replaceNode) {
  3006. var index, parent = element.parentNode;
  3007. jqLiteDealoc(element);
  3008. forEach(new JQLite(replaceNode), function(node) {
  3009. if (index) {
  3010. parent.insertBefore(node, index.nextSibling);
  3011. } else {
  3012. parent.replaceChild(node, element);
  3013. }
  3014. index = node;
  3015. });
  3016. },
  3017. children: function(element) {
  3018. var children = [];
  3019. forEach(element.childNodes, function(element) {
  3020. if (element.nodeType === NODE_TYPE_ELEMENT) {
  3021. children.push(element);
  3022. }
  3023. });
  3024. return children;
  3025. },
  3026. contents: function(element) {
  3027. return element.contentDocument || element.childNodes || [];
  3028. },
  3029. append: function(element, node) {
  3030. var nodeType = element.nodeType;
  3031. if (nodeType !== NODE_TYPE_ELEMENT && nodeType !== NODE_TYPE_DOCUMENT_FRAGMENT) return;
  3032. node = new JQLite(node);
  3033. for (var i = 0, ii = node.length; i < ii; i++) {
  3034. var child = node[i];
  3035. element.appendChild(child);
  3036. }
  3037. },
  3038. prepend: function(element, node) {
  3039. if (element.nodeType === NODE_TYPE_ELEMENT) {
  3040. var index = element.firstChild;
  3041. forEach(new JQLite(node), function(child) {
  3042. element.insertBefore(child, index);
  3043. });
  3044. }
  3045. },
  3046. wrap: function(element, wrapNode) {
  3047. wrapNode = jqLite(wrapNode).eq(0).clone()[0];
  3048. var parent = element.parentNode;
  3049. if (parent) {
  3050. parent.replaceChild(wrapNode, element);
  3051. }
  3052. wrapNode.appendChild(element);
  3053. },
  3054. remove: jqLiteRemove,
  3055. detach: function(element) {
  3056. jqLiteRemove(element, true);
  3057. },
  3058. after: function(element, newElement) {
  3059. var index = element, parent = element.parentNode;
  3060. newElement = new JQLite(newElement);
  3061. for (var i = 0, ii = newElement.length; i < ii; i++) {
  3062. var node = newElement[i];
  3063. parent.insertBefore(node, index.nextSibling);
  3064. index = node;
  3065. }
  3066. },
  3067. addClass: jqLiteAddClass,
  3068. removeClass: jqLiteRemoveClass,
  3069. toggleClass: function(element, selector, condition) {
  3070. if (selector) {
  3071. forEach(selector.split(' '), function(className) {
  3072. var classCondition = condition;
  3073. if (isUndefined(classCondition)) {
  3074. classCondition = !jqLiteHasClass(element, className);
  3075. }
  3076. (classCondition ? jqLiteAddClass : jqLiteRemoveClass)(element, className);
  3077. });
  3078. }
  3079. },
  3080. parent: function(element) {
  3081. var parent = element.parentNode;
  3082. return parent && parent.nodeType !== NODE_TYPE_DOCUMENT_FRAGMENT ? parent : null;
  3083. },
  3084. next: function(element) {
  3085. return element.nextElementSibling;
  3086. },
  3087. find: function(element, selector) {
  3088. if (element.getElementsByTagName) {
  3089. return element.getElementsByTagName(selector);
  3090. } else {
  3091. return [];
  3092. }
  3093. },
  3094. clone: jqLiteClone,
  3095. triggerHandler: function(element, event, extraParameters) {
  3096. var dummyEvent, eventFnsCopy, handlerArgs;
  3097. var eventName = event.type || event;
  3098. var expandoStore = jqLiteExpandoStore(element);
  3099. var events = expandoStore && expandoStore.events;
  3100. var eventFns = events && events[eventName];
  3101. if (eventFns) {
  3102. // Create a dummy event to pass to the handlers
  3103. dummyEvent = {
  3104. preventDefault: function() { this.defaultPrevented = true; },
  3105. isDefaultPrevented: function() { return this.defaultPrevented === true; },
  3106. stopImmediatePropagation: function() { this.immediatePropagationStopped = true; },
  3107. isImmediatePropagationStopped: function() { return this.immediatePropagationStopped === true; },
  3108. stopPropagation: noop,
  3109. type: eventName,
  3110. target: element
  3111. };
  3112. // If a custom event was provided then extend our dummy event with it
  3113. if (event.type) {
  3114. dummyEvent = extend(dummyEvent, event);
  3115. }
  3116. // Copy event handlers in case event handlers array is modified during execution.
  3117. eventFnsCopy = shallowCopy(eventFns);
  3118. handlerArgs = extraParameters ? [dummyEvent].concat(extraParameters) : [dummyEvent];
  3119. forEach(eventFnsCopy, function(fn) {
  3120. if (!dummyEvent.isImmediatePropagationStopped()) {
  3121. fn.apply(element, handlerArgs);
  3122. }
  3123. });
  3124. }
  3125. }
  3126. }, function(fn, name) {
  3127. /**
  3128. * chaining functions
  3129. */
  3130. JQLite.prototype[name] = function(arg1, arg2, arg3) {
  3131. var value;
  3132. for (var i = 0, ii = this.length; i < ii; i++) {
  3133. if (isUndefined(value)) {
  3134. value = fn(this[i], arg1, arg2, arg3);
  3135. if (isDefined(value)) {
  3136. // any function which returns a value needs to be wrapped
  3137. value = jqLite(value);
  3138. }
  3139. } else {
  3140. jqLiteAddNodes(value, fn(this[i], arg1, arg2, arg3));
  3141. }
  3142. }
  3143. return isDefined(value) ? value : this;
  3144. };
  3145. // bind legacy bind/unbind to on/off
  3146. JQLite.prototype.bind = JQLite.prototype.on;
  3147. JQLite.prototype.unbind = JQLite.prototype.off;
  3148. });
  3149. // Provider for private $$jqLite service
  3150. function $$jqLiteProvider() {
  3151. this.$get = function $$jqLite() {
  3152. return extend(JQLite, {
  3153. hasClass: function(node, classes) {
  3154. if (node.attr) node = node[0];
  3155. return jqLiteHasClass(node, classes);
  3156. },
  3157. addClass: function(node, classes) {
  3158. if (node.attr) node = node[0];
  3159. return jqLiteAddClass(node, classes);
  3160. },
  3161. removeClass: function(node, classes) {
  3162. if (node.attr) node = node[0];
  3163. return jqLiteRemoveClass(node, classes);
  3164. }
  3165. });
  3166. };
  3167. }
  3168. /**
  3169. * Computes a hash of an 'obj'.
  3170. * Hash of a:
  3171. * string is string
  3172. * number is number as string
  3173. * object is either result of calling $$hashKey function on the object or uniquely generated id,
  3174. * that is also assigned to the $$hashKey property of the object.
  3175. *
  3176. * @param obj
  3177. * @returns {string} hash string such that the same input will have the same hash string.
  3178. * The resulting string key is in 'type:hashKey' format.
  3179. */
  3180. function hashKey(obj, nextUidFn) {
  3181. var key = obj && obj.$$hashKey;
  3182. if (key) {
  3183. if (typeof key === 'function') {
  3184. key = obj.$$hashKey();
  3185. }
  3186. return key;
  3187. }
  3188. var objType = typeof obj;
  3189. if (objType == 'function' || (objType == 'object' && obj !== null)) {
  3190. key = obj.$$hashKey = objType + ':' + (nextUidFn || nextUid)();
  3191. } else {
  3192. key = objType + ':' + obj;
  3193. }
  3194. return key;
  3195. }
  3196. /**
  3197. * HashMap which can use objects as keys
  3198. */
  3199. function HashMap(array, isolatedUid) {
  3200. if (isolatedUid) {
  3201. var uid = 0;
  3202. this.nextUid = function() {
  3203. return ++uid;
  3204. };
  3205. }
  3206. forEach(array, this.put, this);
  3207. }
  3208. HashMap.prototype = {
  3209. /**
  3210. * Store key value pair
  3211. * @param key key to store can be any type
  3212. * @param value value to store can be any type
  3213. */
  3214. put: function(key, value) {
  3215. this[hashKey(key, this.nextUid)] = value;
  3216. },
  3217. /**
  3218. * @param key
  3219. * @returns {Object} the value for the key
  3220. */
  3221. get: function(key) {
  3222. return this[hashKey(key, this.nextUid)];
  3223. },
  3224. /**
  3225. * Remove the key/value pair
  3226. * @param key
  3227. */
  3228. remove: function(key) {
  3229. var value = this[key = hashKey(key, this.nextUid)];
  3230. delete this[key];
  3231. return value;
  3232. }
  3233. };
  3234. var $$HashMapProvider = [function() {
  3235. this.$get = [function() {
  3236. return HashMap;
  3237. }];
  3238. }];
  3239. /**
  3240. * @ngdoc function
  3241. * @module ng
  3242. * @name angular.injector
  3243. * @kind function
  3244. *
  3245. * @description
  3246. * Creates an injector object that can be used for retrieving services as well as for
  3247. * dependency injection (see {@link guide/di dependency injection}).
  3248. *
  3249. * @param {Array.<string|Function>} modules A list of module functions or their aliases. See
  3250. * {@link angular.module}. The `ng` module must be explicitly added.
  3251. * @param {boolean=} [strictDi=false] Whether the injector should be in strict mode, which
  3252. * disallows argument name annotation inference.
  3253. * @returns {injector} Injector object. See {@link auto.$injector $injector}.
  3254. *
  3255. * @example
  3256. * Typical usage
  3257. * ```js
  3258. * // create an injector
  3259. * var $injector = angular.injector(['ng']);
  3260. *
  3261. * // use the injector to kick off your application
  3262. * // use the type inference to auto inject arguments, or use implicit injection
  3263. * $injector.invoke(function($rootScope, $compile, $document) {
  3264. * $compile($document)($rootScope);
  3265. * $rootScope.$digest();
  3266. * });
  3267. * ```
  3268. *
  3269. * Sometimes you want to get access to the injector of a currently running Angular app
  3270. * from outside Angular. Perhaps, you want to inject and compile some markup after the
  3271. * application has been bootstrapped. You can do this using the extra `injector()` added
  3272. * to JQuery/jqLite elements. See {@link angular.element}.
  3273. *
  3274. * *This is fairly rare but could be the case if a third party library is injecting the
  3275. * markup.*
  3276. *
  3277. * In the following example a new block of HTML containing a `ng-controller`
  3278. * directive is added to the end of the document body by JQuery. We then compile and link
  3279. * it into the current AngularJS scope.
  3280. *
  3281. * ```js
  3282. * var $div = $('<div ng-controller="MyCtrl">{{content.label}}</div>');
  3283. * $(document.body).append($div);
  3284. *
  3285. * angular.element(document).injector().invoke(function($compile) {
  3286. * var scope = angular.element($div).scope();
  3287. * $compile($div)(scope);
  3288. * });
  3289. * ```
  3290. */
  3291. /**
  3292. * @ngdoc module
  3293. * @name auto
  3294. * @description
  3295. *
  3296. * Implicit module which gets automatically added to each {@link auto.$injector $injector}.
  3297. */
  3298. var FN_ARGS = /^[^\(]*\(\s*([^\)]*)\)/m;
  3299. var FN_ARG_SPLIT = /,/;
  3300. var FN_ARG = /^\s*(_?)(\S+?)\1\s*$/;
  3301. var STRIP_COMMENTS = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg;
  3302. var $injectorMinErr = minErr('$injector');
  3303. function anonFn(fn) {
  3304. // For anonymous functions, showing at the very least the function signature can help in
  3305. // debugging.
  3306. var fnText = fn.toString().replace(STRIP_COMMENTS, ''),
  3307. args = fnText.match(FN_ARGS);
  3308. if (args) {
  3309. return 'function(' + (args[1] || '').replace(/[\s\r\n]+/, ' ') + ')';
  3310. }
  3311. return 'fn';
  3312. }
  3313. function annotate(fn, strictDi, name) {
  3314. var $inject,
  3315. fnText,
  3316. argDecl,
  3317. last;
  3318. if (typeof fn === 'function') {
  3319. if (!($inject = fn.$inject)) {
  3320. $inject = [];
  3321. if (fn.length) {
  3322. if (strictDi) {
  3323. if (!isString(name) || !name) {
  3324. name = fn.name || anonFn(fn);
  3325. }
  3326. throw $injectorMinErr('strictdi',
  3327. '{0} is not using explicit annotation and cannot be invoked in strict mode', name);
  3328. }
  3329. fnText = fn.toString().replace(STRIP_COMMENTS, '');
  3330. argDecl = fnText.match(FN_ARGS);
  3331. forEach(argDecl[1].split(FN_ARG_SPLIT), function(arg) {
  3332. arg.replace(FN_ARG, function(all, underscore, name) {
  3333. $inject.push(name);
  3334. });
  3335. });
  3336. }
  3337. fn.$inject = $inject;
  3338. }
  3339. } else if (isArray(fn)) {
  3340. last = fn.length - 1;
  3341. assertArgFn(fn[last], 'fn');
  3342. $inject = fn.slice(0, last);
  3343. } else {
  3344. assertArgFn(fn, 'fn', true);
  3345. }
  3346. return $inject;
  3347. }
  3348. ///////////////////////////////////////
  3349. /**
  3350. * @ngdoc service
  3351. * @name $injector
  3352. *
  3353. * @description
  3354. *
  3355. * `$injector` is used to retrieve object instances as defined by
  3356. * {@link auto.$provide provider}, instantiate types, invoke methods,
  3357. * and load modules.
  3358. *
  3359. * The following always holds true:
  3360. *
  3361. * ```js
  3362. * var $injector = angular.injector();
  3363. * expect($injector.get('$injector')).toBe($injector);
  3364. * expect($injector.invoke(function($injector) {
  3365. * return $injector;
  3366. * })).toBe($injector);
  3367. * ```
  3368. *
  3369. * # Injection Function Annotation
  3370. *
  3371. * JavaScript does not have annotations, and annotations are needed for dependency injection. The
  3372. * following are all valid ways of annotating function with injection arguments and are equivalent.
  3373. *
  3374. * ```js
  3375. * // inferred (only works if code not minified/obfuscated)
  3376. * $injector.invoke(function(serviceA){});
  3377. *
  3378. * // annotated
  3379. * function explicit(serviceA) {};
  3380. * explicit.$inject = ['serviceA'];
  3381. * $injector.invoke(explicit);
  3382. *
  3383. * // inline
  3384. * $injector.invoke(['serviceA', function(serviceA){}]);
  3385. * ```
  3386. *
  3387. * ## Inference
  3388. *
  3389. * In JavaScript calling `toString()` on a function returns the function definition. The definition
  3390. * can then be parsed and the function arguments can be extracted. This method of discovering
  3391. * annotations is disallowed when the injector is in strict mode.
  3392. * *NOTE:* This does not work with minification, and obfuscation tools since these tools change the
  3393. * argument names.
  3394. *
  3395. * ## `$inject` Annotation
  3396. * By adding an `$inject` property onto a function the injection parameters can be specified.
  3397. *
  3398. * ## Inline
  3399. * As an array of injection names, where the last item in the array is the function to call.
  3400. */
  3401. /**
  3402. * @ngdoc method
  3403. * @name $injector#get
  3404. *
  3405. * @description
  3406. * Return an instance of the service.
  3407. *
  3408. * @param {string} name The name of the instance to retrieve.
  3409. * @param {string=} caller An optional string to provide the origin of the function call for error messages.
  3410. * @return {*} The instance.
  3411. */
  3412. /**
  3413. * @ngdoc method
  3414. * @name $injector#invoke
  3415. *
  3416. * @description
  3417. * Invoke the method and supply the method arguments from the `$injector`.
  3418. *
  3419. * @param {Function|Array.<string|Function>} fn The injectable function to invoke. Function parameters are
  3420. * injected according to the {@link guide/di $inject Annotation} rules.
  3421. * @param {Object=} self The `this` for the invoked method.
  3422. * @param {Object=} locals Optional object. If preset then any argument names are read from this
  3423. * object first, before the `$injector` is consulted.
  3424. * @returns {*} the value returned by the invoked `fn` function.
  3425. */
  3426. /**
  3427. * @ngdoc method
  3428. * @name $injector#has
  3429. *
  3430. * @description
  3431. * Allows the user to query if the particular service exists.
  3432. *
  3433. * @param {string} name Name of the service to query.
  3434. * @returns {boolean} `true` if injector has given service.
  3435. */
  3436. /**
  3437. * @ngdoc method
  3438. * @name $injector#instantiate
  3439. * @description
  3440. * Create a new instance of JS type. The method takes a constructor function, invokes the new
  3441. * operator, and supplies all of the arguments to the constructor function as specified by the
  3442. * constructor annotation.
  3443. *
  3444. * @param {Function} Type Annotated constructor function.
  3445. * @param {Object=} locals Optional object. If preset then any argument names are read from this
  3446. * object first, before the `$injector` is consulted.
  3447. * @returns {Object} new instance of `Type`.
  3448. */
  3449. /**
  3450. * @ngdoc method
  3451. * @name $injector#annotate
  3452. *
  3453. * @description
  3454. * Returns an array of service names which the function is requesting for injection. This API is
  3455. * used by the injector to determine which services need to be injected into the function when the
  3456. * function is invoked. There are three ways in which the function can be annotated with the needed
  3457. * dependencies.
  3458. *
  3459. * # Argument names
  3460. *
  3461. * The simplest form is to extract the dependencies from the arguments of the function. This is done
  3462. * by converting the function into a string using `toString()` method and extracting the argument
  3463. * names.
  3464. * ```js
  3465. * // Given
  3466. * function MyController($scope, $route) {
  3467. * // ...
  3468. * }
  3469. *
  3470. * // Then
  3471. * expect(injector.annotate(MyController)).toEqual(['$scope', '$route']);
  3472. * ```
  3473. *
  3474. * You can disallow this method by using strict injection mode.
  3475. *
  3476. * This method does not work with code minification / obfuscation. For this reason the following
  3477. * annotation strategies are supported.
  3478. *
  3479. * # The `$inject` property
  3480. *
  3481. * If a function has an `$inject` property and its value is an array of strings, then the strings
  3482. * represent names of services to be injected into the function.
  3483. * ```js
  3484. * // Given
  3485. * var MyController = function(obfuscatedScope, obfuscatedRoute) {
  3486. * // ...
  3487. * }
  3488. * // Define function dependencies
  3489. * MyController['$inject'] = ['$scope', '$route'];
  3490. *
  3491. * // Then
  3492. * expect(injector.annotate(MyController)).toEqual(['$scope', '$route']);
  3493. * ```
  3494. *
  3495. * # The array notation
  3496. *
  3497. * It is often desirable to inline Injected functions and that's when setting the `$inject` property
  3498. * is very inconvenient. In these situations using the array notation to specify the dependencies in
  3499. * a way that survives minification is a better choice:
  3500. *
  3501. * ```js
  3502. * // We wish to write this (not minification / obfuscation safe)
  3503. * injector.invoke(function($compile, $rootScope) {
  3504. * // ...
  3505. * });
  3506. *
  3507. * // We are forced to write break inlining
  3508. * var tmpFn = function(obfuscatedCompile, obfuscatedRootScope) {
  3509. * // ...
  3510. * };
  3511. * tmpFn.$inject = ['$compile', '$rootScope'];
  3512. * injector.invoke(tmpFn);
  3513. *
  3514. * // To better support inline function the inline annotation is supported
  3515. * injector.invoke(['$compile', '$rootScope', function(obfCompile, obfRootScope) {
  3516. * // ...
  3517. * }]);
  3518. *
  3519. * // Therefore
  3520. * expect(injector.annotate(
  3521. * ['$compile', '$rootScope', function(obfus_$compile, obfus_$rootScope) {}])
  3522. * ).toEqual(['$compile', '$rootScope']);
  3523. * ```
  3524. *
  3525. * @param {Function|Array.<string|Function>} fn Function for which dependent service names need to
  3526. * be retrieved as described above.
  3527. *
  3528. * @param {boolean=} [strictDi=false] Disallow argument name annotation inference.
  3529. *
  3530. * @returns {Array.<string>} The names of the services which the function requires.
  3531. */
  3532. /**
  3533. * @ngdoc service
  3534. * @name $provide
  3535. *
  3536. * @description
  3537. *
  3538. * The {@link auto.$provide $provide} service has a number of methods for registering components
  3539. * with the {@link auto.$injector $injector}. Many of these functions are also exposed on
  3540. * {@link angular.Module}.
  3541. *
  3542. * An Angular **service** is a singleton object created by a **service factory**. These **service
  3543. * factories** are functions which, in turn, are created by a **service provider**.
  3544. * The **service providers** are constructor functions. When instantiated they must contain a
  3545. * property called `$get`, which holds the **service factory** function.
  3546. *
  3547. * When you request a service, the {@link auto.$injector $injector} is responsible for finding the
  3548. * correct **service provider**, instantiating it and then calling its `$get` **service factory**
  3549. * function to get the instance of the **service**.
  3550. *
  3551. * Often services have no configuration options and there is no need to add methods to the service
  3552. * provider. The provider will be no more than a constructor function with a `$get` property. For
  3553. * these cases the {@link auto.$provide $provide} service has additional helper methods to register
  3554. * services without specifying a provider.
  3555. *
  3556. * * {@link auto.$provide#provider provider(provider)} - registers a **service provider** with the
  3557. * {@link auto.$injector $injector}
  3558. * * {@link auto.$provide#constant constant(obj)} - registers a value/object that can be accessed by
  3559. * providers and services.
  3560. * * {@link auto.$provide#value value(obj)} - registers a value/object that can only be accessed by
  3561. * services, not providers.
  3562. * * {@link auto.$provide#factory factory(fn)} - registers a service **factory function**, `fn`,
  3563. * that will be wrapped in a **service provider** object, whose `$get` property will contain the
  3564. * given factory function.
  3565. * * {@link auto.$provide#service service(class)} - registers a **constructor function**, `class`
  3566. * that will be wrapped in a **service provider** object, whose `$get` property will instantiate
  3567. * a new object using the given constructor function.
  3568. *
  3569. * See the individual methods for more information and examples.
  3570. */
  3571. /**
  3572. * @ngdoc method
  3573. * @name $provide#provider
  3574. * @description
  3575. *
  3576. * Register a **provider function** with the {@link auto.$injector $injector}. Provider functions
  3577. * are constructor functions, whose instances are responsible for "providing" a factory for a
  3578. * service.
  3579. *
  3580. * Service provider names start with the name of the service they provide followed by `Provider`.
  3581. * For example, the {@link ng.$log $log} service has a provider called
  3582. * {@link ng.$logProvider $logProvider}.
  3583. *
  3584. * Service provider objects can have additional methods which allow configuration of the provider
  3585. * and its service. Importantly, you can configure what kind of service is created by the `$get`
  3586. * method, or how that service will act. For example, the {@link ng.$logProvider $logProvider} has a
  3587. * method {@link ng.$logProvider#debugEnabled debugEnabled}
  3588. * which lets you specify whether the {@link ng.$log $log} service will log debug messages to the
  3589. * console or not.
  3590. *
  3591. * @param {string} name The name of the instance. NOTE: the provider will be available under `name +
  3592. 'Provider'` key.
  3593. * @param {(Object|function())} provider If the provider is:
  3594. *
  3595. * - `Object`: then it should have a `$get` method. The `$get` method will be invoked using
  3596. * {@link auto.$injector#invoke $injector.invoke()} when an instance needs to be created.
  3597. * - `Constructor`: a new instance of the provider will be created using
  3598. * {@link auto.$injector#instantiate $injector.instantiate()}, then treated as `object`.
  3599. *
  3600. * @returns {Object} registered provider instance
  3601. * @example
  3602. *
  3603. * The following example shows how to create a simple event tracking service and register it using
  3604. * {@link auto.$provide#provider $provide.provider()}.
  3605. *
  3606. * ```js
  3607. * // Define the eventTracker provider
  3608. * function EventTrackerProvider() {
  3609. * var trackingUrl = '/track';
  3610. *
  3611. * // A provider method for configuring where the tracked events should been saved
  3612. * this.setTrackingUrl = function(url) {
  3613. * trackingUrl = url;
  3614. * };
  3615. *
  3616. * // The service factory function
  3617. * this.$get = ['$http', function($http) {
  3618. * var trackedEvents = {};
  3619. * return {
  3620. * // Call this to track an event
  3621. * event: function(event) {
  3622. * var count = trackedEvents[event] || 0;
  3623. * count += 1;
  3624. * trackedEvents[event] = count;
  3625. * return count;
  3626. * },
  3627. * // Call this to save the tracked events to the trackingUrl
  3628. * save: function() {
  3629. * $http.post(trackingUrl, trackedEvents);
  3630. * }
  3631. * };
  3632. * }];
  3633. * }
  3634. *
  3635. * describe('eventTracker', function() {
  3636. * var postSpy;
  3637. *
  3638. * beforeEach(module(function($provide) {
  3639. * // Register the eventTracker provider
  3640. * $provide.provider('eventTracker', EventTrackerProvider);
  3641. * }));
  3642. *
  3643. * beforeEach(module(function(eventTrackerProvider) {
  3644. * // Configure eventTracker provider
  3645. * eventTrackerProvider.setTrackingUrl('/custom-track');
  3646. * }));
  3647. *
  3648. * it('tracks events', inject(function(eventTracker) {
  3649. * expect(eventTracker.event('login')).toEqual(1);
  3650. * expect(eventTracker.event('login')).toEqual(2);
  3651. * }));
  3652. *
  3653. * it('saves to the tracking url', inject(function(eventTracker, $http) {
  3654. * postSpy = spyOn($http, 'post');
  3655. * eventTracker.event('login');
  3656. * eventTracker.save();
  3657. * expect(postSpy).toHaveBeenCalled();
  3658. * expect(postSpy.mostRecentCall.args[0]).not.toEqual('/track');
  3659. * expect(postSpy.mostRecentCall.args[0]).toEqual('/custom-track');
  3660. * expect(postSpy.mostRecentCall.args[1]).toEqual({ 'login': 1 });
  3661. * }));
  3662. * });
  3663. * ```
  3664. */
  3665. /**
  3666. * @ngdoc method
  3667. * @name $provide#factory
  3668. * @description
  3669. *
  3670. * Register a **service factory**, which will be called to return the service instance.
  3671. * This is short for registering a service where its provider consists of only a `$get` property,
  3672. * which is the given service factory function.
  3673. * You should use {@link auto.$provide#factory $provide.factory(getFn)} if you do not need to
  3674. * configure your service in a provider.
  3675. *
  3676. * @param {string} name The name of the instance.
  3677. * @param {Function|Array.<string|Function>} $getFn The injectable $getFn for the instance creation.
  3678. * Internally this is a short hand for `$provide.provider(name, {$get: $getFn})`.
  3679. * @returns {Object} registered provider instance
  3680. *
  3681. * @example
  3682. * Here is an example of registering a service
  3683. * ```js
  3684. * $provide.factory('ping', ['$http', function($http) {
  3685. * return function ping() {
  3686. * return $http.send('/ping');
  3687. * };
  3688. * }]);
  3689. * ```
  3690. * You would then inject and use this service like this:
  3691. * ```js
  3692. * someModule.controller('Ctrl', ['ping', function(ping) {
  3693. * ping();
  3694. * }]);
  3695. * ```
  3696. */
  3697. /**
  3698. * @ngdoc method
  3699. * @name $provide#service
  3700. * @description
  3701. *
  3702. * Register a **service constructor**, which will be invoked with `new` to create the service
  3703. * instance.
  3704. * This is short for registering a service where its provider's `$get` property is the service
  3705. * constructor function that will be used to instantiate the service instance.
  3706. *
  3707. * You should use {@link auto.$provide#service $provide.service(class)} if you define your service
  3708. * as a type/class.
  3709. *
  3710. * @param {string} name The name of the instance.
  3711. * @param {Function|Array.<string|Function>} constructor An injectable class (constructor function)
  3712. * that will be instantiated.
  3713. * @returns {Object} registered provider instance
  3714. *
  3715. * @example
  3716. * Here is an example of registering a service using
  3717. * {@link auto.$provide#service $provide.service(class)}.
  3718. * ```js
  3719. * var Ping = function($http) {
  3720. * this.$http = $http;
  3721. * };
  3722. *
  3723. * Ping.$inject = ['$http'];
  3724. *
  3725. * Ping.prototype.send = function() {
  3726. * return this.$http.get('/ping');
  3727. * };
  3728. * $provide.service('ping', Ping);
  3729. * ```
  3730. * You would then inject and use this service like this:
  3731. * ```js
  3732. * someModule.controller('Ctrl', ['ping', function(ping) {
  3733. * ping.send();
  3734. * }]);
  3735. * ```
  3736. */
  3737. /**
  3738. * @ngdoc method
  3739. * @name $provide#value
  3740. * @description
  3741. *
  3742. * Register a **value service** with the {@link auto.$injector $injector}, such as a string, a
  3743. * number, an array, an object or a function. This is short for registering a service where its
  3744. * provider's `$get` property is a factory function that takes no arguments and returns the **value
  3745. * service**.
  3746. *
  3747. * Value services are similar to constant services, except that they cannot be injected into a
  3748. * module configuration function (see {@link angular.Module#config}) but they can be overridden by
  3749. * an Angular
  3750. * {@link auto.$provide#decorator decorator}.
  3751. *
  3752. * @param {string} name The name of the instance.
  3753. * @param {*} value The value.
  3754. * @returns {Object} registered provider instance
  3755. *
  3756. * @example
  3757. * Here are some examples of creating value services.
  3758. * ```js
  3759. * $provide.value('ADMIN_USER', 'admin');
  3760. *
  3761. * $provide.value('RoleLookup', { admin: 0, writer: 1, reader: 2 });
  3762. *
  3763. * $provide.value('halfOf', function(value) {
  3764. * return value / 2;
  3765. * });
  3766. * ```
  3767. */
  3768. /**
  3769. * @ngdoc method
  3770. * @name $provide#constant
  3771. * @description
  3772. *
  3773. * Register a **constant service**, such as a string, a number, an array, an object or a function,
  3774. * with the {@link auto.$injector $injector}. Unlike {@link auto.$provide#value value} it can be
  3775. * injected into a module configuration function (see {@link angular.Module#config}) and it cannot
  3776. * be overridden by an Angular {@link auto.$provide#decorator decorator}.
  3777. *
  3778. * @param {string} name The name of the constant.
  3779. * @param {*} value The constant value.
  3780. * @returns {Object} registered instance
  3781. *
  3782. * @example
  3783. * Here a some examples of creating constants:
  3784. * ```js
  3785. * $provide.constant('SHARD_HEIGHT', 306);
  3786. *
  3787. * $provide.constant('MY_COLOURS', ['red', 'blue', 'grey']);
  3788. *
  3789. * $provide.constant('double', function(value) {
  3790. * return value * 2;
  3791. * });
  3792. * ```
  3793. */
  3794. /**
  3795. * @ngdoc method
  3796. * @name $provide#decorator
  3797. * @description
  3798. *
  3799. * Register a **service decorator** with the {@link auto.$injector $injector}. A service decorator
  3800. * intercepts the creation of a service, allowing it to override or modify the behaviour of the
  3801. * service. The object returned by the decorator may be the original service, or a new service
  3802. * object which replaces or wraps and delegates to the original service.
  3803. *
  3804. * @param {string} name The name of the service to decorate.
  3805. * @param {Function|Array.<string|Function>} decorator This function will be invoked when the service needs to be
  3806. * instantiated and should return the decorated service instance. The function is called using
  3807. * the {@link auto.$injector#invoke injector.invoke} method and is therefore fully injectable.
  3808. * Local injection arguments:
  3809. *
  3810. * * `$delegate` - The original service instance, which can be monkey patched, configured,
  3811. * decorated or delegated to.
  3812. *
  3813. * @example
  3814. * Here we decorate the {@link ng.$log $log} service to convert warnings to errors by intercepting
  3815. * calls to {@link ng.$log#error $log.warn()}.
  3816. * ```js
  3817. * $provide.decorator('$log', ['$delegate', function($delegate) {
  3818. * $delegate.warn = $delegate.error;
  3819. * return $delegate;
  3820. * }]);
  3821. * ```
  3822. */
  3823. function createInjector(modulesToLoad, strictDi) {
  3824. strictDi = (strictDi === true);
  3825. var INSTANTIATING = {},
  3826. providerSuffix = 'Provider',
  3827. path = [],
  3828. loadedModules = new HashMap([], true),
  3829. providerCache = {
  3830. $provide: {
  3831. provider: supportObject(provider),
  3832. factory: supportObject(factory),
  3833. service: supportObject(service),
  3834. value: supportObject(value),
  3835. constant: supportObject(constant),
  3836. decorator: decorator
  3837. }
  3838. },
  3839. providerInjector = (providerCache.$injector =
  3840. createInternalInjector(providerCache, function(serviceName, caller) {
  3841. if (angular.isString(caller)) {
  3842. path.push(caller);
  3843. }
  3844. throw $injectorMinErr('unpr', "Unknown provider: {0}", path.join(' <- '));
  3845. })),
  3846. instanceCache = {},
  3847. instanceInjector = (instanceCache.$injector =
  3848. createInternalInjector(instanceCache, function(serviceName, caller) {
  3849. var provider = providerInjector.get(serviceName + providerSuffix, caller);
  3850. return instanceInjector.invoke(provider.$get, provider, undefined, serviceName);
  3851. }));
  3852. forEach(loadModules(modulesToLoad), function(fn) { if (fn) instanceInjector.invoke(fn); });
  3853. return instanceInjector;
  3854. ////////////////////////////////////
  3855. // $provider
  3856. ////////////////////////////////////
  3857. function supportObject(delegate) {
  3858. return function(key, value) {
  3859. if (isObject(key)) {
  3860. forEach(key, reverseParams(delegate));
  3861. } else {
  3862. return delegate(key, value);
  3863. }
  3864. };
  3865. }
  3866. function provider(name, provider_) {
  3867. assertNotHasOwnProperty(name, 'service');
  3868. if (isFunction(provider_) || isArray(provider_)) {
  3869. provider_ = providerInjector.instantiate(provider_);
  3870. }
  3871. if (!provider_.$get) {
  3872. throw $injectorMinErr('pget', "Provider '{0}' must define $get factory method.", name);
  3873. }
  3874. return providerCache[name + providerSuffix] = provider_;
  3875. }
  3876. function enforceReturnValue(name, factory) {
  3877. return function enforcedReturnValue() {
  3878. var result = instanceInjector.invoke(factory, this);
  3879. if (isUndefined(result)) {
  3880. throw $injectorMinErr('undef', "Provider '{0}' must return a value from $get factory method.", name);
  3881. }
  3882. return result;
  3883. };
  3884. }
  3885. function factory(name, factoryFn, enforce) {
  3886. return provider(name, {
  3887. $get: enforce !== false ? enforceReturnValue(name, factoryFn) : factoryFn
  3888. });
  3889. }
  3890. function service(name, constructor) {
  3891. return factory(name, ['$injector', function($injector) {
  3892. return $injector.instantiate(constructor);
  3893. }]);
  3894. }
  3895. function value(name, val) { return factory(name, valueFn(val), false); }
  3896. function constant(name, value) {
  3897. assertNotHasOwnProperty(name, 'constant');
  3898. providerCache[name] = value;
  3899. instanceCache[name] = value;
  3900. }
  3901. function decorator(serviceName, decorFn) {
  3902. var origProvider = providerInjector.get(serviceName + providerSuffix),
  3903. orig$get = origProvider.$get;
  3904. origProvider.$get = function() {
  3905. var origInstance = instanceInjector.invoke(orig$get, origProvider);
  3906. return instanceInjector.invoke(decorFn, null, {$delegate: origInstance});
  3907. };
  3908. }
  3909. ////////////////////////////////////
  3910. // Module Loading
  3911. ////////////////////////////////////
  3912. function loadModules(modulesToLoad) {
  3913. assertArg(isUndefined(modulesToLoad) || isArray(modulesToLoad), 'modulesToLoad', 'not an array');
  3914. var runBlocks = [], moduleFn;
  3915. forEach(modulesToLoad, function(module) {
  3916. if (loadedModules.get(module)) return;
  3917. loadedModules.put(module, true);
  3918. function runInvokeQueue(queue) {
  3919. var i, ii;
  3920. for (i = 0, ii = queue.length; i < ii; i++) {
  3921. var invokeArgs = queue[i],
  3922. provider = providerInjector.get(invokeArgs[0]);
  3923. provider[invokeArgs[1]].apply(provider, invokeArgs[2]);
  3924. }
  3925. }
  3926. try {
  3927. if (isString(module)) {
  3928. moduleFn = angularModule(module);
  3929. runBlocks = runBlocks.concat(loadModules(moduleFn.requires)).concat(moduleFn._runBlocks);
  3930. runInvokeQueue(moduleFn._invokeQueue);
  3931. runInvokeQueue(moduleFn._configBlocks);
  3932. } else if (isFunction(module)) {
  3933. runBlocks.push(providerInjector.invoke(module));
  3934. } else if (isArray(module)) {
  3935. runBlocks.push(providerInjector.invoke(module));
  3936. } else {
  3937. assertArgFn(module, 'module');
  3938. }
  3939. } catch (e) {
  3940. if (isArray(module)) {
  3941. module = module[module.length - 1];
  3942. }
  3943. if (e.message && e.stack && e.stack.indexOf(e.message) == -1) {
  3944. // Safari & FF's stack traces don't contain error.message content
  3945. // unlike those of Chrome and IE
  3946. // So if stack doesn't contain message, we create a new string that contains both.
  3947. // Since error.stack is read-only in Safari, I'm overriding e and not e.stack here.
  3948. /* jshint -W022 */
  3949. e = e.message + '\n' + e.stack;
  3950. }
  3951. throw $injectorMinErr('modulerr', "Failed to instantiate module {0} due to:\n{1}",
  3952. module, e.stack || e.message || e);
  3953. }
  3954. });
  3955. return runBlocks;
  3956. }
  3957. ////////////////////////////////////
  3958. // internal Injector
  3959. ////////////////////////////////////
  3960. function createInternalInjector(cache, factory) {
  3961. function getService(serviceName, caller) {
  3962. if (cache.hasOwnProperty(serviceName)) {
  3963. if (cache[serviceName] === INSTANTIATING) {
  3964. throw $injectorMinErr('cdep', 'Circular dependency found: {0}',
  3965. serviceName + ' <- ' + path.join(' <- '));
  3966. }
  3967. return cache[serviceName];
  3968. } else {
  3969. try {
  3970. path.unshift(serviceName);
  3971. cache[serviceName] = INSTANTIATING;
  3972. return cache[serviceName] = factory(serviceName, caller);
  3973. } catch (err) {
  3974. if (cache[serviceName] === INSTANTIATING) {
  3975. delete cache[serviceName];
  3976. }
  3977. throw err;
  3978. } finally {
  3979. path.shift();
  3980. }
  3981. }
  3982. }
  3983. function invoke(fn, self, locals, serviceName) {
  3984. if (typeof locals === 'string') {
  3985. serviceName = locals;
  3986. locals = null;
  3987. }
  3988. var args = [],
  3989. $inject = createInjector.$$annotate(fn, strictDi, serviceName),
  3990. length, i,
  3991. key;
  3992. for (i = 0, length = $inject.length; i < length; i++) {
  3993. key = $inject[i];
  3994. if (typeof key !== 'string') {
  3995. throw $injectorMinErr('itkn',
  3996. 'Incorrect injection token! Expected service name as string, got {0}', key);
  3997. }
  3998. args.push(
  3999. locals && locals.hasOwnProperty(key)
  4000. ? locals[key]
  4001. : getService(key, serviceName)
  4002. );
  4003. }
  4004. if (isArray(fn)) {
  4005. fn = fn[length];
  4006. }
  4007. // http://jsperf.com/angularjs-invoke-apply-vs-switch
  4008. // #5388
  4009. return fn.apply(self, args);
  4010. }
  4011. function instantiate(Type, locals, serviceName) {
  4012. // Check if Type is annotated and use just the given function at n-1 as parameter
  4013. // e.g. someModule.factory('greeter', ['$window', function(renamed$window) {}]);
  4014. // Object creation: http://jsperf.com/create-constructor/2
  4015. var instance = Object.create((isArray(Type) ? Type[Type.length - 1] : Type).prototype || null);
  4016. var returnedValue = invoke(Type, instance, locals, serviceName);
  4017. return isObject(returnedValue) || isFunction(returnedValue) ? returnedValue : instance;
  4018. }
  4019. return {
  4020. invoke: invoke,
  4021. instantiate: instantiate,
  4022. get: getService,
  4023. annotate: createInjector.$$annotate,
  4024. has: function(name) {
  4025. return providerCache.hasOwnProperty(name + providerSuffix) || cache.hasOwnProperty(name);
  4026. }
  4027. };
  4028. }
  4029. }
  4030. createInjector.$$annotate = annotate;
  4031. /**
  4032. * @ngdoc provider
  4033. * @name $anchorScrollProvider
  4034. *
  4035. * @description
  4036. * Use `$anchorScrollProvider` to disable automatic scrolling whenever
  4037. * {@link ng.$location#hash $location.hash()} changes.
  4038. */
  4039. function $AnchorScrollProvider() {
  4040. var autoScrollingEnabled = true;
  4041. /**
  4042. * @ngdoc method
  4043. * @name $anchorScrollProvider#disableAutoScrolling
  4044. *
  4045. * @description
  4046. * By default, {@link ng.$anchorScroll $anchorScroll()} will automatically detect changes to
  4047. * {@link ng.$location#hash $location.hash()} and scroll to the element matching the new hash.<br />
  4048. * Use this method to disable automatic scrolling.
  4049. *
  4050. * If automatic scrolling is disabled, one must explicitly call
  4051. * {@link ng.$anchorScroll $anchorScroll()} in order to scroll to the element related to the
  4052. * current hash.
  4053. */
  4054. this.disableAutoScrolling = function() {
  4055. autoScrollingEnabled = false;
  4056. };
  4057. /**
  4058. * @ngdoc service
  4059. * @name $anchorScroll
  4060. * @kind function
  4061. * @requires $window
  4062. * @requires $location
  4063. * @requires $rootScope
  4064. *
  4065. * @description
  4066. * When called, it scrolls to the element related to the specified `hash` or (if omitted) to the
  4067. * current value of {@link ng.$location#hash $location.hash()}, according to the rules specified
  4068. * in the
  4069. * [HTML5 spec](http://dev.w3.org/html5/spec/Overview.html#the-indicated-part-of-the-document).
  4070. *
  4071. * It also watches the {@link ng.$location#hash $location.hash()} and automatically scrolls to
  4072. * match any anchor whenever it changes. This can be disabled by calling
  4073. * {@link ng.$anchorScrollProvider#disableAutoScrolling $anchorScrollProvider.disableAutoScrolling()}.
  4074. *
  4075. * Additionally, you can use its {@link ng.$anchorScroll#yOffset yOffset} property to specify a
  4076. * vertical scroll-offset (either fixed or dynamic).
  4077. *
  4078. * @param {string=} hash The hash specifying the element to scroll to. If omitted, the value of
  4079. * {@link ng.$location#hash $location.hash()} will be used.
  4080. *
  4081. * @property {(number|function|jqLite)} yOffset
  4082. * If set, specifies a vertical scroll-offset. This is often useful when there are fixed
  4083. * positioned elements at the top of the page, such as navbars, headers etc.
  4084. *
  4085. * `yOffset` can be specified in various ways:
  4086. * - **number**: A fixed number of pixels to be used as offset.<br /><br />
  4087. * - **function**: A getter function called everytime `$anchorScroll()` is executed. Must return
  4088. * a number representing the offset (in pixels).<br /><br />
  4089. * - **jqLite**: A jqLite/jQuery element to be used for specifying the offset. The distance from
  4090. * the top of the page to the element's bottom will be used as offset.<br />
  4091. * **Note**: The element will be taken into account only as long as its `position` is set to
  4092. * `fixed`. This option is useful, when dealing with responsive navbars/headers that adjust
  4093. * their height and/or positioning according to the viewport's size.
  4094. *
  4095. * <br />
  4096. * <div class="alert alert-warning">
  4097. * In order for `yOffset` to work properly, scrolling should take place on the document's root and
  4098. * not some child element.
  4099. * </div>
  4100. *
  4101. * @example
  4102. <example module="anchorScrollExample">
  4103. <file name="index.html">
  4104. <div id="scrollArea" ng-controller="ScrollController">
  4105. <a ng-click="gotoBottom()">Go to bottom</a>
  4106. <a id="bottom"></a> You're at the bottom!
  4107. </div>
  4108. </file>
  4109. <file name="script.js">
  4110. angular.module('anchorScrollExample', [])
  4111. .controller('ScrollController', ['$scope', '$location', '$anchorScroll',
  4112. function ($scope, $location, $anchorScroll) {
  4113. $scope.gotoBottom = function() {
  4114. // set the location.hash to the id of
  4115. // the element you wish to scroll to.
  4116. $location.hash('bottom');
  4117. // call $anchorScroll()
  4118. $anchorScroll();
  4119. };
  4120. }]);
  4121. </file>
  4122. <file name="style.css">
  4123. #scrollArea {
  4124. height: 280px;
  4125. overflow: auto;
  4126. }
  4127. #bottom {
  4128. display: block;
  4129. margin-top: 2000px;
  4130. }
  4131. </file>
  4132. </example>
  4133. *
  4134. * <hr />
  4135. * The example below illustrates the use of a vertical scroll-offset (specified as a fixed value).
  4136. * See {@link ng.$anchorScroll#yOffset $anchorScroll.yOffset} for more details.
  4137. *
  4138. * @example
  4139. <example module="anchorScrollOffsetExample">
  4140. <file name="index.html">
  4141. <div class="fixed-header" ng-controller="headerCtrl">
  4142. <a href="" ng-click="gotoAnchor(x)" ng-repeat="x in [1,2,3,4,5]">
  4143. Go to anchor {{x}}
  4144. </a>
  4145. </div>
  4146. <div id="anchor{{x}}" class="anchor" ng-repeat="x in [1,2,3,4,5]">
  4147. Anchor {{x}} of 5
  4148. </div>
  4149. </file>
  4150. <file name="script.js">
  4151. angular.module('anchorScrollOffsetExample', [])
  4152. .run(['$anchorScroll', function($anchorScroll) {
  4153. $anchorScroll.yOffset = 50; // always scroll by 50 extra pixels
  4154. }])
  4155. .controller('headerCtrl', ['$anchorScroll', '$location', '$scope',
  4156. function ($anchorScroll, $location, $scope) {
  4157. $scope.gotoAnchor = function(x) {
  4158. var newHash = 'anchor' + x;
  4159. if ($location.hash() !== newHash) {
  4160. // set the $location.hash to `newHash` and
  4161. // $anchorScroll will automatically scroll to it
  4162. $location.hash('anchor' + x);
  4163. } else {
  4164. // call $anchorScroll() explicitly,
  4165. // since $location.hash hasn't changed
  4166. $anchorScroll();
  4167. }
  4168. };
  4169. }
  4170. ]);
  4171. </file>
  4172. <file name="style.css">
  4173. body {
  4174. padding-top: 50px;
  4175. }
  4176. .anchor {
  4177. border: 2px dashed DarkOrchid;
  4178. padding: 10px 10px 200px 10px;
  4179. }
  4180. .fixed-header {
  4181. background-color: rgba(0, 0, 0, 0.2);
  4182. height: 50px;
  4183. position: fixed;
  4184. top: 0; left: 0; right: 0;
  4185. }
  4186. .fixed-header > a {
  4187. display: inline-block;
  4188. margin: 5px 15px;
  4189. }
  4190. </file>
  4191. </example>
  4192. */
  4193. this.$get = ['$window', '$location', '$rootScope', function($window, $location, $rootScope) {
  4194. var document = $window.document;
  4195. // Helper function to get first anchor from a NodeList
  4196. // (using `Array#some()` instead of `angular#forEach()` since it's more performant
  4197. // and working in all supported browsers.)
  4198. function getFirstAnchor(list) {
  4199. var result = null;
  4200. Array.prototype.some.call(list, function(element) {
  4201. if (nodeName_(element) === 'a') {
  4202. result = element;
  4203. return true;
  4204. }
  4205. });
  4206. return result;
  4207. }
  4208. function getYOffset() {
  4209. var offset = scroll.yOffset;
  4210. if (isFunction(offset)) {
  4211. offset = offset();
  4212. } else if (isElement(offset)) {
  4213. var elem = offset[0];
  4214. var style = $window.getComputedStyle(elem);
  4215. if (style.position !== 'fixed') {
  4216. offset = 0;
  4217. } else {
  4218. offset = elem.getBoundingClientRect().bottom;
  4219. }
  4220. } else if (!isNumber(offset)) {
  4221. offset = 0;
  4222. }
  4223. return offset;
  4224. }
  4225. function scrollTo(elem) {
  4226. if (elem) {
  4227. elem.scrollIntoView();
  4228. var offset = getYOffset();
  4229. if (offset) {
  4230. // `offset` is the number of pixels we should scroll UP in order to align `elem` properly.
  4231. // This is true ONLY if the call to `elem.scrollIntoView()` initially aligns `elem` at the
  4232. // top of the viewport.
  4233. //
  4234. // IF the number of pixels from the top of `elem` to the end of the page's content is less
  4235. // than the height of the viewport, then `elem.scrollIntoView()` will align the `elem` some
  4236. // way down the page.
  4237. //
  4238. // This is often the case for elements near the bottom of the page.
  4239. //
  4240. // In such cases we do not need to scroll the whole `offset` up, just the difference between
  4241. // the top of the element and the offset, which is enough to align the top of `elem` at the
  4242. // desired position.
  4243. var elemTop = elem.getBoundingClientRect().top;
  4244. $window.scrollBy(0, elemTop - offset);
  4245. }
  4246. } else {
  4247. $window.scrollTo(0, 0);
  4248. }
  4249. }
  4250. function scroll(hash) {
  4251. hash = isString(hash) ? hash : $location.hash();
  4252. var elm;
  4253. // empty hash, scroll to the top of the page
  4254. if (!hash) scrollTo(null);
  4255. // element with given id
  4256. else if ((elm = document.getElementById(hash))) scrollTo(elm);
  4257. // first anchor with given name :-D
  4258. else if ((elm = getFirstAnchor(document.getElementsByName(hash)))) scrollTo(elm);
  4259. // no element and hash == 'top', scroll to the top of the page
  4260. else if (hash === 'top') scrollTo(null);
  4261. }
  4262. // does not scroll when user clicks on anchor link that is currently on
  4263. // (no url change, no $location.hash() change), browser native does scroll
  4264. if (autoScrollingEnabled) {
  4265. $rootScope.$watch(function autoScrollWatch() {return $location.hash();},
  4266. function autoScrollWatchAction(newVal, oldVal) {
  4267. // skip the initial scroll if $location.hash is empty
  4268. if (newVal === oldVal && newVal === '') return;
  4269. jqLiteDocumentLoaded(function() {
  4270. $rootScope.$evalAsync(scroll);
  4271. });
  4272. });
  4273. }
  4274. return scroll;
  4275. }];
  4276. }
  4277. var $animateMinErr = minErr('$animate');
  4278. var ELEMENT_NODE = 1;
  4279. var NG_ANIMATE_CLASSNAME = 'ng-animate';
  4280. function mergeClasses(a,b) {
  4281. if (!a && !b) return '';
  4282. if (!a) return b;
  4283. if (!b) return a;
  4284. if (isArray(a)) a = a.join(' ');
  4285. if (isArray(b)) b = b.join(' ');
  4286. return a + ' ' + b;
  4287. }
  4288. function extractElementNode(element) {
  4289. for (var i = 0; i < element.length; i++) {
  4290. var elm = element[i];
  4291. if (elm.nodeType === ELEMENT_NODE) {
  4292. return elm;
  4293. }
  4294. }
  4295. }
  4296. function splitClasses(classes) {
  4297. if (isString(classes)) {
  4298. classes = classes.split(' ');
  4299. }
  4300. // Use createMap() to prevent class assumptions involving property names in
  4301. // Object.prototype
  4302. var obj = createMap();
  4303. forEach(classes, function(klass) {
  4304. // sometimes the split leaves empty string values
  4305. // incase extra spaces were applied to the options
  4306. if (klass.length) {
  4307. obj[klass] = true;
  4308. }
  4309. });
  4310. return obj;
  4311. }
  4312. // if any other type of options value besides an Object value is
  4313. // passed into the $animate.method() animation then this helper code
  4314. // will be run which will ignore it. While this patch is not the
  4315. // greatest solution to this, a lot of existing plugins depend on
  4316. // $animate to either call the callback (< 1.2) or return a promise
  4317. // that can be changed. This helper function ensures that the options
  4318. // are wiped clean incase a callback function is provided.
  4319. function prepareAnimateOptions(options) {
  4320. return isObject(options)
  4321. ? options
  4322. : {};
  4323. }
  4324. var $$CoreAnimateRunnerProvider = function() {
  4325. this.$get = ['$q', '$$rAF', function($q, $$rAF) {
  4326. function AnimateRunner() {}
  4327. AnimateRunner.all = noop;
  4328. AnimateRunner.chain = noop;
  4329. AnimateRunner.prototype = {
  4330. end: noop,
  4331. cancel: noop,
  4332. resume: noop,
  4333. pause: noop,
  4334. complete: noop,
  4335. then: function(pass, fail) {
  4336. return $q(function(resolve) {
  4337. $$rAF(function() {
  4338. resolve();
  4339. });
  4340. }).then(pass, fail);
  4341. }
  4342. };
  4343. return AnimateRunner;
  4344. }];
  4345. };
  4346. // this is prefixed with Core since it conflicts with
  4347. // the animateQueueProvider defined in ngAnimate/animateQueue.js
  4348. var $$CoreAnimateQueueProvider = function() {
  4349. var postDigestQueue = new HashMap();
  4350. var postDigestElements = [];
  4351. this.$get = ['$$AnimateRunner', '$rootScope',
  4352. function($$AnimateRunner, $rootScope) {
  4353. return {
  4354. enabled: noop,
  4355. on: noop,
  4356. off: noop,
  4357. pin: noop,
  4358. push: function(element, event, options, domOperation) {
  4359. domOperation && domOperation();
  4360. options = options || {};
  4361. options.from && element.css(options.from);
  4362. options.to && element.css(options.to);
  4363. if (options.addClass || options.removeClass) {
  4364. addRemoveClassesPostDigest(element, options.addClass, options.removeClass);
  4365. }
  4366. return new $$AnimateRunner(); // jshint ignore:line
  4367. }
  4368. };
  4369. function updateData(data, classes, value) {
  4370. var changed = false;
  4371. if (classes) {
  4372. classes = isString(classes) ? classes.split(' ') :
  4373. isArray(classes) ? classes : [];
  4374. forEach(classes, function(className) {
  4375. if (className) {
  4376. changed = true;
  4377. data[className] = value;
  4378. }
  4379. });
  4380. }
  4381. return changed;
  4382. }
  4383. function handleCSSClassChanges() {
  4384. forEach(postDigestElements, function(element) {
  4385. var data = postDigestQueue.get(element);
  4386. if (data) {
  4387. var existing = splitClasses(element.attr('class'));
  4388. var toAdd = '';
  4389. var toRemove = '';
  4390. forEach(data, function(status, className) {
  4391. var hasClass = !!existing[className];
  4392. if (status !== hasClass) {
  4393. if (status) {
  4394. toAdd += (toAdd.length ? ' ' : '') + className;
  4395. } else {
  4396. toRemove += (toRemove.length ? ' ' : '') + className;
  4397. }
  4398. }
  4399. });
  4400. forEach(element, function(elm) {
  4401. toAdd && jqLiteAddClass(elm, toAdd);
  4402. toRemove && jqLiteRemoveClass(elm, toRemove);
  4403. });
  4404. postDigestQueue.remove(element);
  4405. }
  4406. });
  4407. postDigestElements.length = 0;
  4408. }
  4409. function addRemoveClassesPostDigest(element, add, remove) {
  4410. var data = postDigestQueue.get(element) || {};
  4411. var classesAdded = updateData(data, add, true);
  4412. var classesRemoved = updateData(data, remove, false);
  4413. if (classesAdded || classesRemoved) {
  4414. postDigestQueue.put(element, data);
  4415. postDigestElements.push(element);
  4416. if (postDigestElements.length === 1) {
  4417. $rootScope.$$postDigest(handleCSSClassChanges);
  4418. }
  4419. }
  4420. }
  4421. }];
  4422. };
  4423. /**
  4424. * @ngdoc provider
  4425. * @name $animateProvider
  4426. *
  4427. * @description
  4428. * Default implementation of $animate that doesn't perform any animations, instead just
  4429. * synchronously performs DOM updates and resolves the returned runner promise.
  4430. *
  4431. * In order to enable animations the `ngAnimate` module has to be loaded.
  4432. *
  4433. * To see the functional implementation check out `src/ngAnimate/animate.js`.
  4434. */
  4435. var $AnimateProvider = ['$provide', function($provide) {
  4436. var provider = this;
  4437. this.$$registeredAnimations = Object.create(null);
  4438. /**
  4439. * @ngdoc method
  4440. * @name $animateProvider#register
  4441. *
  4442. * @description
  4443. * Registers a new injectable animation factory function. The factory function produces the
  4444. * animation object which contains callback functions for each event that is expected to be
  4445. * animated.
  4446. *
  4447. * * `eventFn`: `function(element, ... , doneFunction, options)`
  4448. * The element to animate, the `doneFunction` and the options fed into the animation. Depending
  4449. * on the type of animation additional arguments will be injected into the animation function. The
  4450. * list below explains the function signatures for the different animation methods:
  4451. *
  4452. * - setClass: function(element, addedClasses, removedClasses, doneFunction, options)
  4453. * - addClass: function(element, addedClasses, doneFunction, options)
  4454. * - removeClass: function(element, removedClasses, doneFunction, options)
  4455. * - enter, leave, move: function(element, doneFunction, options)
  4456. * - animate: function(element, fromStyles, toStyles, doneFunction, options)
  4457. *
  4458. * Make sure to trigger the `doneFunction` once the animation is fully complete.
  4459. *
  4460. * ```js
  4461. * return {
  4462. * //enter, leave, move signature
  4463. * eventFn : function(element, done, options) {
  4464. * //code to run the animation
  4465. * //once complete, then run done()
  4466. * return function endFunction(wasCancelled) {
  4467. * //code to cancel the animation
  4468. * }
  4469. * }
  4470. * }
  4471. * ```
  4472. *
  4473. * @param {string} name The name of the animation (this is what the class-based CSS value will be compared to).
  4474. * @param {Function} factory The factory function that will be executed to return the animation
  4475. * object.
  4476. */
  4477. this.register = function(name, factory) {
  4478. if (name && name.charAt(0) !== '.') {
  4479. throw $animateMinErr('notcsel', "Expecting class selector starting with '.' got '{0}'.", name);
  4480. }
  4481. var key = name + '-animation';
  4482. provider.$$registeredAnimations[name.substr(1)] = key;
  4483. $provide.factory(key, factory);
  4484. };
  4485. /**
  4486. * @ngdoc method
  4487. * @name $animateProvider#classNameFilter
  4488. *
  4489. * @description
  4490. * Sets and/or returns the CSS class regular expression that is checked when performing
  4491. * an animation. Upon bootstrap the classNameFilter value is not set at all and will
  4492. * therefore enable $animate to attempt to perform an animation on any element that is triggered.
  4493. * When setting the `classNameFilter` value, animations will only be performed on elements
  4494. * that successfully match the filter expression. This in turn can boost performance
  4495. * for low-powered devices as well as applications containing a lot of structural operations.
  4496. * @param {RegExp=} expression The className expression which will be checked against all animations
  4497. * @return {RegExp} The current CSS className expression value. If null then there is no expression value
  4498. */
  4499. this.classNameFilter = function(expression) {
  4500. if (arguments.length === 1) {
  4501. this.$$classNameFilter = (expression instanceof RegExp) ? expression : null;
  4502. if (this.$$classNameFilter) {
  4503. var reservedRegex = new RegExp("(\\s+|\\/)" + NG_ANIMATE_CLASSNAME + "(\\s+|\\/)");
  4504. if (reservedRegex.test(this.$$classNameFilter.toString())) {
  4505. throw $animateMinErr('nongcls','$animateProvider.classNameFilter(regex) prohibits accepting a regex value which matches/contains the "{0}" CSS class.', NG_ANIMATE_CLASSNAME);
  4506. }
  4507. }
  4508. }
  4509. return this.$$classNameFilter;
  4510. };
  4511. this.$get = ['$$animateQueue', function($$animateQueue) {
  4512. function domInsert(element, parentElement, afterElement) {
  4513. // if for some reason the previous element was removed
  4514. // from the dom sometime before this code runs then let's
  4515. // just stick to using the parent element as the anchor
  4516. if (afterElement) {
  4517. var afterNode = extractElementNode(afterElement);
  4518. if (afterNode && !afterNode.parentNode && !afterNode.previousElementSibling) {
  4519. afterElement = null;
  4520. }
  4521. }
  4522. afterElement ? afterElement.after(element) : parentElement.prepend(element);
  4523. }
  4524. /**
  4525. * @ngdoc service
  4526. * @name $animate
  4527. * @description The $animate service exposes a series of DOM utility methods that provide support
  4528. * for animation hooks. The default behavior is the application of DOM operations, however,
  4529. * when an animation is detected (and animations are enabled), $animate will do the heavy lifting
  4530. * to ensure that animation runs with the triggered DOM operation.
  4531. *
  4532. * By default $animate doesn't trigger an animations. This is because the `ngAnimate` module isn't
  4533. * included and only when it is active then the animation hooks that `$animate` triggers will be
  4534. * functional. Once active then all structural `ng-` directives will trigger animations as they perform
  4535. * their DOM-related operations (enter, leave and move). Other directives such as `ngClass`,
  4536. * `ngShow`, `ngHide` and `ngMessages` also provide support for animations.
  4537. *
  4538. * It is recommended that the`$animate` service is always used when executing DOM-related procedures within directives.
  4539. *
  4540. * To learn more about enabling animation support, click here to visit the
  4541. * {@link ngAnimate ngAnimate module page}.
  4542. */
  4543. return {
  4544. // we don't call it directly since non-existant arguments may
  4545. // be interpreted as null within the sub enabled function
  4546. /**
  4547. *
  4548. * @ngdoc method
  4549. * @name $animate#on
  4550. * @kind function
  4551. * @description Sets up an event listener to fire whenever the animation event (enter, leave, move, etc...)
  4552. * has fired on the given element or among any of its children. Once the listener is fired, the provided callback
  4553. * is fired with the following params:
  4554. *
  4555. * ```js
  4556. * $animate.on('enter', container,
  4557. * function callback(element, phase) {
  4558. * // cool we detected an enter animation within the container
  4559. * }
  4560. * );
  4561. * ```
  4562. *
  4563. * @param {string} event the animation event that will be captured (e.g. enter, leave, move, addClass, removeClass, etc...)
  4564. * @param {DOMElement} container the container element that will capture each of the animation events that are fired on itself
  4565. * as well as among its children
  4566. * @param {Function} callback the callback function that will be fired when the listener is triggered
  4567. *
  4568. * The arguments present in the callback function are:
  4569. * * `element` - The captured DOM element that the animation was fired on.
  4570. * * `phase` - The phase of the animation. The two possible phases are **start** (when the animation starts) and **close** (when it ends).
  4571. */
  4572. on: $$animateQueue.on,
  4573. /**
  4574. *
  4575. * @ngdoc method
  4576. * @name $animate#off
  4577. * @kind function
  4578. * @description Deregisters an event listener based on the event which has been associated with the provided element. This method
  4579. * can be used in three different ways depending on the arguments:
  4580. *
  4581. * ```js
  4582. * // remove all the animation event listeners listening for `enter`
  4583. * $animate.off('enter');
  4584. *
  4585. * // remove all the animation event listeners listening for `enter` on the given element and its children
  4586. * $animate.off('enter', container);
  4587. *
  4588. * // remove the event listener function provided by `listenerFn` that is set
  4589. * // to listen for `enter` on the given `element` as well as its children
  4590. * $animate.off('enter', container, callback);
  4591. * ```
  4592. *
  4593. * @param {string} event the animation event (e.g. enter, leave, move, addClass, removeClass, etc...)
  4594. * @param {DOMElement=} container the container element the event listener was placed on
  4595. * @param {Function=} callback the callback function that was registered as the listener
  4596. */
  4597. off: $$animateQueue.off,
  4598. /**
  4599. * @ngdoc method
  4600. * @name $animate#pin
  4601. * @kind function
  4602. * @description Associates the provided element with a host parent element to allow the element to be animated even if it exists
  4603. * outside of the DOM structure of the Angular application. By doing so, any animation triggered via `$animate` can be issued on the
  4604. * element despite being outside the realm of the application or within another application. Say for example if the application
  4605. * was bootstrapped on an element that is somewhere inside of the `<body>` tag, but we wanted to allow for an element to be situated
  4606. * as a direct child of `document.body`, then this can be achieved by pinning the element via `$animate.pin(element)`. Keep in mind
  4607. * that calling `$animate.pin(element, parentElement)` will not actually insert into the DOM anywhere; it will just create the association.
  4608. *
  4609. * Note that this feature is only active when the `ngAnimate` module is used.
  4610. *
  4611. * @param {DOMElement} element the external element that will be pinned
  4612. * @param {DOMElement} parentElement the host parent element that will be associated with the external element
  4613. */
  4614. pin: $$animateQueue.pin,
  4615. /**
  4616. *
  4617. * @ngdoc method
  4618. * @name $animate#enabled
  4619. * @kind function
  4620. * @description Used to get and set whether animations are enabled or not on the entire application or on an element and its children. This
  4621. * function can be called in four ways:
  4622. *
  4623. * ```js
  4624. * // returns true or false
  4625. * $animate.enabled();
  4626. *
  4627. * // changes the enabled state for all animations
  4628. * $animate.enabled(false);
  4629. * $animate.enabled(true);
  4630. *
  4631. * // returns true or false if animations are enabled for an element
  4632. * $animate.enabled(element);
  4633. *
  4634. * // changes the enabled state for an element and its children
  4635. * $animate.enabled(element, true);
  4636. * $animate.enabled(element, false);
  4637. * ```
  4638. *
  4639. * @param {DOMElement=} element the element that will be considered for checking/setting the enabled state
  4640. * @param {boolean=} enabled whether or not the animations will be enabled for the element
  4641. *
  4642. * @return {boolean} whether or not animations are enabled
  4643. */
  4644. enabled: $$animateQueue.enabled,
  4645. /**
  4646. * @ngdoc method
  4647. * @name $animate#cancel
  4648. * @kind function
  4649. * @description Cancels the provided animation.
  4650. *
  4651. * @param {Promise} animationPromise The animation promise that is returned when an animation is started.
  4652. */
  4653. cancel: function(runner) {
  4654. runner.end && runner.end();
  4655. },
  4656. /**
  4657. *
  4658. * @ngdoc method
  4659. * @name $animate#enter
  4660. * @kind function
  4661. * @description Inserts the element into the DOM either after the `after` element (if provided) or
  4662. * as the first child within the `parent` element and then triggers an animation.
  4663. * A promise is returned that will be resolved during the next digest once the animation
  4664. * has completed.
  4665. *
  4666. * @param {DOMElement} element the element which will be inserted into the DOM
  4667. * @param {DOMElement} parent the parent element which will append the element as
  4668. * a child (so long as the after element is not present)
  4669. * @param {DOMElement=} after the sibling element after which the element will be appended
  4670. * @param {object=} options an optional collection of options/styles that will be applied to the element
  4671. *
  4672. * @return {Promise} the animation callback promise
  4673. */
  4674. enter: function(element, parent, after, options) {
  4675. parent = parent && jqLite(parent);
  4676. after = after && jqLite(after);
  4677. parent = parent || after.parent();
  4678. domInsert(element, parent, after);
  4679. return $$animateQueue.push(element, 'enter', prepareAnimateOptions(options));
  4680. },
  4681. /**
  4682. *
  4683. * @ngdoc method
  4684. * @name $animate#move
  4685. * @kind function
  4686. * @description Inserts (moves) the element into its new position in the DOM either after
  4687. * the `after` element (if provided) or as the first child within the `parent` element
  4688. * and then triggers an animation. A promise is returned that will be resolved
  4689. * during the next digest once the animation has completed.
  4690. *
  4691. * @param {DOMElement} element the element which will be moved into the new DOM position
  4692. * @param {DOMElement} parent the parent element which will append the element as
  4693. * a child (so long as the after element is not present)
  4694. * @param {DOMElement=} after the sibling element after which the element will be appended
  4695. * @param {object=} options an optional collection of options/styles that will be applied to the element
  4696. *
  4697. * @return {Promise} the animation callback promise
  4698. */
  4699. move: function(element, parent, after, options) {
  4700. parent = parent && jqLite(parent);
  4701. after = after && jqLite(after);
  4702. parent = parent || after.parent();
  4703. domInsert(element, parent, after);
  4704. return $$animateQueue.push(element, 'move', prepareAnimateOptions(options));
  4705. },
  4706. /**
  4707. * @ngdoc method
  4708. * @name $animate#leave
  4709. * @kind function
  4710. * @description Triggers an animation and then removes the element from the DOM.
  4711. * When the function is called a promise is returned that will be resolved during the next
  4712. * digest once the animation has completed.
  4713. *
  4714. * @param {DOMElement} element the element which will be removed from the DOM
  4715. * @param {object=} options an optional collection of options/styles that will be applied to the element
  4716. *
  4717. * @return {Promise} the animation callback promise
  4718. */
  4719. leave: function(element, options) {
  4720. return $$animateQueue.push(element, 'leave', prepareAnimateOptions(options), function() {
  4721. element.remove();
  4722. });
  4723. },
  4724. /**
  4725. * @ngdoc method
  4726. * @name $animate#addClass
  4727. * @kind function
  4728. *
  4729. * @description Triggers an addClass animation surrounding the addition of the provided CSS class(es). Upon
  4730. * execution, the addClass operation will only be handled after the next digest and it will not trigger an
  4731. * animation if element already contains the CSS class or if the class is removed at a later step.
  4732. * Note that class-based animations are treated differently compared to structural animations
  4733. * (like enter, move and leave) since the CSS classes may be added/removed at different points
  4734. * depending if CSS or JavaScript animations are used.
  4735. *
  4736. * @param {DOMElement} element the element which the CSS classes will be applied to
  4737. * @param {string} className the CSS class(es) that will be added (multiple classes are separated via spaces)
  4738. * @param {object=} options an optional collection of options/styles that will be applied to the element
  4739. *
  4740. * @return {Promise} the animation callback promise
  4741. */
  4742. addClass: function(element, className, options) {
  4743. options = prepareAnimateOptions(options);
  4744. options.addClass = mergeClasses(options.addclass, className);
  4745. return $$animateQueue.push(element, 'addClass', options);
  4746. },
  4747. /**
  4748. * @ngdoc method
  4749. * @name $animate#removeClass
  4750. * @kind function
  4751. *
  4752. * @description Triggers a removeClass animation surrounding the removal of the provided CSS class(es). Upon
  4753. * execution, the removeClass operation will only be handled after the next digest and it will not trigger an
  4754. * animation if element does not contain the CSS class or if the class is added at a later step.
  4755. * Note that class-based animations are treated differently compared to structural animations
  4756. * (like enter, move and leave) since the CSS classes may be added/removed at different points
  4757. * depending if CSS or JavaScript animations are used.
  4758. *
  4759. * @param {DOMElement} element the element which the CSS classes will be applied to
  4760. * @param {string} className the CSS class(es) that will be removed (multiple classes are separated via spaces)
  4761. * @param {object=} options an optional collection of options/styles that will be applied to the element
  4762. *
  4763. * @return {Promise} the animation callback promise
  4764. */
  4765. removeClass: function(element, className, options) {
  4766. options = prepareAnimateOptions(options);
  4767. options.removeClass = mergeClasses(options.removeClass, className);
  4768. return $$animateQueue.push(element, 'removeClass', options);
  4769. },
  4770. /**
  4771. * @ngdoc method
  4772. * @name $animate#setClass
  4773. * @kind function
  4774. *
  4775. * @description Performs both the addition and removal of a CSS classes on an element and (during the process)
  4776. * triggers an animation surrounding the class addition/removal. Much like `$animate.addClass` and
  4777. * `$animate.removeClass`, `setClass` will only evaluate the classes being added/removed once a digest has
  4778. * passed. Note that class-based animations are treated differently compared to structural animations
  4779. * (like enter, move and leave) since the CSS classes may be added/removed at different points
  4780. * depending if CSS or JavaScript animations are used.
  4781. *
  4782. * @param {DOMElement} element the element which the CSS classes will be applied to
  4783. * @param {string} add the CSS class(es) that will be added (multiple classes are separated via spaces)
  4784. * @param {string} remove the CSS class(es) that will be removed (multiple classes are separated via spaces)
  4785. * @param {object=} options an optional collection of options/styles that will be applied to the element
  4786. *
  4787. * @return {Promise} the animation callback promise
  4788. */
  4789. setClass: function(element, add, remove, options) {
  4790. options = prepareAnimateOptions(options);
  4791. options.addClass = mergeClasses(options.addClass, add);
  4792. options.removeClass = mergeClasses(options.removeClass, remove);
  4793. return $$animateQueue.push(element, 'setClass', options);
  4794. },
  4795. /**
  4796. * @ngdoc method
  4797. * @name $animate#animate
  4798. * @kind function
  4799. *
  4800. * @description Performs an inline animation on the element which applies the provided to and from CSS styles to the element.
  4801. * If any detected CSS transition, keyframe or JavaScript matches the provided className value then the animation will take
  4802. * on the provided styles. For example, if a transition animation is set for the given className then the provided from and
  4803. * to styles will be applied alongside the given transition. If a JavaScript animation is detected then the provided styles
  4804. * will be given in as function paramters into the `animate` method (or as apart of the `options` parameter).
  4805. *
  4806. * @param {DOMElement} element the element which the CSS styles will be applied to
  4807. * @param {object} from the from (starting) CSS styles that will be applied to the element and across the animation.
  4808. * @param {object} to the to (destination) CSS styles that will be applied to the element and across the animation.
  4809. * @param {string=} className an optional CSS class that will be applied to the element for the duration of the animation. If
  4810. * this value is left as empty then a CSS class of `ng-inline-animate` will be applied to the element.
  4811. * (Note that if no animation is detected then this value will not be appplied to the element.)
  4812. * @param {object=} options an optional collection of options/styles that will be applied to the element
  4813. *
  4814. * @return {Promise} the animation callback promise
  4815. */
  4816. animate: function(element, from, to, className, options) {
  4817. options = prepareAnimateOptions(options);
  4818. options.from = options.from ? extend(options.from, from) : from;
  4819. options.to = options.to ? extend(options.to, to) : to;
  4820. className = className || 'ng-inline-animate';
  4821. options.tempClasses = mergeClasses(options.tempClasses, className);
  4822. return $$animateQueue.push(element, 'animate', options);
  4823. }
  4824. };
  4825. }];
  4826. }];
  4827. /**
  4828. * @ngdoc service
  4829. * @name $animateCss
  4830. * @kind object
  4831. *
  4832. * @description
  4833. * This is the core version of `$animateCss`. By default, only when the `ngAnimate` is included,
  4834. * then the `$animateCss` service will actually perform animations.
  4835. *
  4836. * Click here {@link ngAnimate.$animateCss to read the documentation for $animateCss}.
  4837. */
  4838. var $CoreAnimateCssProvider = function() {
  4839. this.$get = ['$$rAF', '$q', function($$rAF, $q) {
  4840. var RAFPromise = function() {};
  4841. RAFPromise.prototype = {
  4842. done: function(cancel) {
  4843. this.defer && this.defer[cancel === true ? 'reject' : 'resolve']();
  4844. },
  4845. end: function() {
  4846. this.done();
  4847. },
  4848. cancel: function() {
  4849. this.done(true);
  4850. },
  4851. getPromise: function() {
  4852. if (!this.defer) {
  4853. this.defer = $q.defer();
  4854. }
  4855. return this.defer.promise;
  4856. },
  4857. then: function(f1,f2) {
  4858. return this.getPromise().then(f1,f2);
  4859. },
  4860. 'catch': function(f1) {
  4861. return this.getPromise()['catch'](f1);
  4862. },
  4863. 'finally': function(f1) {
  4864. return this.getPromise()['finally'](f1);
  4865. }
  4866. };
  4867. return function(element, options) {
  4868. if (options.from) {
  4869. element.css(options.from);
  4870. options.from = null;
  4871. }
  4872. var closed, runner = new RAFPromise();
  4873. return {
  4874. start: run,
  4875. end: run
  4876. };
  4877. function run() {
  4878. $$rAF(function() {
  4879. close();
  4880. if (!closed) {
  4881. runner.done();
  4882. }
  4883. closed = true;
  4884. });
  4885. return runner;
  4886. }
  4887. function close() {
  4888. if (options.addClass) {
  4889. element.addClass(options.addClass);
  4890. options.addClass = null;
  4891. }
  4892. if (options.removeClass) {
  4893. element.removeClass(options.removeClass);
  4894. options.removeClass = null;
  4895. }
  4896. if (options.to) {
  4897. element.css(options.to);
  4898. options.to = null;
  4899. }
  4900. }
  4901. };
  4902. }];
  4903. };
  4904. /* global stripHash: true */
  4905. /**
  4906. * ! This is a private undocumented service !
  4907. *
  4908. * @name $browser
  4909. * @requires $log
  4910. * @description
  4911. * This object has two goals:
  4912. *
  4913. * - hide all the global state in the browser caused by the window object
  4914. * - abstract away all the browser specific features and inconsistencies
  4915. *
  4916. * For tests we provide {@link ngMock.$browser mock implementation} of the `$browser`
  4917. * service, which can be used for convenient testing of the application without the interaction with
  4918. * the real browser apis.
  4919. */
  4920. /**
  4921. * @param {object} window The global window object.
  4922. * @param {object} document jQuery wrapped document.
  4923. * @param {object} $log window.console or an object with the same interface.
  4924. * @param {object} $sniffer $sniffer service
  4925. */
  4926. function Browser(window, document, $log, $sniffer) {
  4927. var self = this,
  4928. rawDocument = document[0],
  4929. location = window.location,
  4930. history = window.history,
  4931. setTimeout = window.setTimeout,
  4932. clearTimeout = window.clearTimeout,
  4933. pendingDeferIds = {};
  4934. self.isMock = false;
  4935. var outstandingRequestCount = 0;
  4936. var outstandingRequestCallbacks = [];
  4937. // TODO(vojta): remove this temporary api
  4938. self.$$completeOutstandingRequest = completeOutstandingRequest;
  4939. self.$$incOutstandingRequestCount = function() { outstandingRequestCount++; };
  4940. /**
  4941. * Executes the `fn` function(supports currying) and decrements the `outstandingRequestCallbacks`
  4942. * counter. If the counter reaches 0, all the `outstandingRequestCallbacks` are executed.
  4943. */
  4944. function completeOutstandingRequest(fn) {
  4945. try {
  4946. fn.apply(null, sliceArgs(arguments, 1));
  4947. } finally {
  4948. outstandingRequestCount--;
  4949. if (outstandingRequestCount === 0) {
  4950. while (outstandingRequestCallbacks.length) {
  4951. try {
  4952. outstandingRequestCallbacks.pop()();
  4953. } catch (e) {
  4954. $log.error(e);
  4955. }
  4956. }
  4957. }
  4958. }
  4959. }
  4960. function getHash(url) {
  4961. var index = url.indexOf('#');
  4962. return index === -1 ? '' : url.substr(index);
  4963. }
  4964. /**
  4965. * @private
  4966. * Note: this method is used only by scenario runner
  4967. * TODO(vojta): prefix this method with $$ ?
  4968. * @param {function()} callback Function that will be called when no outstanding request
  4969. */
  4970. self.notifyWhenNoOutstandingRequests = function(callback) {
  4971. if (outstandingRequestCount === 0) {
  4972. callback();
  4973. } else {
  4974. outstandingRequestCallbacks.push(callback);
  4975. }
  4976. };
  4977. //////////////////////////////////////////////////////////////
  4978. // URL API
  4979. //////////////////////////////////////////////////////////////
  4980. var cachedState, lastHistoryState,
  4981. lastBrowserUrl = location.href,
  4982. baseElement = document.find('base'),
  4983. pendingLocation = null;
  4984. cacheState();
  4985. lastHistoryState = cachedState;
  4986. /**
  4987. * @name $browser#url
  4988. *
  4989. * @description
  4990. * GETTER:
  4991. * Without any argument, this method just returns current value of location.href.
  4992. *
  4993. * SETTER:
  4994. * With at least one argument, this method sets url to new value.
  4995. * If html5 history api supported, pushState/replaceState is used, otherwise
  4996. * location.href/location.replace is used.
  4997. * Returns its own instance to allow chaining
  4998. *
  4999. * NOTE: this api is intended for use only by the $location service. Please use the
  5000. * {@link ng.$location $location service} to change url.
  5001. *
  5002. * @param {string} url New url (when used as setter)
  5003. * @param {boolean=} replace Should new url replace current history record?
  5004. * @param {object=} state object to use with pushState/replaceState
  5005. */
  5006. self.url = function(url, replace, state) {
  5007. // In modern browsers `history.state` is `null` by default; treating it separately
  5008. // from `undefined` would cause `$browser.url('/foo')` to change `history.state`
  5009. // to undefined via `pushState`. Instead, let's change `undefined` to `null` here.
  5010. if (isUndefined(state)) {
  5011. state = null;
  5012. }
  5013. // Android Browser BFCache causes location, history reference to become stale.
  5014. if (location !== window.location) location = window.location;
  5015. if (history !== window.history) history = window.history;
  5016. // setter
  5017. if (url) {
  5018. var sameState = lastHistoryState === state;
  5019. // Don't change anything if previous and current URLs and states match. This also prevents
  5020. // IE<10 from getting into redirect loop when in LocationHashbangInHtml5Url mode.
  5021. // See https://github.com/angular/angular.js/commit/ffb2701
  5022. if (lastBrowserUrl === url && (!$sniffer.history || sameState)) {
  5023. return self;
  5024. }
  5025. var sameBase = lastBrowserUrl && stripHash(lastBrowserUrl) === stripHash(url);
  5026. lastBrowserUrl = url;
  5027. lastHistoryState = state;
  5028. // Don't use history API if only the hash changed
  5029. // due to a bug in IE10/IE11 which leads
  5030. // to not firing a `hashchange` nor `popstate` event
  5031. // in some cases (see #9143).
  5032. if ($sniffer.history && (!sameBase || !sameState)) {
  5033. history[replace ? 'replaceState' : 'pushState'](state, '', url);
  5034. cacheState();
  5035. // Do the assignment again so that those two variables are referentially identical.
  5036. lastHistoryState = cachedState;
  5037. } else {
  5038. if (!sameBase || pendingLocation) {
  5039. pendingLocation = url;
  5040. }
  5041. if (replace) {
  5042. location.replace(url);
  5043. } else if (!sameBase) {
  5044. location.href = url;
  5045. } else {
  5046. location.hash = getHash(url);
  5047. }
  5048. if (location.href !== url) {
  5049. pendingLocation = url;
  5050. }
  5051. }
  5052. return self;
  5053. // getter
  5054. } else {
  5055. // - pendingLocation is needed as browsers don't allow to read out
  5056. // the new location.href if a reload happened or if there is a bug like in iOS 9 (see
  5057. // https://openradar.appspot.com/22186109).
  5058. // - the replacement is a workaround for https://bugzilla.mozilla.org/show_bug.cgi?id=407172
  5059. return pendingLocation || location.href.replace(/%27/g,"'");
  5060. }
  5061. };
  5062. /**
  5063. * @name $browser#state
  5064. *
  5065. * @description
  5066. * This method is a getter.
  5067. *
  5068. * Return history.state or null if history.state is undefined.
  5069. *
  5070. * @returns {object} state
  5071. */
  5072. self.state = function() {
  5073. return cachedState;
  5074. };
  5075. var urlChangeListeners = [],
  5076. urlChangeInit = false;
  5077. function cacheStateAndFireUrlChange() {
  5078. pendingLocation = null;
  5079. cacheState();
  5080. fireUrlChange();
  5081. }
  5082. function getCurrentState() {
  5083. try {
  5084. return history.state;
  5085. } catch (e) {
  5086. // MSIE can reportedly throw when there is no state (UNCONFIRMED).
  5087. }
  5088. }
  5089. // This variable should be used *only* inside the cacheState function.
  5090. var lastCachedState = null;
  5091. function cacheState() {
  5092. // This should be the only place in $browser where `history.state` is read.
  5093. cachedState = getCurrentState();
  5094. cachedState = isUndefined(cachedState) ? null : cachedState;
  5095. // Prevent callbacks fo fire twice if both hashchange & popstate were fired.
  5096. if (equals(cachedState, lastCachedState)) {
  5097. cachedState = lastCachedState;
  5098. }
  5099. lastCachedState = cachedState;
  5100. }
  5101. function fireUrlChange() {
  5102. if (lastBrowserUrl === self.url() && lastHistoryState === cachedState) {
  5103. return;
  5104. }
  5105. lastBrowserUrl = self.url();
  5106. lastHistoryState = cachedState;
  5107. forEach(urlChangeListeners, function(listener) {
  5108. listener(self.url(), cachedState);
  5109. });
  5110. }
  5111. /**
  5112. * @name $browser#onUrlChange
  5113. *
  5114. * @description
  5115. * Register callback function that will be called, when url changes.
  5116. *
  5117. * It's only called when the url is changed from outside of angular:
  5118. * - user types different url into address bar
  5119. * - user clicks on history (forward/back) button
  5120. * - user clicks on a link
  5121. *
  5122. * It's not called when url is changed by $browser.url() method
  5123. *
  5124. * The listener gets called with new url as parameter.
  5125. *
  5126. * NOTE: this api is intended for use only by the $location service. Please use the
  5127. * {@link ng.$location $location service} to monitor url changes in angular apps.
  5128. *
  5129. * @param {function(string)} listener Listener function to be called when url changes.
  5130. * @return {function(string)} Returns the registered listener fn - handy if the fn is anonymous.
  5131. */
  5132. self.onUrlChange = function(callback) {
  5133. // TODO(vojta): refactor to use node's syntax for events
  5134. if (!urlChangeInit) {
  5135. // We listen on both (hashchange/popstate) when available, as some browsers (e.g. Opera)
  5136. // don't fire popstate when user change the address bar and don't fire hashchange when url
  5137. // changed by push/replaceState
  5138. // html5 history api - popstate event
  5139. if ($sniffer.history) jqLite(window).on('popstate', cacheStateAndFireUrlChange);
  5140. // hashchange event
  5141. jqLite(window).on('hashchange', cacheStateAndFireUrlChange);
  5142. urlChangeInit = true;
  5143. }
  5144. urlChangeListeners.push(callback);
  5145. return callback;
  5146. };
  5147. /**
  5148. * @private
  5149. * Remove popstate and hashchange handler from window.
  5150. *
  5151. * NOTE: this api is intended for use only by $rootScope.
  5152. */
  5153. self.$$applicationDestroyed = function() {
  5154. jqLite(window).off('hashchange popstate', cacheStateAndFireUrlChange);
  5155. };
  5156. /**
  5157. * Checks whether the url has changed outside of Angular.
  5158. * Needs to be exported to be able to check for changes that have been done in sync,
  5159. * as hashchange/popstate events fire in async.
  5160. */
  5161. self.$$checkUrlChange = fireUrlChange;
  5162. //////////////////////////////////////////////////////////////
  5163. // Misc API
  5164. //////////////////////////////////////////////////////////////
  5165. /**
  5166. * @name $browser#baseHref
  5167. *
  5168. * @description
  5169. * Returns current <base href>
  5170. * (always relative - without domain)
  5171. *
  5172. * @returns {string} The current base href
  5173. */
  5174. self.baseHref = function() {
  5175. var href = baseElement.attr('href');
  5176. return href ? href.replace(/^(https?\:)?\/\/[^\/]*/, '') : '';
  5177. };
  5178. /**
  5179. * @name $browser#defer
  5180. * @param {function()} fn A function, who's execution should be deferred.
  5181. * @param {number=} [delay=0] of milliseconds to defer the function execution.
  5182. * @returns {*} DeferId that can be used to cancel the task via `$browser.defer.cancel()`.
  5183. *
  5184. * @description
  5185. * Executes a fn asynchronously via `setTimeout(fn, delay)`.
  5186. *
  5187. * Unlike when calling `setTimeout` directly, in test this function is mocked and instead of using
  5188. * `setTimeout` in tests, the fns are queued in an array, which can be programmatically flushed
  5189. * via `$browser.defer.flush()`.
  5190. *
  5191. */
  5192. self.defer = function(fn, delay) {
  5193. var timeoutId;
  5194. outstandingRequestCount++;
  5195. timeoutId = setTimeout(function() {
  5196. delete pendingDeferIds[timeoutId];
  5197. completeOutstandingRequest(fn);
  5198. }, delay || 0);
  5199. pendingDeferIds[timeoutId] = true;
  5200. return timeoutId;
  5201. };
  5202. /**
  5203. * @name $browser#defer.cancel
  5204. *
  5205. * @description
  5206. * Cancels a deferred task identified with `deferId`.
  5207. *
  5208. * @param {*} deferId Token returned by the `$browser.defer` function.
  5209. * @returns {boolean} Returns `true` if the task hasn't executed yet and was successfully
  5210. * canceled.
  5211. */
  5212. self.defer.cancel = function(deferId) {
  5213. if (pendingDeferIds[deferId]) {
  5214. delete pendingDeferIds[deferId];
  5215. clearTimeout(deferId);
  5216. completeOutstandingRequest(noop);
  5217. return true;
  5218. }
  5219. return false;
  5220. };
  5221. }
  5222. function $BrowserProvider() {
  5223. this.$get = ['$window', '$log', '$sniffer', '$document',
  5224. function($window, $log, $sniffer, $document) {
  5225. return new Browser($window, $document, $log, $sniffer);
  5226. }];
  5227. }
  5228. /**
  5229. * @ngdoc service
  5230. * @name $cacheFactory
  5231. *
  5232. * @description
  5233. * Factory that constructs {@link $cacheFactory.Cache Cache} objects and gives access to
  5234. * them.
  5235. *
  5236. * ```js
  5237. *
  5238. * var cache = $cacheFactory('cacheId');
  5239. * expect($cacheFactory.get('cacheId')).toBe(cache);
  5240. * expect($cacheFactory.get('noSuchCacheId')).not.toBeDefined();
  5241. *
  5242. * cache.put("key", "value");
  5243. * cache.put("another key", "another value");
  5244. *
  5245. * // We've specified no options on creation
  5246. * expect(cache.info()).toEqual({id: 'cacheId', size: 2});
  5247. *
  5248. * ```
  5249. *
  5250. *
  5251. * @param {string} cacheId Name or id of the newly created cache.
  5252. * @param {object=} options Options object that specifies the cache behavior. Properties:
  5253. *
  5254. * - `{number=}` `capacity` — turns the cache into LRU cache.
  5255. *
  5256. * @returns {object} Newly created cache object with the following set of methods:
  5257. *
  5258. * - `{object}` `info()` — Returns id, size, and options of cache.
  5259. * - `{{*}}` `put({string} key, {*} value)` — Puts a new key-value pair into the cache and returns
  5260. * it.
  5261. * - `{{*}}` `get({string} key)` — Returns cached value for `key` or undefined for cache miss.
  5262. * - `{void}` `remove({string} key)` — Removes a key-value pair from the cache.
  5263. * - `{void}` `removeAll()` — Removes all cached values.
  5264. * - `{void}` `destroy()` — Removes references to this cache from $cacheFactory.
  5265. *
  5266. * @example
  5267. <example module="cacheExampleApp">
  5268. <file name="index.html">
  5269. <div ng-controller="CacheController">
  5270. <input ng-model="newCacheKey" placeholder="Key">
  5271. <input ng-model="newCacheValue" placeholder="Value">
  5272. <button ng-click="put(newCacheKey, newCacheValue)">Cache</button>
  5273. <p ng-if="keys.length">Cached Values</p>
  5274. <div ng-repeat="key in keys">
  5275. <span ng-bind="key"></span>
  5276. <span>: </span>
  5277. <b ng-bind="cache.get(key)"></b>
  5278. </div>
  5279. <p>Cache Info</p>
  5280. <div ng-repeat="(key, value) in cache.info()">
  5281. <span ng-bind="key"></span>
  5282. <span>: </span>
  5283. <b ng-bind="value"></b>
  5284. </div>
  5285. </div>
  5286. </file>
  5287. <file name="script.js">
  5288. angular.module('cacheExampleApp', []).
  5289. controller('CacheController', ['$scope', '$cacheFactory', function($scope, $cacheFactory) {
  5290. $scope.keys = [];
  5291. $scope.cache = $cacheFactory('cacheId');
  5292. $scope.put = function(key, value) {
  5293. if (isUndefined($scope.cache.get(key))) {
  5294. $scope.keys.push(key);
  5295. }
  5296. $scope.cache.put(key, isUndefined(value) ? null : value);
  5297. };
  5298. }]);
  5299. </file>
  5300. <file name="style.css">
  5301. p {
  5302. margin: 10px 0 3px;
  5303. }
  5304. </file>
  5305. </example>
  5306. */
  5307. function $CacheFactoryProvider() {
  5308. this.$get = function() {
  5309. var caches = {};
  5310. function cacheFactory(cacheId, options) {
  5311. if (cacheId in caches) {
  5312. throw minErr('$cacheFactory')('iid', "CacheId '{0}' is already taken!", cacheId);
  5313. }
  5314. var size = 0,
  5315. stats = extend({}, options, {id: cacheId}),
  5316. data = {},
  5317. capacity = (options && options.capacity) || Number.MAX_VALUE,
  5318. lruHash = {},
  5319. freshEnd = null,
  5320. staleEnd = null;
  5321. /**
  5322. * @ngdoc type
  5323. * @name $cacheFactory.Cache
  5324. *
  5325. * @description
  5326. * A cache object used to store and retrieve data, primarily used by
  5327. * {@link $http $http} and the {@link ng.directive:script script} directive to cache
  5328. * templates and other data.
  5329. *
  5330. * ```js
  5331. * angular.module('superCache')
  5332. * .factory('superCache', ['$cacheFactory', function($cacheFactory) {
  5333. * return $cacheFactory('super-cache');
  5334. * }]);
  5335. * ```
  5336. *
  5337. * Example test:
  5338. *
  5339. * ```js
  5340. * it('should behave like a cache', inject(function(superCache) {
  5341. * superCache.put('key', 'value');
  5342. * superCache.put('another key', 'another value');
  5343. *
  5344. * expect(superCache.info()).toEqual({
  5345. * id: 'super-cache',
  5346. * size: 2
  5347. * });
  5348. *
  5349. * superCache.remove('another key');
  5350. * expect(superCache.get('another key')).toBeUndefined();
  5351. *
  5352. * superCache.removeAll();
  5353. * expect(superCache.info()).toEqual({
  5354. * id: 'super-cache',
  5355. * size: 0
  5356. * });
  5357. * }));
  5358. * ```
  5359. */
  5360. return caches[cacheId] = {
  5361. /**
  5362. * @ngdoc method
  5363. * @name $cacheFactory.Cache#put
  5364. * @kind function
  5365. *
  5366. * @description
  5367. * Inserts a named entry into the {@link $cacheFactory.Cache Cache} object to be
  5368. * retrieved later, and incrementing the size of the cache if the key was not already
  5369. * present in the cache. If behaving like an LRU cache, it will also remove stale
  5370. * entries from the set.
  5371. *
  5372. * It will not insert undefined values into the cache.
  5373. *
  5374. * @param {string} key the key under which the cached data is stored.
  5375. * @param {*} value the value to store alongside the key. If it is undefined, the key
  5376. * will not be stored.
  5377. * @returns {*} the value stored.
  5378. */
  5379. put: function(key, value) {
  5380. if (isUndefined(value)) return;
  5381. if (capacity < Number.MAX_VALUE) {
  5382. var lruEntry = lruHash[key] || (lruHash[key] = {key: key});
  5383. refresh(lruEntry);
  5384. }
  5385. if (!(key in data)) size++;
  5386. data[key] = value;
  5387. if (size > capacity) {
  5388. this.remove(staleEnd.key);
  5389. }
  5390. return value;
  5391. },
  5392. /**
  5393. * @ngdoc method
  5394. * @name $cacheFactory.Cache#get
  5395. * @kind function
  5396. *
  5397. * @description
  5398. * Retrieves named data stored in the {@link $cacheFactory.Cache Cache} object.
  5399. *
  5400. * @param {string} key the key of the data to be retrieved
  5401. * @returns {*} the value stored.
  5402. */
  5403. get: function(key) {
  5404. if (capacity < Number.MAX_VALUE) {
  5405. var lruEntry = lruHash[key];
  5406. if (!lruEntry) return;
  5407. refresh(lruEntry);
  5408. }
  5409. return data[key];
  5410. },
  5411. /**
  5412. * @ngdoc method
  5413. * @name $cacheFactory.Cache#remove
  5414. * @kind function
  5415. *
  5416. * @description
  5417. * Removes an entry from the {@link $cacheFactory.Cache Cache} object.
  5418. *
  5419. * @param {string} key the key of the entry to be removed
  5420. */
  5421. remove: function(key) {
  5422. if (capacity < Number.MAX_VALUE) {
  5423. var lruEntry = lruHash[key];
  5424. if (!lruEntry) return;
  5425. if (lruEntry == freshEnd) freshEnd = lruEntry.p;
  5426. if (lruEntry == staleEnd) staleEnd = lruEntry.n;
  5427. link(lruEntry.n,lruEntry.p);
  5428. delete lruHash[key];
  5429. }
  5430. delete data[key];
  5431. size--;
  5432. },
  5433. /**
  5434. * @ngdoc method
  5435. * @name $cacheFactory.Cache#removeAll
  5436. * @kind function
  5437. *
  5438. * @description
  5439. * Clears the cache object of any entries.
  5440. */
  5441. removeAll: function() {
  5442. data = {};
  5443. size = 0;
  5444. lruHash = {};
  5445. freshEnd = staleEnd = null;
  5446. },
  5447. /**
  5448. * @ngdoc method
  5449. * @name $cacheFactory.Cache#destroy
  5450. * @kind function
  5451. *
  5452. * @description
  5453. * Destroys the {@link $cacheFactory.Cache Cache} object entirely,
  5454. * removing it from the {@link $cacheFactory $cacheFactory} set.
  5455. */
  5456. destroy: function() {
  5457. data = null;
  5458. stats = null;
  5459. lruHash = null;
  5460. delete caches[cacheId];
  5461. },
  5462. /**
  5463. * @ngdoc method
  5464. * @name $cacheFactory.Cache#info
  5465. * @kind function
  5466. *
  5467. * @description
  5468. * Retrieve information regarding a particular {@link $cacheFactory.Cache Cache}.
  5469. *
  5470. * @returns {object} an object with the following properties:
  5471. * <ul>
  5472. * <li>**id**: the id of the cache instance</li>
  5473. * <li>**size**: the number of entries kept in the cache instance</li>
  5474. * <li>**...**: any additional properties from the options object when creating the
  5475. * cache.</li>
  5476. * </ul>
  5477. */
  5478. info: function() {
  5479. return extend({}, stats, {size: size});
  5480. }
  5481. };
  5482. /**
  5483. * makes the `entry` the freshEnd of the LRU linked list
  5484. */
  5485. function refresh(entry) {
  5486. if (entry != freshEnd) {
  5487. if (!staleEnd) {
  5488. staleEnd = entry;
  5489. } else if (staleEnd == entry) {
  5490. staleEnd = entry.n;
  5491. }
  5492. link(entry.n, entry.p);
  5493. link(entry, freshEnd);
  5494. freshEnd = entry;
  5495. freshEnd.n = null;
  5496. }
  5497. }
  5498. /**
  5499. * bidirectionally links two entries of the LRU linked list
  5500. */
  5501. function link(nextEntry, prevEntry) {
  5502. if (nextEntry != prevEntry) {
  5503. if (nextEntry) nextEntry.p = prevEntry; //p stands for previous, 'prev' didn't minify
  5504. if (prevEntry) prevEntry.n = nextEntry; //n stands for next, 'next' didn't minify
  5505. }
  5506. }
  5507. }
  5508. /**
  5509. * @ngdoc method
  5510. * @name $cacheFactory#info
  5511. *
  5512. * @description
  5513. * Get information about all the caches that have been created
  5514. *
  5515. * @returns {Object} - key-value map of `cacheId` to the result of calling `cache#info`
  5516. */
  5517. cacheFactory.info = function() {
  5518. var info = {};
  5519. forEach(caches, function(cache, cacheId) {
  5520. info[cacheId] = cache.info();
  5521. });
  5522. return info;
  5523. };
  5524. /**
  5525. * @ngdoc method
  5526. * @name $cacheFactory#get
  5527. *
  5528. * @description
  5529. * Get access to a cache object by the `cacheId` used when it was created.
  5530. *
  5531. * @param {string} cacheId Name or id of a cache to access.
  5532. * @returns {object} Cache object identified by the cacheId or undefined if no such cache.
  5533. */
  5534. cacheFactory.get = function(cacheId) {
  5535. return caches[cacheId];
  5536. };
  5537. return cacheFactory;
  5538. };
  5539. }
  5540. /**
  5541. * @ngdoc service
  5542. * @name $templateCache
  5543. *
  5544. * @description
  5545. * The first time a template is used, it is loaded in the template cache for quick retrieval. You
  5546. * can load templates directly into the cache in a `script` tag, or by consuming the
  5547. * `$templateCache` service directly.
  5548. *
  5549. * Adding via the `script` tag:
  5550. *
  5551. * ```html
  5552. * <script type="text/ng-template" id="templateId.html">
  5553. * <p>This is the content of the template</p>
  5554. * </script>
  5555. * ```
  5556. *
  5557. * **Note:** the `script` tag containing the template does not need to be included in the `head` of
  5558. * the document, but it must be a descendent of the {@link ng.$rootElement $rootElement} (IE,
  5559. * element with ng-app attribute), otherwise the template will be ignored.
  5560. *
  5561. * Adding via the `$templateCache` service:
  5562. *
  5563. * ```js
  5564. * var myApp = angular.module('myApp', []);
  5565. * myApp.run(function($templateCache) {
  5566. * $templateCache.put('templateId.html', 'This is the content of the template');
  5567. * });
  5568. * ```
  5569. *
  5570. * To retrieve the template later, simply use it in your HTML:
  5571. * ```html
  5572. * <div ng-include=" 'templateId.html' "></div>
  5573. * ```
  5574. *
  5575. * or get it via Javascript:
  5576. * ```js
  5577. * $templateCache.get('templateId.html')
  5578. * ```
  5579. *
  5580. * See {@link ng.$cacheFactory $cacheFactory}.
  5581. *
  5582. */
  5583. function $TemplateCacheProvider() {
  5584. this.$get = ['$cacheFactory', function($cacheFactory) {
  5585. return $cacheFactory('templates');
  5586. }];
  5587. }
  5588. /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
  5589. * Any commits to this file should be reviewed with security in mind. *
  5590. * Changes to this file can potentially create security vulnerabilities. *
  5591. * An approval from 2 Core members with history of modifying *
  5592. * this file is required. *
  5593. * *
  5594. * Does the change somehow allow for arbitrary javascript to be executed? *
  5595. * Or allows for someone to change the prototype of built-in objects? *
  5596. * Or gives undesired access to variables likes document or window? *
  5597. * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
  5598. /* ! VARIABLE/FUNCTION NAMING CONVENTIONS THAT APPLY TO THIS FILE!
  5599. *
  5600. * DOM-related variables:
  5601. *
  5602. * - "node" - DOM Node
  5603. * - "element" - DOM Element or Node
  5604. * - "$node" or "$element" - jqLite-wrapped node or element
  5605. *
  5606. *
  5607. * Compiler related stuff:
  5608. *
  5609. * - "linkFn" - linking fn of a single directive
  5610. * - "nodeLinkFn" - function that aggregates all linking fns for a particular node
  5611. * - "childLinkFn" - function that aggregates all linking fns for child nodes of a particular node
  5612. * - "compositeLinkFn" - function that aggregates all linking fns for a compilation root (nodeList)
  5613. */
  5614. /**
  5615. * @ngdoc service
  5616. * @name $compile
  5617. * @kind function
  5618. *
  5619. * @description
  5620. * Compiles an HTML string or DOM into a template and produces a template function, which
  5621. * can then be used to link {@link ng.$rootScope.Scope `scope`} and the template together.
  5622. *
  5623. * The compilation is a process of walking the DOM tree and matching DOM elements to
  5624. * {@link ng.$compileProvider#directive directives}.
  5625. *
  5626. * <div class="alert alert-warning">
  5627. * **Note:** This document is an in-depth reference of all directive options.
  5628. * For a gentle introduction to directives with examples of common use cases,
  5629. * see the {@link guide/directive directive guide}.
  5630. * </div>
  5631. *
  5632. * ## Comprehensive Directive API
  5633. *
  5634. * There are many different options for a directive.
  5635. *
  5636. * The difference resides in the return value of the factory function.
  5637. * You can either return a "Directive Definition Object" (see below) that defines the directive properties,
  5638. * or just the `postLink` function (all other properties will have the default values).
  5639. *
  5640. * <div class="alert alert-success">
  5641. * **Best Practice:** It's recommended to use the "directive definition object" form.
  5642. * </div>
  5643. *
  5644. * Here's an example directive declared with a Directive Definition Object:
  5645. *
  5646. * ```js
  5647. * var myModule = angular.module(...);
  5648. *
  5649. * myModule.directive('directiveName', function factory(injectables) {
  5650. * var directiveDefinitionObject = {
  5651. * priority: 0,
  5652. * template: '<div></div>', // or // function(tElement, tAttrs) { ... },
  5653. * // or
  5654. * // templateUrl: 'directive.html', // or // function(tElement, tAttrs) { ... },
  5655. * transclude: false,
  5656. * restrict: 'A',
  5657. * templateNamespace: 'html',
  5658. * scope: false,
  5659. * controller: function($scope, $element, $attrs, $transclude, otherInjectables) { ... },
  5660. * controllerAs: 'stringIdentifier',
  5661. * bindToController: false,
  5662. * require: 'siblingDirectiveName', // or // ['^parentDirectiveName', '?optionalDirectiveName', '?^optionalParent'],
  5663. * compile: function compile(tElement, tAttrs, transclude) {
  5664. * return {
  5665. * pre: function preLink(scope, iElement, iAttrs, controller) { ... },
  5666. * post: function postLink(scope, iElement, iAttrs, controller) { ... }
  5667. * }
  5668. * // or
  5669. * // return function postLink( ... ) { ... }
  5670. * },
  5671. * // or
  5672. * // link: {
  5673. * // pre: function preLink(scope, iElement, iAttrs, controller) { ... },
  5674. * // post: function postLink(scope, iElement, iAttrs, controller) { ... }
  5675. * // }
  5676. * // or
  5677. * // link: function postLink( ... ) { ... }
  5678. * };
  5679. * return directiveDefinitionObject;
  5680. * });
  5681. * ```
  5682. *
  5683. * <div class="alert alert-warning">
  5684. * **Note:** Any unspecified options will use the default value. You can see the default values below.
  5685. * </div>
  5686. *
  5687. * Therefore the above can be simplified as:
  5688. *
  5689. * ```js
  5690. * var myModule = angular.module(...);
  5691. *
  5692. * myModule.directive('directiveName', function factory(injectables) {
  5693. * var directiveDefinitionObject = {
  5694. * link: function postLink(scope, iElement, iAttrs) { ... }
  5695. * };
  5696. * return directiveDefinitionObject;
  5697. * // or
  5698. * // return function postLink(scope, iElement, iAttrs) { ... }
  5699. * });
  5700. * ```
  5701. *
  5702. *
  5703. *
  5704. * ### Directive Definition Object
  5705. *
  5706. * The directive definition object provides instructions to the {@link ng.$compile
  5707. * compiler}. The attributes are:
  5708. *
  5709. * #### `multiElement`
  5710. * When this property is set to true, the HTML compiler will collect DOM nodes between
  5711. * nodes with the attributes `directive-name-start` and `directive-name-end`, and group them
  5712. * together as the directive elements. It is recommended that this feature be used on directives
  5713. * which are not strictly behavioural (such as {@link ngClick}), and which
  5714. * do not manipulate or replace child nodes (such as {@link ngInclude}).
  5715. *
  5716. * #### `priority`
  5717. * When there are multiple directives defined on a single DOM element, sometimes it
  5718. * is necessary to specify the order in which the directives are applied. The `priority` is used
  5719. * to sort the directives before their `compile` functions get called. Priority is defined as a
  5720. * number. Directives with greater numerical `priority` are compiled first. Pre-link functions
  5721. * are also run in priority order, but post-link functions are run in reverse order. The order
  5722. * of directives with the same priority is undefined. The default priority is `0`.
  5723. *
  5724. * #### `terminal`
  5725. * If set to true then the current `priority` will be the last set of directives
  5726. * which will execute (any directives at the current priority will still execute
  5727. * as the order of execution on same `priority` is undefined). Note that expressions
  5728. * and other directives used in the directive's template will also be excluded from execution.
  5729. *
  5730. * #### `scope`
  5731. * The scope property can be `true`, an object or a falsy value:
  5732. *
  5733. * * **falsy:** No scope will be created for the directive. The directive will use its parent's scope.
  5734. *
  5735. * * **`true`:** A new child scope that prototypically inherits from its parent will be created for
  5736. * the directive's element. If multiple directives on the same element request a new scope,
  5737. * only one new scope is created. The new scope rule does not apply for the root of the template
  5738. * since the root of the template always gets a new scope.
  5739. *
  5740. * * **`{...}` (an object hash):** A new "isolate" scope is created for the directive's element. The
  5741. * 'isolate' scope differs from normal scope in that it does not prototypically inherit from its parent
  5742. * scope. This is useful when creating reusable components, which should not accidentally read or modify
  5743. * data in the parent scope.
  5744. *
  5745. * The 'isolate' scope object hash defines a set of local scope properties derived from attributes on the
  5746. * directive's element. These local properties are useful for aliasing values for templates. The keys in
  5747. * the object hash map to the name of the property on the isolate scope; the values define how the property
  5748. * is bound to the parent scope, via matching attributes on the directive's element:
  5749. *
  5750. * * `@` or `@attr` - bind a local scope property to the value of DOM attribute. The result is
  5751. * always a string since DOM attributes are strings. If no `attr` name is specified then the
  5752. * attribute name is assumed to be the same as the local name.
  5753. * Given `<widget my-attr="hello {{name}}">` and widget definition
  5754. * of `scope: { localName:'@myAttr' }`, then widget scope property `localName` will reflect
  5755. * the interpolated value of `hello {{name}}`. As the `name` attribute changes so will the
  5756. * `localName` property on the widget scope. The `name` is read from the parent scope (not
  5757. * component scope).
  5758. *
  5759. * * `=` or `=attr` - set up bi-directional binding between a local scope property and the
  5760. * parent scope property of name defined via the value of the `attr` attribute. If no `attr`
  5761. * name is specified then the attribute name is assumed to be the same as the local name.
  5762. * Given `<widget my-attr="parentModel">` and widget definition of
  5763. * `scope: { localModel:'=myAttr' }`, then widget scope property `localModel` will reflect the
  5764. * value of `parentModel` on the parent scope. Any changes to `parentModel` will be reflected
  5765. * in `localModel` and any changes in `localModel` will reflect in `parentModel`. If the parent
  5766. * scope property doesn't exist, it will throw a NON_ASSIGNABLE_MODEL_EXPRESSION exception. You
  5767. * can avoid this behavior using `=?` or `=?attr` in order to flag the property as optional. If
  5768. * you want to shallow watch for changes (i.e. $watchCollection instead of $watch) you can use
  5769. * `=*` or `=*attr` (`=*?` or `=*?attr` if the property is optional).
  5770. *
  5771. * * `&` or `&attr` - provides a way to execute an expression in the context of the parent scope.
  5772. * If no `attr` name is specified then the attribute name is assumed to be the same as the
  5773. * local name. Given `<widget my-attr="count = count + value">` and widget definition of
  5774. * `scope: { localFn:'&myAttr' }`, then isolate scope property `localFn` will point to
  5775. * a function wrapper for the `count = count + value` expression. Often it's desirable to
  5776. * pass data from the isolated scope via an expression to the parent scope, this can be
  5777. * done by passing a map of local variable names and values into the expression wrapper fn.
  5778. * For example, if the expression is `increment(amount)` then we can specify the amount value
  5779. * by calling the `localFn` as `localFn({amount: 22})`.
  5780. *
  5781. * In general it's possible to apply more than one directive to one element, but there might be limitations
  5782. * depending on the type of scope required by the directives. The following points will help explain these limitations.
  5783. * For simplicity only two directives are taken into account, but it is also applicable for several directives:
  5784. *
  5785. * * **no scope** + **no scope** => Two directives which don't require their own scope will use their parent's scope
  5786. * * **child scope** + **no scope** => Both directives will share one single child scope
  5787. * * **child scope** + **child scope** => Both directives will share one single child scope
  5788. * * **isolated scope** + **no scope** => The isolated directive will use it's own created isolated scope. The other directive will use
  5789. * its parent's scope
  5790. * * **isolated scope** + **child scope** => **Won't work!** Only one scope can be related to one element. Therefore these directives cannot
  5791. * be applied to the same element.
  5792. * * **isolated scope** + **isolated scope** => **Won't work!** Only one scope can be related to one element. Therefore these directives
  5793. * cannot be applied to the same element.
  5794. *
  5795. *
  5796. * #### `bindToController`
  5797. * When an isolate scope is used for a component (see above), and `controllerAs` is used, `bindToController: true` will
  5798. * allow a component to have its properties bound to the controller, rather than to scope. When the controller
  5799. * is instantiated, the initial values of the isolate scope bindings are already available.
  5800. *
  5801. * #### `controller`
  5802. * Controller constructor function. The controller is instantiated before the
  5803. * pre-linking phase and can be accessed by other directives (see
  5804. * `require` attribute). This allows the directives to communicate with each other and augment
  5805. * each other's behavior. The controller is injectable (and supports bracket notation) with the following locals:
  5806. *
  5807. * * `$scope` - Current scope associated with the element
  5808. * * `$element` - Current element
  5809. * * `$attrs` - Current attributes object for the element
  5810. * * `$transclude` - A transclude linking function pre-bound to the correct transclusion scope:
  5811. * `function([scope], cloneLinkingFn, futureParentElement)`.
  5812. * * `scope`: optional argument to override the scope.
  5813. * * `cloneLinkingFn`: optional argument to create clones of the original transcluded content.
  5814. * * `futureParentElement`:
  5815. * * defines the parent to which the `cloneLinkingFn` will add the cloned elements.
  5816. * * default: `$element.parent()` resp. `$element` for `transclude:'element'` resp. `transclude:true`.
  5817. * * only needed for transcludes that are allowed to contain non html elements (e.g. SVG elements)
  5818. * and when the `cloneLinkinFn` is passed,
  5819. * as those elements need to created and cloned in a special way when they are defined outside their
  5820. * usual containers (e.g. like `<svg>`).
  5821. * * See also the `directive.templateNamespace` property.
  5822. *
  5823. *
  5824. * #### `require`
  5825. * Require another directive and inject its controller as the fourth argument to the linking function. The
  5826. * `require` takes a string name (or array of strings) of the directive(s) to pass in. If an array is used, the
  5827. * injected argument will be an array in corresponding order. If no such directive can be
  5828. * found, or if the directive does not have a controller, then an error is raised (unless no link function
  5829. * is specified, in which case error checking is skipped). The name can be prefixed with:
  5830. *
  5831. * * (no prefix) - Locate the required controller on the current element. Throw an error if not found.
  5832. * * `?` - Attempt to locate the required controller or pass `null` to the `link` fn if not found.
  5833. * * `^` - Locate the required controller by searching the element and its parents. Throw an error if not found.
  5834. * * `^^` - Locate the required controller by searching the element's parents. Throw an error if not found.
  5835. * * `?^` - Attempt to locate the required controller by searching the element and its parents or pass
  5836. * `null` to the `link` fn if not found.
  5837. * * `?^^` - Attempt to locate the required controller by searching the element's parents, or pass
  5838. * `null` to the `link` fn if not found.
  5839. *
  5840. *
  5841. * #### `controllerAs`
  5842. * Identifier name for a reference to the controller in the directive's scope.
  5843. * This allows the controller to be referenced from the directive template. This is especially
  5844. * useful when a directive is used as component, i.e. with an `isolate` scope. It's also possible
  5845. * to use it in a directive without an `isolate` / `new` scope, but you need to be aware that the
  5846. * `controllerAs` reference might overwrite a property that already exists on the parent scope.
  5847. *
  5848. *
  5849. * #### `restrict`
  5850. * String of subset of `EACM` which restricts the directive to a specific directive
  5851. * declaration style. If omitted, the defaults (elements and attributes) are used.
  5852. *
  5853. * * `E` - Element name (default): `<my-directive></my-directive>`
  5854. * * `A` - Attribute (default): `<div my-directive="exp"></div>`
  5855. * * `C` - Class: `<div class="my-directive: exp;"></div>`
  5856. * * `M` - Comment: `<!-- directive: my-directive exp -->`
  5857. *
  5858. *
  5859. * #### `templateNamespace`
  5860. * String representing the document type used by the markup in the template.
  5861. * AngularJS needs this information as those elements need to be created and cloned
  5862. * in a special way when they are defined outside their usual containers like `<svg>` and `<math>`.
  5863. *
  5864. * * `html` - All root nodes in the template are HTML. Root nodes may also be
  5865. * top-level elements such as `<svg>` or `<math>`.
  5866. * * `svg` - The root nodes in the template are SVG elements (excluding `<math>`).
  5867. * * `math` - The root nodes in the template are MathML elements (excluding `<svg>`).
  5868. *
  5869. * If no `templateNamespace` is specified, then the namespace is considered to be `html`.
  5870. *
  5871. * #### `template`
  5872. * HTML markup that may:
  5873. * * Replace the contents of the directive's element (default).
  5874. * * Replace the directive's element itself (if `replace` is true - DEPRECATED).
  5875. * * Wrap the contents of the directive's element (if `transclude` is true).
  5876. *
  5877. * Value may be:
  5878. *
  5879. * * A string. For example `<div red-on-hover>{{delete_str}}</div>`.
  5880. * * A function which takes two arguments `tElement` and `tAttrs` (described in the `compile`
  5881. * function api below) and returns a string value.
  5882. *
  5883. *
  5884. * #### `templateUrl`
  5885. * This is similar to `template` but the template is loaded from the specified URL, asynchronously.
  5886. *
  5887. * Because template loading is asynchronous the compiler will suspend compilation of directives on that element
  5888. * for later when the template has been resolved. In the meantime it will continue to compile and link
  5889. * sibling and parent elements as though this element had not contained any directives.
  5890. *
  5891. * The compiler does not suspend the entire compilation to wait for templates to be loaded because this
  5892. * would result in the whole app "stalling" until all templates are loaded asynchronously - even in the
  5893. * case when only one deeply nested directive has `templateUrl`.
  5894. *
  5895. * Template loading is asynchronous even if the template has been preloaded into the {@link $templateCache}
  5896. *
  5897. * You can specify `templateUrl` as a string representing the URL or as a function which takes two
  5898. * arguments `tElement` and `tAttrs` (described in the `compile` function api below) and returns
  5899. * a string value representing the url. In either case, the template URL is passed through {@link
  5900. * $sce#getTrustedResourceUrl $sce.getTrustedResourceUrl}.
  5901. *
  5902. *
  5903. * #### `replace` ([*DEPRECATED*!], will be removed in next major release - i.e. v2.0)
  5904. * specify what the template should replace. Defaults to `false`.
  5905. *
  5906. * * `true` - the template will replace the directive's element.
  5907. * * `false` - the template will replace the contents of the directive's element.
  5908. *
  5909. * The replacement process migrates all of the attributes / classes from the old element to the new
  5910. * one. See the {@link guide/directive#template-expanding-directive
  5911. * Directives Guide} for an example.
  5912. *
  5913. * There are very few scenarios where element replacement is required for the application function,
  5914. * the main one being reusable custom components that are used within SVG contexts
  5915. * (because SVG doesn't work with custom elements in the DOM tree).
  5916. *
  5917. * #### `transclude`
  5918. * Extract the contents of the element where the directive appears and make it available to the directive.
  5919. * The contents are compiled and provided to the directive as a **transclusion function**. See the
  5920. * {@link $compile#transclusion Transclusion} section below.
  5921. *
  5922. * There are two kinds of transclusion depending upon whether you want to transclude just the contents of the
  5923. * directive's element or the entire element:
  5924. *
  5925. * * `true` - transclude the content (i.e. the child nodes) of the directive's element.
  5926. * * `'element'` - transclude the whole of the directive's element including any directives on this
  5927. * element that defined at a lower priority than this directive. When used, the `template`
  5928. * property is ignored.
  5929. *
  5930. *
  5931. * #### `compile`
  5932. *
  5933. * ```js
  5934. * function compile(tElement, tAttrs, transclude) { ... }
  5935. * ```
  5936. *
  5937. * The compile function deals with transforming the template DOM. Since most directives do not do
  5938. * template transformation, it is not used often. The compile function takes the following arguments:
  5939. *
  5940. * * `tElement` - template element - The element where the directive has been declared. It is
  5941. * safe to do template transformation on the element and child elements only.
  5942. *
  5943. * * `tAttrs` - template attributes - Normalized list of attributes declared on this element shared
  5944. * between all directive compile functions.
  5945. *
  5946. * * `transclude` - [*DEPRECATED*!] A transclude linking function: `function(scope, cloneLinkingFn)`
  5947. *
  5948. * <div class="alert alert-warning">
  5949. * **Note:** The template instance and the link instance may be different objects if the template has
  5950. * been cloned. For this reason it is **not** safe to do anything other than DOM transformations that
  5951. * apply to all cloned DOM nodes within the compile function. Specifically, DOM listener registration
  5952. * should be done in a linking function rather than in a compile function.
  5953. * </div>
  5954. * <div class="alert alert-warning">
  5955. * **Note:** The compile function cannot handle directives that recursively use themselves in their
  5956. * own templates or compile functions. Compiling these directives results in an infinite loop and a
  5957. * stack overflow errors.
  5958. *
  5959. * This can be avoided by manually using $compile in the postLink function to imperatively compile
  5960. * a directive's template instead of relying on automatic template compilation via `template` or
  5961. * `templateUrl` declaration or manual compilation inside the compile function.
  5962. * </div>
  5963. *
  5964. * <div class="alert alert-danger">
  5965. * **Note:** The `transclude` function that is passed to the compile function is deprecated, as it
  5966. * e.g. does not know about the right outer scope. Please use the transclude function that is passed
  5967. * to the link function instead.
  5968. * </div>
  5969. * A compile function can have a return value which can be either a function or an object.
  5970. *
  5971. * * returning a (post-link) function - is equivalent to registering the linking function via the
  5972. * `link` property of the config object when the compile function is empty.
  5973. *
  5974. * * returning an object with function(s) registered via `pre` and `post` properties - allows you to
  5975. * control when a linking function should be called during the linking phase. See info about
  5976. * pre-linking and post-linking functions below.
  5977. *
  5978. *
  5979. * #### `link`
  5980. * This property is used only if the `compile` property is not defined.
  5981. *
  5982. * ```js
  5983. * function link(scope, iElement, iAttrs, controller, transcludeFn) { ... }
  5984. * ```
  5985. *
  5986. * The link function is responsible for registering DOM listeners as well as updating the DOM. It is
  5987. * executed after the template has been cloned. This is where most of the directive logic will be
  5988. * put.
  5989. *
  5990. * * `scope` - {@link ng.$rootScope.Scope Scope} - The scope to be used by the
  5991. * directive for registering {@link ng.$rootScope.Scope#$watch watches}.
  5992. *
  5993. * * `iElement` - instance element - The element where the directive is to be used. It is safe to
  5994. * manipulate the children of the element only in `postLink` function since the children have
  5995. * already been linked.
  5996. *
  5997. * * `iAttrs` - instance attributes - Normalized list of attributes declared on this element shared
  5998. * between all directive linking functions.
  5999. *
  6000. * * `controller` - the directive's required controller instance(s) - Instances are shared
  6001. * among all directives, which allows the directives to use the controllers as a communication
  6002. * channel. The exact value depends on the directive's `require` property:
  6003. * * no controller(s) required: the directive's own controller, or `undefined` if it doesn't have one
  6004. * * `string`: the controller instance
  6005. * * `array`: array of controller instances
  6006. *
  6007. * If a required controller cannot be found, and it is optional, the instance is `null`,
  6008. * otherwise the {@link error:$compile:ctreq Missing Required Controller} error is thrown.
  6009. *
  6010. * Note that you can also require the directive's own controller - it will be made available like
  6011. * any other controller.
  6012. *
  6013. * * `transcludeFn` - A transclude linking function pre-bound to the correct transclusion scope.
  6014. * This is the same as the `$transclude`
  6015. * parameter of directive controllers, see there for details.
  6016. * `function([scope], cloneLinkingFn, futureParentElement)`.
  6017. *
  6018. * #### Pre-linking function
  6019. *
  6020. * Executed before the child elements are linked. Not safe to do DOM transformation since the
  6021. * compiler linking function will fail to locate the correct elements for linking.
  6022. *
  6023. * #### Post-linking function
  6024. *
  6025. * Executed after the child elements are linked.
  6026. *
  6027. * Note that child elements that contain `templateUrl` directives will not have been compiled
  6028. * and linked since they are waiting for their template to load asynchronously and their own
  6029. * compilation and linking has been suspended until that occurs.
  6030. *
  6031. * It is safe to do DOM transformation in the post-linking function on elements that are not waiting
  6032. * for their async templates to be resolved.
  6033. *
  6034. *
  6035. * ### Transclusion
  6036. *
  6037. * Transclusion is the process of extracting a collection of DOM elements from one part of the DOM and
  6038. * copying them to another part of the DOM, while maintaining their connection to the original AngularJS
  6039. * scope from where they were taken.
  6040. *
  6041. * Transclusion is used (often with {@link ngTransclude}) to insert the
  6042. * original contents of a directive's element into a specified place in the template of the directive.
  6043. * The benefit of transclusion, over simply moving the DOM elements manually, is that the transcluded
  6044. * content has access to the properties on the scope from which it was taken, even if the directive
  6045. * has isolated scope.
  6046. * See the {@link guide/directive#creating-a-directive-that-wraps-other-elements Directives Guide}.
  6047. *
  6048. * This makes it possible for the widget to have private state for its template, while the transcluded
  6049. * content has access to its originating scope.
  6050. *
  6051. * <div class="alert alert-warning">
  6052. * **Note:** When testing an element transclude directive you must not place the directive at the root of the
  6053. * DOM fragment that is being compiled. See {@link guide/unit-testing#testing-transclusion-directives
  6054. * Testing Transclusion Directives}.
  6055. * </div>
  6056. *
  6057. * #### Transclusion Functions
  6058. *
  6059. * When a directive requests transclusion, the compiler extracts its contents and provides a **transclusion
  6060. * function** to the directive's `link` function and `controller`. This transclusion function is a special
  6061. * **linking function** that will return the compiled contents linked to a new transclusion scope.
  6062. *
  6063. * <div class="alert alert-info">
  6064. * If you are just using {@link ngTransclude} then you don't need to worry about this function, since
  6065. * ngTransclude will deal with it for us.
  6066. * </div>
  6067. *
  6068. * If you want to manually control the insertion and removal of the transcluded content in your directive
  6069. * then you must use this transclude function. When you call a transclude function it returns a a jqLite/JQuery
  6070. * object that contains the compiled DOM, which is linked to the correct transclusion scope.
  6071. *
  6072. * When you call a transclusion function you can pass in a **clone attach function**. This function accepts
  6073. * two parameters, `function(clone, scope) { ... }`, where the `clone` is a fresh compiled copy of your transcluded
  6074. * content and the `scope` is the newly created transclusion scope, to which the clone is bound.
  6075. *
  6076. * <div class="alert alert-info">
  6077. * **Best Practice**: Always provide a `cloneFn` (clone attach function) when you call a translude function
  6078. * since you then get a fresh clone of the original DOM and also have access to the new transclusion scope.
  6079. * </div>
  6080. *
  6081. * It is normal practice to attach your transcluded content (`clone`) to the DOM inside your **clone
  6082. * attach function**:
  6083. *
  6084. * ```js
  6085. * var transcludedContent, transclusionScope;
  6086. *
  6087. * $transclude(function(clone, scope) {
  6088. * element.append(clone);
  6089. * transcludedContent = clone;
  6090. * transclusionScope = scope;
  6091. * });
  6092. * ```
  6093. *
  6094. * Later, if you want to remove the transcluded content from your DOM then you should also destroy the
  6095. * associated transclusion scope:
  6096. *
  6097. * ```js
  6098. * transcludedContent.remove();
  6099. * transclusionScope.$destroy();
  6100. * ```
  6101. *
  6102. * <div class="alert alert-info">
  6103. * **Best Practice**: if you intend to add and remove transcluded content manually in your directive
  6104. * (by calling the transclude function to get the DOM and calling `element.remove()` to remove it),
  6105. * then you are also responsible for calling `$destroy` on the transclusion scope.
  6106. * </div>
  6107. *
  6108. * The built-in DOM manipulation directives, such as {@link ngIf}, {@link ngSwitch} and {@link ngRepeat}
  6109. * automatically destroy their transluded clones as necessary so you do not need to worry about this if
  6110. * you are simply using {@link ngTransclude} to inject the transclusion into your directive.
  6111. *
  6112. *
  6113. * #### Transclusion Scopes
  6114. *
  6115. * When you call a transclude function it returns a DOM fragment that is pre-bound to a **transclusion
  6116. * scope**. This scope is special, in that it is a child of the directive's scope (and so gets destroyed
  6117. * when the directive's scope gets destroyed) but it inherits the properties of the scope from which it
  6118. * was taken.
  6119. *
  6120. * For example consider a directive that uses transclusion and isolated scope. The DOM hierarchy might look
  6121. * like this:
  6122. *
  6123. * ```html
  6124. * <div ng-app>
  6125. * <div isolate>
  6126. * <div transclusion>
  6127. * </div>
  6128. * </div>
  6129. * </div>
  6130. * ```
  6131. *
  6132. * The `$parent` scope hierarchy will look like this:
  6133. *
  6134. * ```
  6135. * - $rootScope
  6136. * - isolate
  6137. * - transclusion
  6138. * ```
  6139. *
  6140. * but the scopes will inherit prototypically from different scopes to their `$parent`.
  6141. *
  6142. * ```
  6143. * - $rootScope
  6144. * - transclusion
  6145. * - isolate
  6146. * ```
  6147. *
  6148. *
  6149. * ### Attributes
  6150. *
  6151. * The {@link ng.$compile.directive.Attributes Attributes} object - passed as a parameter in the
  6152. * `link()` or `compile()` functions. It has a variety of uses.
  6153. *
  6154. * accessing *Normalized attribute names:*
  6155. * Directives like 'ngBind' can be expressed in many ways: 'ng:bind', `data-ng-bind`, or 'x-ng-bind'.
  6156. * the attributes object allows for normalized access to
  6157. * the attributes.
  6158. *
  6159. * * *Directive inter-communication:* All directives share the same instance of the attributes
  6160. * object which allows the directives to use the attributes object as inter directive
  6161. * communication.
  6162. *
  6163. * * *Supports interpolation:* Interpolation attributes are assigned to the attribute object
  6164. * allowing other directives to read the interpolated value.
  6165. *
  6166. * * *Observing interpolated attributes:* Use `$observe` to observe the value changes of attributes
  6167. * that contain interpolation (e.g. `src="{{bar}}"`). Not only is this very efficient but it's also
  6168. * the only way to easily get the actual value because during the linking phase the interpolation
  6169. * hasn't been evaluated yet and so the value is at this time set to `undefined`.
  6170. *
  6171. * ```js
  6172. * function linkingFn(scope, elm, attrs, ctrl) {
  6173. * // get the attribute value
  6174. * console.log(attrs.ngModel);
  6175. *
  6176. * // change the attribute
  6177. * attrs.$set('ngModel', 'new value');
  6178. *
  6179. * // observe changes to interpolated attribute
  6180. * attrs.$observe('ngModel', function(value) {
  6181. * console.log('ngModel has changed value to ' + value);
  6182. * });
  6183. * }
  6184. * ```
  6185. *
  6186. * ## Example
  6187. *
  6188. * <div class="alert alert-warning">
  6189. * **Note**: Typically directives are registered with `module.directive`. The example below is
  6190. * to illustrate how `$compile` works.
  6191. * </div>
  6192. *
  6193. <example module="compileExample">
  6194. <file name="index.html">
  6195. <script>
  6196. angular.module('compileExample', [], function($compileProvider) {
  6197. // configure new 'compile' directive by passing a directive
  6198. // factory function. The factory function injects the '$compile'
  6199. $compileProvider.directive('compile', function($compile) {
  6200. // directive factory creates a link function
  6201. return function(scope, element, attrs) {
  6202. scope.$watch(
  6203. function(scope) {
  6204. // watch the 'compile' expression for changes
  6205. return scope.$eval(attrs.compile);
  6206. },
  6207. function(value) {
  6208. // when the 'compile' expression changes
  6209. // assign it into the current DOM
  6210. element.html(value);
  6211. // compile the new DOM and link it to the current
  6212. // scope.
  6213. // NOTE: we only compile .childNodes so that
  6214. // we don't get into infinite loop compiling ourselves
  6215. $compile(element.contents())(scope);
  6216. }
  6217. );
  6218. };
  6219. });
  6220. })
  6221. .controller('GreeterController', ['$scope', function($scope) {
  6222. $scope.name = 'Angular';
  6223. $scope.html = 'Hello {{name}}';
  6224. }]);
  6225. </script>
  6226. <div ng-controller="GreeterController">
  6227. <input ng-model="name"> <br/>
  6228. <textarea ng-model="html"></textarea> <br/>
  6229. <div compile="html"></div>
  6230. </div>
  6231. </file>
  6232. <file name="protractor.js" type="protractor">
  6233. it('should auto compile', function() {
  6234. var textarea = $('textarea');
  6235. var output = $('div[compile]');
  6236. // The initial state reads 'Hello Angular'.
  6237. expect(output.getText()).toBe('Hello Angular');
  6238. textarea.clear();
  6239. textarea.sendKeys('{{name}}!');
  6240. expect(output.getText()).toBe('Angular!');
  6241. });
  6242. </file>
  6243. </example>
  6244. *
  6245. *
  6246. * @param {string|DOMElement} element Element or HTML string to compile into a template function.
  6247. * @param {function(angular.Scope, cloneAttachFn=)} transclude function available to directives - DEPRECATED.
  6248. *
  6249. * <div class="alert alert-danger">
  6250. * **Note:** Passing a `transclude` function to the $compile function is deprecated, as it
  6251. * e.g. will not use the right outer scope. Please pass the transclude function as a
  6252. * `parentBoundTranscludeFn` to the link function instead.
  6253. * </div>
  6254. *
  6255. * @param {number} maxPriority only apply directives lower than given priority (Only effects the
  6256. * root element(s), not their children)
  6257. * @returns {function(scope, cloneAttachFn=, options=)} a link function which is used to bind template
  6258. * (a DOM element/tree) to a scope. Where:
  6259. *
  6260. * * `scope` - A {@link ng.$rootScope.Scope Scope} to bind to.
  6261. * * `cloneAttachFn` - If `cloneAttachFn` is provided, then the link function will clone the
  6262. * `template` and call the `cloneAttachFn` function allowing the caller to attach the
  6263. * cloned elements to the DOM document at the appropriate place. The `cloneAttachFn` is
  6264. * called as: <br/> `cloneAttachFn(clonedElement, scope)` where:
  6265. *
  6266. * * `clonedElement` - is a clone of the original `element` passed into the compiler.
  6267. * * `scope` - is the current scope with which the linking function is working with.
  6268. *
  6269. * * `options` - An optional object hash with linking options. If `options` is provided, then the following
  6270. * keys may be used to control linking behavior:
  6271. *
  6272. * * `parentBoundTranscludeFn` - the transclude function made available to
  6273. * directives; if given, it will be passed through to the link functions of
  6274. * directives found in `element` during compilation.
  6275. * * `transcludeControllers` - an object hash with keys that map controller names
  6276. * to controller instances; if given, it will make the controllers
  6277. * available to directives.
  6278. * * `futureParentElement` - defines the parent to which the `cloneAttachFn` will add
  6279. * the cloned elements; only needed for transcludes that are allowed to contain non html
  6280. * elements (e.g. SVG elements). See also the directive.controller property.
  6281. *
  6282. * Calling the linking function returns the element of the template. It is either the original
  6283. * element passed in, or the clone of the element if the `cloneAttachFn` is provided.
  6284. *
  6285. * After linking the view is not updated until after a call to $digest which typically is done by
  6286. * Angular automatically.
  6287. *
  6288. * If you need access to the bound view, there are two ways to do it:
  6289. *
  6290. * - If you are not asking the linking function to clone the template, create the DOM element(s)
  6291. * before you send them to the compiler and keep this reference around.
  6292. * ```js
  6293. * var element = $compile('<p>{{total}}</p>')(scope);
  6294. * ```
  6295. *
  6296. * - if on the other hand, you need the element to be cloned, the view reference from the original
  6297. * example would not point to the clone, but rather to the original template that was cloned. In
  6298. * this case, you can access the clone via the cloneAttachFn:
  6299. * ```js
  6300. * var templateElement = angular.element('<p>{{total}}</p>'),
  6301. * scope = ....;
  6302. *
  6303. * var clonedElement = $compile(templateElement)(scope, function(clonedElement, scope) {
  6304. * //attach the clone to DOM document at the right place
  6305. * });
  6306. *
  6307. * //now we have reference to the cloned DOM via `clonedElement`
  6308. * ```
  6309. *
  6310. *
  6311. * For information on how the compiler works, see the
  6312. * {@link guide/compiler Angular HTML Compiler} section of the Developer Guide.
  6313. */
  6314. var $compileMinErr = minErr('$compile');
  6315. /**
  6316. * @ngdoc provider
  6317. * @name $compileProvider
  6318. *
  6319. * @description
  6320. */
  6321. $CompileProvider.$inject = ['$provide', '$$sanitizeUriProvider'];
  6322. function $CompileProvider($provide, $$sanitizeUriProvider) {
  6323. var hasDirectives = {},
  6324. Suffix = 'Directive',
  6325. COMMENT_DIRECTIVE_REGEXP = /^\s*directive\:\s*([\w\-]+)\s+(.*)$/,
  6326. CLASS_DIRECTIVE_REGEXP = /(([\w\-]+)(?:\:([^;]+))?;?)/,
  6327. ALL_OR_NOTHING_ATTRS = makeMap('ngSrc,ngSrcset,src,srcset'),
  6328. REQUIRE_PREFIX_REGEXP = /^(?:(\^\^?)?(\?)?(\^\^?)?)?/;
  6329. // Ref: http://developers.whatwg.org/webappapis.html#event-handler-idl-attributes
  6330. // The assumption is that future DOM event attribute names will begin with
  6331. // 'on' and be composed of only English letters.
  6332. var EVENT_HANDLER_ATTR_REGEXP = /^(on[a-z]+|formaction)$/;
  6333. function parseIsolateBindings(scope, directiveName, isController) {
  6334. var LOCAL_REGEXP = /^\s*([@&]|=(\*?))(\??)\s*(\w*)\s*$/;
  6335. var bindings = {};
  6336. forEach(scope, function(definition, scopeName) {
  6337. var match = definition.match(LOCAL_REGEXP);
  6338. if (!match) {
  6339. throw $compileMinErr('iscp',
  6340. "Invalid {3} for directive '{0}'." +
  6341. " Definition: {... {1}: '{2}' ...}",
  6342. directiveName, scopeName, definition,
  6343. (isController ? "controller bindings definition" :
  6344. "isolate scope definition"));
  6345. }
  6346. bindings[scopeName] = {
  6347. mode: match[1][0],
  6348. collection: match[2] === '*',
  6349. optional: match[3] === '?',
  6350. attrName: match[4] || scopeName
  6351. };
  6352. });
  6353. return bindings;
  6354. }
  6355. function parseDirectiveBindings(directive, directiveName) {
  6356. var bindings = {
  6357. isolateScope: null,
  6358. bindToController: null
  6359. };
  6360. if (isObject(directive.scope)) {
  6361. if (directive.bindToController === true) {
  6362. bindings.bindToController = parseIsolateBindings(directive.scope,
  6363. directiveName, true);
  6364. bindings.isolateScope = {};
  6365. } else {
  6366. bindings.isolateScope = parseIsolateBindings(directive.scope,
  6367. directiveName, false);
  6368. }
  6369. }
  6370. if (isObject(directive.bindToController)) {
  6371. bindings.bindToController =
  6372. parseIsolateBindings(directive.bindToController, directiveName, true);
  6373. }
  6374. if (isObject(bindings.bindToController)) {
  6375. var controller = directive.controller;
  6376. var controllerAs = directive.controllerAs;
  6377. if (!controller) {
  6378. // There is no controller, there may or may not be a controllerAs property
  6379. throw $compileMinErr('noctrl',
  6380. "Cannot bind to controller without directive '{0}'s controller.",
  6381. directiveName);
  6382. } else if (!identifierForController(controller, controllerAs)) {
  6383. // There is a controller, but no identifier or controllerAs property
  6384. throw $compileMinErr('noident',
  6385. "Cannot bind to controller without identifier for directive '{0}'.",
  6386. directiveName);
  6387. }
  6388. }
  6389. return bindings;
  6390. }
  6391. function assertValidDirectiveName(name) {
  6392. var letter = name.charAt(0);
  6393. if (!letter || letter !== lowercase(letter)) {
  6394. throw $compileMinErr('baddir', "Directive name '{0}' is invalid. The first character must be a lowercase letter", name);
  6395. }
  6396. if (name !== name.trim()) {
  6397. throw $compileMinErr('baddir',
  6398. "Directive name '{0}' is invalid. The name should not contain leading or trailing whitespaces",
  6399. name);
  6400. }
  6401. }
  6402. /**
  6403. * @ngdoc method
  6404. * @name $compileProvider#directive
  6405. * @kind function
  6406. *
  6407. * @description
  6408. * Register a new directive with the compiler.
  6409. *
  6410. * @param {string|Object} name Name of the directive in camel-case (i.e. <code>ngBind</code> which
  6411. * will match as <code>ng-bind</code>), or an object map of directives where the keys are the
  6412. * names and the values are the factories.
  6413. * @param {Function|Array} directiveFactory An injectable directive factory function. See
  6414. * {@link guide/directive} for more info.
  6415. * @returns {ng.$compileProvider} Self for chaining.
  6416. */
  6417. this.directive = function registerDirective(name, directiveFactory) {
  6418. assertNotHasOwnProperty(name, 'directive');
  6419. if (isString(name)) {
  6420. assertValidDirectiveName(name);
  6421. assertArg(directiveFactory, 'directiveFactory');
  6422. if (!hasDirectives.hasOwnProperty(name)) {
  6423. hasDirectives[name] = [];
  6424. $provide.factory(name + Suffix, ['$injector', '$exceptionHandler',
  6425. function($injector, $exceptionHandler) {
  6426. var directives = [];
  6427. forEach(hasDirectives[name], function(directiveFactory, index) {
  6428. try {
  6429. var directive = $injector.invoke(directiveFactory);
  6430. if (isFunction(directive)) {
  6431. directive = { compile: valueFn(directive) };
  6432. } else if (!directive.compile && directive.link) {
  6433. directive.compile = valueFn(directive.link);
  6434. }
  6435. directive.priority = directive.priority || 0;
  6436. directive.index = index;
  6437. directive.name = directive.name || name;
  6438. directive.require = directive.require || (directive.controller && directive.name);
  6439. directive.restrict = directive.restrict || 'EA';
  6440. var bindings = directive.$$bindings =
  6441. parseDirectiveBindings(directive, directive.name);
  6442. if (isObject(bindings.isolateScope)) {
  6443. directive.$$isolateBindings = bindings.isolateScope;
  6444. }
  6445. directive.$$moduleName = directiveFactory.$$moduleName;
  6446. directives.push(directive);
  6447. } catch (e) {
  6448. $exceptionHandler(e);
  6449. }
  6450. });
  6451. return directives;
  6452. }]);
  6453. }
  6454. hasDirectives[name].push(directiveFactory);
  6455. } else {
  6456. forEach(name, reverseParams(registerDirective));
  6457. }
  6458. return this;
  6459. };
  6460. /**
  6461. * @ngdoc method
  6462. * @name $compileProvider#aHrefSanitizationWhitelist
  6463. * @kind function
  6464. *
  6465. * @description
  6466. * Retrieves or overrides the default regular expression that is used for whitelisting of safe
  6467. * urls during a[href] sanitization.
  6468. *
  6469. * The sanitization is a security measure aimed at preventing XSS attacks via html links.
  6470. *
  6471. * Any url about to be assigned to a[href] via data-binding is first normalized and turned into
  6472. * an absolute url. Afterwards, the url is matched against the `aHrefSanitizationWhitelist`
  6473. * regular expression. If a match is found, the original url is written into the dom. Otherwise,
  6474. * the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM.
  6475. *
  6476. * @param {RegExp=} regexp New regexp to whitelist urls with.
  6477. * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for
  6478. * chaining otherwise.
  6479. */
  6480. this.aHrefSanitizationWhitelist = function(regexp) {
  6481. if (isDefined(regexp)) {
  6482. $$sanitizeUriProvider.aHrefSanitizationWhitelist(regexp);
  6483. return this;
  6484. } else {
  6485. return $$sanitizeUriProvider.aHrefSanitizationWhitelist();
  6486. }
  6487. };
  6488. /**
  6489. * @ngdoc method
  6490. * @name $compileProvider#imgSrcSanitizationWhitelist
  6491. * @kind function
  6492. *
  6493. * @description
  6494. * Retrieves or overrides the default regular expression that is used for whitelisting of safe
  6495. * urls during img[src] sanitization.
  6496. *
  6497. * The sanitization is a security measure aimed at prevent XSS attacks via html links.
  6498. *
  6499. * Any url about to be assigned to img[src] via data-binding is first normalized and turned into
  6500. * an absolute url. Afterwards, the url is matched against the `imgSrcSanitizationWhitelist`
  6501. * regular expression. If a match is found, the original url is written into the dom. Otherwise,
  6502. * the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM.
  6503. *
  6504. * @param {RegExp=} regexp New regexp to whitelist urls with.
  6505. * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for
  6506. * chaining otherwise.
  6507. */
  6508. this.imgSrcSanitizationWhitelist = function(regexp) {
  6509. if (isDefined(regexp)) {
  6510. $$sanitizeUriProvider.imgSrcSanitizationWhitelist(regexp);
  6511. return this;
  6512. } else {
  6513. return $$sanitizeUriProvider.imgSrcSanitizationWhitelist();
  6514. }
  6515. };
  6516. /**
  6517. * @ngdoc method
  6518. * @name $compileProvider#debugInfoEnabled
  6519. *
  6520. * @param {boolean=} enabled update the debugInfoEnabled state if provided, otherwise just return the
  6521. * current debugInfoEnabled state
  6522. * @returns {*} current value if used as getter or itself (chaining) if used as setter
  6523. *
  6524. * @kind function
  6525. *
  6526. * @description
  6527. * Call this method to enable/disable various debug runtime information in the compiler such as adding
  6528. * binding information and a reference to the current scope on to DOM elements.
  6529. * If enabled, the compiler will add the following to DOM elements that have been bound to the scope
  6530. * * `ng-binding` CSS class
  6531. * * `$binding` data property containing an array of the binding expressions
  6532. *
  6533. * You may want to disable this in production for a significant performance boost. See
  6534. * {@link guide/production#disabling-debug-data Disabling Debug Data} for more.
  6535. *
  6536. * The default value is true.
  6537. */
  6538. var debugInfoEnabled = true;
  6539. this.debugInfoEnabled = function(enabled) {
  6540. if (isDefined(enabled)) {
  6541. debugInfoEnabled = enabled;
  6542. return this;
  6543. }
  6544. return debugInfoEnabled;
  6545. };
  6546. this.$get = [
  6547. '$injector', '$interpolate', '$exceptionHandler', '$templateRequest', '$parse',
  6548. '$controller', '$rootScope', '$document', '$sce', '$animate', '$$sanitizeUri',
  6549. function($injector, $interpolate, $exceptionHandler, $templateRequest, $parse,
  6550. $controller, $rootScope, $document, $sce, $animate, $$sanitizeUri) {
  6551. var Attributes = function(element, attributesToCopy) {
  6552. if (attributesToCopy) {
  6553. var keys = Object.keys(attributesToCopy);
  6554. var i, l, key;
  6555. for (i = 0, l = keys.length; i < l; i++) {
  6556. key = keys[i];
  6557. this[key] = attributesToCopy[key];
  6558. }
  6559. } else {
  6560. this.$attr = {};
  6561. }
  6562. this.$$element = element;
  6563. };
  6564. Attributes.prototype = {
  6565. /**
  6566. * @ngdoc method
  6567. * @name $compile.directive.Attributes#$normalize
  6568. * @kind function
  6569. *
  6570. * @description
  6571. * Converts an attribute name (e.g. dash/colon/underscore-delimited string, optionally prefixed with `x-` or
  6572. * `data-`) to its normalized, camelCase form.
  6573. *
  6574. * Also there is special case for Moz prefix starting with upper case letter.
  6575. *
  6576. * For further information check out the guide on {@link guide/directive#matching-directives Matching Directives}
  6577. *
  6578. * @param {string} name Name to normalize
  6579. */
  6580. $normalize: directiveNormalize,
  6581. /**
  6582. * @ngdoc method
  6583. * @name $compile.directive.Attributes#$addClass
  6584. * @kind function
  6585. *
  6586. * @description
  6587. * Adds the CSS class value specified by the classVal parameter to the element. If animations
  6588. * are enabled then an animation will be triggered for the class addition.
  6589. *
  6590. * @param {string} classVal The className value that will be added to the element
  6591. */
  6592. $addClass: function(classVal) {
  6593. if (classVal && classVal.length > 0) {
  6594. $animate.addClass(this.$$element, classVal);
  6595. }
  6596. },
  6597. /**
  6598. * @ngdoc method
  6599. * @name $compile.directive.Attributes#$removeClass
  6600. * @kind function
  6601. *
  6602. * @description
  6603. * Removes the CSS class value specified by the classVal parameter from the element. If
  6604. * animations are enabled then an animation will be triggered for the class removal.
  6605. *
  6606. * @param {string} classVal The className value that will be removed from the element
  6607. */
  6608. $removeClass: function(classVal) {
  6609. if (classVal && classVal.length > 0) {
  6610. $animate.removeClass(this.$$element, classVal);
  6611. }
  6612. },
  6613. /**
  6614. * @ngdoc method
  6615. * @name $compile.directive.Attributes#$updateClass
  6616. * @kind function
  6617. *
  6618. * @description
  6619. * Adds and removes the appropriate CSS class values to the element based on the difference
  6620. * between the new and old CSS class values (specified as newClasses and oldClasses).
  6621. *
  6622. * @param {string} newClasses The current CSS className value
  6623. * @param {string} oldClasses The former CSS className value
  6624. */
  6625. $updateClass: function(newClasses, oldClasses) {
  6626. var toAdd = tokenDifference(newClasses, oldClasses);
  6627. if (toAdd && toAdd.length) {
  6628. $animate.addClass(this.$$element, toAdd);
  6629. }
  6630. var toRemove = tokenDifference(oldClasses, newClasses);
  6631. if (toRemove && toRemove.length) {
  6632. $animate.removeClass(this.$$element, toRemove);
  6633. }
  6634. },
  6635. /**
  6636. * Set a normalized attribute on the element in a way such that all directives
  6637. * can share the attribute. This function properly handles boolean attributes.
  6638. * @param {string} key Normalized key. (ie ngAttribute)
  6639. * @param {string|boolean} value The value to set. If `null` attribute will be deleted.
  6640. * @param {boolean=} writeAttr If false, does not write the value to DOM element attribute.
  6641. * Defaults to true.
  6642. * @param {string=} attrName Optional none normalized name. Defaults to key.
  6643. */
  6644. $set: function(key, value, writeAttr, attrName) {
  6645. // TODO: decide whether or not to throw an error if "class"
  6646. //is set through this function since it may cause $updateClass to
  6647. //become unstable.
  6648. var node = this.$$element[0],
  6649. booleanKey = getBooleanAttrName(node, key),
  6650. aliasedKey = getAliasedAttrName(key),
  6651. observer = key,
  6652. nodeName;
  6653. if (booleanKey) {
  6654. this.$$element.prop(key, value);
  6655. attrName = booleanKey;
  6656. } else if (aliasedKey) {
  6657. this[aliasedKey] = value;
  6658. observer = aliasedKey;
  6659. }
  6660. this[key] = value;
  6661. // translate normalized key to actual key
  6662. if (attrName) {
  6663. this.$attr[key] = attrName;
  6664. } else {
  6665. attrName = this.$attr[key];
  6666. if (!attrName) {
  6667. this.$attr[key] = attrName = snake_case(key, '-');
  6668. }
  6669. }
  6670. nodeName = nodeName_(this.$$element);
  6671. if ((nodeName === 'a' && key === 'href') ||
  6672. (nodeName === 'img' && key === 'src')) {
  6673. // sanitize a[href] and img[src] values
  6674. this[key] = value = $$sanitizeUri(value, key === 'src');
  6675. } else if (nodeName === 'img' && key === 'srcset') {
  6676. // sanitize img[srcset] values
  6677. var result = "";
  6678. // first check if there are spaces because it's not the same pattern
  6679. var trimmedSrcset = trim(value);
  6680. // ( 999x ,| 999w ,| ,|, )
  6681. var srcPattern = /(\s+\d+x\s*,|\s+\d+w\s*,|\s+,|,\s+)/;
  6682. var pattern = /\s/.test(trimmedSrcset) ? srcPattern : /(,)/;
  6683. // split srcset into tuple of uri and descriptor except for the last item
  6684. var rawUris = trimmedSrcset.split(pattern);
  6685. // for each tuples
  6686. var nbrUrisWith2parts = Math.floor(rawUris.length / 2);
  6687. for (var i = 0; i < nbrUrisWith2parts; i++) {
  6688. var innerIdx = i * 2;
  6689. // sanitize the uri
  6690. result += $$sanitizeUri(trim(rawUris[innerIdx]), true);
  6691. // add the descriptor
  6692. result += (" " + trim(rawUris[innerIdx + 1]));
  6693. }
  6694. // split the last item into uri and descriptor
  6695. var lastTuple = trim(rawUris[i * 2]).split(/\s/);
  6696. // sanitize the last uri
  6697. result += $$sanitizeUri(trim(lastTuple[0]), true);
  6698. // and add the last descriptor if any
  6699. if (lastTuple.length === 2) {
  6700. result += (" " + trim(lastTuple[1]));
  6701. }
  6702. this[key] = value = result;
  6703. }
  6704. if (writeAttr !== false) {
  6705. if (value === null || isUndefined(value)) {
  6706. this.$$element.removeAttr(attrName);
  6707. } else {
  6708. this.$$element.attr(attrName, value);
  6709. }
  6710. }
  6711. // fire observers
  6712. var $$observers = this.$$observers;
  6713. $$observers && forEach($$observers[observer], function(fn) {
  6714. try {
  6715. fn(value);
  6716. } catch (e) {
  6717. $exceptionHandler(e);
  6718. }
  6719. });
  6720. },
  6721. /**
  6722. * @ngdoc method
  6723. * @name $compile.directive.Attributes#$observe
  6724. * @kind function
  6725. *
  6726. * @description
  6727. * Observes an interpolated attribute.
  6728. *
  6729. * The observer function will be invoked once during the next `$digest` following
  6730. * compilation. The observer is then invoked whenever the interpolated value
  6731. * changes.
  6732. *
  6733. * @param {string} key Normalized key. (ie ngAttribute) .
  6734. * @param {function(interpolatedValue)} fn Function that will be called whenever
  6735. the interpolated value of the attribute changes.
  6736. * See the {@link guide/directive#text-and-attribute-bindings Directives} guide for more info.
  6737. * @returns {function()} Returns a deregistration function for this observer.
  6738. */
  6739. $observe: function(key, fn) {
  6740. var attrs = this,
  6741. $$observers = (attrs.$$observers || (attrs.$$observers = createMap())),
  6742. listeners = ($$observers[key] || ($$observers[key] = []));
  6743. listeners.push(fn);
  6744. $rootScope.$evalAsync(function() {
  6745. if (!listeners.$$inter && attrs.hasOwnProperty(key) && !isUndefined(attrs[key])) {
  6746. // no one registered attribute interpolation function, so lets call it manually
  6747. fn(attrs[key]);
  6748. }
  6749. });
  6750. return function() {
  6751. arrayRemove(listeners, fn);
  6752. };
  6753. }
  6754. };
  6755. function safeAddClass($element, className) {
  6756. try {
  6757. $element.addClass(className);
  6758. } catch (e) {
  6759. // ignore, since it means that we are trying to set class on
  6760. // SVG element, where class name is read-only.
  6761. }
  6762. }
  6763. var startSymbol = $interpolate.startSymbol(),
  6764. endSymbol = $interpolate.endSymbol(),
  6765. denormalizeTemplate = (startSymbol == '{{' || endSymbol == '}}')
  6766. ? identity
  6767. : function denormalizeTemplate(template) {
  6768. return template.replace(/\{\{/g, startSymbol).replace(/}}/g, endSymbol);
  6769. },
  6770. NG_ATTR_BINDING = /^ngAttr[A-Z]/;
  6771. compile.$$addBindingInfo = debugInfoEnabled ? function $$addBindingInfo($element, binding) {
  6772. var bindings = $element.data('$binding') || [];
  6773. if (isArray(binding)) {
  6774. bindings = bindings.concat(binding);
  6775. } else {
  6776. bindings.push(binding);
  6777. }
  6778. $element.data('$binding', bindings);
  6779. } : noop;
  6780. compile.$$addBindingClass = debugInfoEnabled ? function $$addBindingClass($element) {
  6781. safeAddClass($element, 'ng-binding');
  6782. } : noop;
  6783. compile.$$addScopeInfo = debugInfoEnabled ? function $$addScopeInfo($element, scope, isolated, noTemplate) {
  6784. var dataName = isolated ? (noTemplate ? '$isolateScopeNoTemplate' : '$isolateScope') : '$scope';
  6785. $element.data(dataName, scope);
  6786. } : noop;
  6787. compile.$$addScopeClass = debugInfoEnabled ? function $$addScopeClass($element, isolated) {
  6788. safeAddClass($element, isolated ? 'ng-isolate-scope' : 'ng-scope');
  6789. } : noop;
  6790. return compile;
  6791. //================================
  6792. function compile($compileNodes, transcludeFn, maxPriority, ignoreDirective,
  6793. previousCompileContext) {
  6794. if (!($compileNodes instanceof jqLite)) {
  6795. // jquery always rewraps, whereas we need to preserve the original selector so that we can
  6796. // modify it.
  6797. $compileNodes = jqLite($compileNodes);
  6798. }
  6799. // We can not compile top level text elements since text nodes can be merged and we will
  6800. // not be able to attach scope data to them, so we will wrap them in <span>
  6801. forEach($compileNodes, function(node, index) {
  6802. if (node.nodeType == NODE_TYPE_TEXT && node.nodeValue.match(/\S+/) /* non-empty */ ) {
  6803. $compileNodes[index] = jqLite(node).wrap('<span></span>').parent()[0];
  6804. }
  6805. });
  6806. var compositeLinkFn =
  6807. compileNodes($compileNodes, transcludeFn, $compileNodes,
  6808. maxPriority, ignoreDirective, previousCompileContext);
  6809. compile.$$addScopeClass($compileNodes);
  6810. var namespace = null;
  6811. return function publicLinkFn(scope, cloneConnectFn, options) {
  6812. assertArg(scope, 'scope');
  6813. options = options || {};
  6814. var parentBoundTranscludeFn = options.parentBoundTranscludeFn,
  6815. transcludeControllers = options.transcludeControllers,
  6816. futureParentElement = options.futureParentElement;
  6817. // When `parentBoundTranscludeFn` is passed, it is a
  6818. // `controllersBoundTransclude` function (it was previously passed
  6819. // as `transclude` to directive.link) so we must unwrap it to get
  6820. // its `boundTranscludeFn`
  6821. if (parentBoundTranscludeFn && parentBoundTranscludeFn.$$boundTransclude) {
  6822. parentBoundTranscludeFn = parentBoundTranscludeFn.$$boundTransclude;
  6823. }
  6824. if (!namespace) {
  6825. namespace = detectNamespaceForChildElements(futureParentElement);
  6826. }
  6827. var $linkNode;
  6828. if (namespace !== 'html') {
  6829. // When using a directive with replace:true and templateUrl the $compileNodes
  6830. // (or a child element inside of them)
  6831. // might change, so we need to recreate the namespace adapted compileNodes
  6832. // for call to the link function.
  6833. // Note: This will already clone the nodes...
  6834. $linkNode = jqLite(
  6835. wrapTemplate(namespace, jqLite('<div>').append($compileNodes).html())
  6836. );
  6837. } else if (cloneConnectFn) {
  6838. // important!!: we must call our jqLite.clone() since the jQuery one is trying to be smart
  6839. // and sometimes changes the structure of the DOM.
  6840. $linkNode = JQLitePrototype.clone.call($compileNodes);
  6841. } else {
  6842. $linkNode = $compileNodes;
  6843. }
  6844. if (transcludeControllers) {
  6845. for (var controllerName in transcludeControllers) {
  6846. $linkNode.data('$' + controllerName + 'Controller', transcludeControllers[controllerName].instance);
  6847. }
  6848. }
  6849. compile.$$addScopeInfo($linkNode, scope);
  6850. if (cloneConnectFn) cloneConnectFn($linkNode, scope);
  6851. if (compositeLinkFn) compositeLinkFn(scope, $linkNode, $linkNode, parentBoundTranscludeFn);
  6852. return $linkNode;
  6853. };
  6854. }
  6855. function detectNamespaceForChildElements(parentElement) {
  6856. // TODO: Make this detect MathML as well...
  6857. var node = parentElement && parentElement[0];
  6858. if (!node) {
  6859. return 'html';
  6860. } else {
  6861. return nodeName_(node) !== 'foreignobject' && node.toString().match(/SVG/) ? 'svg' : 'html';
  6862. }
  6863. }
  6864. /**
  6865. * Compile function matches each node in nodeList against the directives. Once all directives
  6866. * for a particular node are collected their compile functions are executed. The compile
  6867. * functions return values - the linking functions - are combined into a composite linking
  6868. * function, which is the a linking function for the node.
  6869. *
  6870. * @param {NodeList} nodeList an array of nodes or NodeList to compile
  6871. * @param {function(angular.Scope, cloneAttachFn=)} transcludeFn A linking function, where the
  6872. * scope argument is auto-generated to the new child of the transcluded parent scope.
  6873. * @param {DOMElement=} $rootElement If the nodeList is the root of the compilation tree then
  6874. * the rootElement must be set the jqLite collection of the compile root. This is
  6875. * needed so that the jqLite collection items can be replaced with widgets.
  6876. * @param {number=} maxPriority Max directive priority.
  6877. * @returns {Function} A composite linking function of all of the matched directives or null.
  6878. */
  6879. function compileNodes(nodeList, transcludeFn, $rootElement, maxPriority, ignoreDirective,
  6880. previousCompileContext) {
  6881. var linkFns = [],
  6882. attrs, directives, nodeLinkFn, childNodes, childLinkFn, linkFnFound, nodeLinkFnFound;
  6883. for (var i = 0; i < nodeList.length; i++) {
  6884. attrs = new Attributes();
  6885. // we must always refer to nodeList[i] since the nodes can be replaced underneath us.
  6886. directives = collectDirectives(nodeList[i], [], attrs, i === 0 ? maxPriority : undefined,
  6887. ignoreDirective);
  6888. nodeLinkFn = (directives.length)
  6889. ? applyDirectivesToNode(directives, nodeList[i], attrs, transcludeFn, $rootElement,
  6890. null, [], [], previousCompileContext)
  6891. : null;
  6892. if (nodeLinkFn && nodeLinkFn.scope) {
  6893. compile.$$addScopeClass(attrs.$$element);
  6894. }
  6895. childLinkFn = (nodeLinkFn && nodeLinkFn.terminal ||
  6896. !(childNodes = nodeList[i].childNodes) ||
  6897. !childNodes.length)
  6898. ? null
  6899. : compileNodes(childNodes,
  6900. nodeLinkFn ? (
  6901. (nodeLinkFn.transcludeOnThisElement || !nodeLinkFn.templateOnThisElement)
  6902. && nodeLinkFn.transclude) : transcludeFn);
  6903. if (nodeLinkFn || childLinkFn) {
  6904. linkFns.push(i, nodeLinkFn, childLinkFn);
  6905. linkFnFound = true;
  6906. nodeLinkFnFound = nodeLinkFnFound || nodeLinkFn;
  6907. }
  6908. //use the previous context only for the first element in the virtual group
  6909. previousCompileContext = null;
  6910. }
  6911. // return a linking function if we have found anything, null otherwise
  6912. return linkFnFound ? compositeLinkFn : null;
  6913. function compositeLinkFn(scope, nodeList, $rootElement, parentBoundTranscludeFn) {
  6914. var nodeLinkFn, childLinkFn, node, childScope, i, ii, idx, childBoundTranscludeFn;
  6915. var stableNodeList;
  6916. if (nodeLinkFnFound) {
  6917. // copy nodeList so that if a nodeLinkFn removes or adds an element at this DOM level our
  6918. // offsets don't get screwed up
  6919. var nodeListLength = nodeList.length;
  6920. stableNodeList = new Array(nodeListLength);
  6921. // create a sparse array by only copying the elements which have a linkFn
  6922. for (i = 0; i < linkFns.length; i+=3) {
  6923. idx = linkFns[i];
  6924. stableNodeList[idx] = nodeList[idx];
  6925. }
  6926. } else {
  6927. stableNodeList = nodeList;
  6928. }
  6929. for (i = 0, ii = linkFns.length; i < ii;) {
  6930. node = stableNodeList[linkFns[i++]];
  6931. nodeLinkFn = linkFns[i++];
  6932. childLinkFn = linkFns[i++];
  6933. if (nodeLinkFn) {
  6934. if (nodeLinkFn.scope) {
  6935. childScope = scope.$new();
  6936. compile.$$addScopeInfo(jqLite(node), childScope);
  6937. var destroyBindings = nodeLinkFn.$$destroyBindings;
  6938. if (destroyBindings) {
  6939. nodeLinkFn.$$destroyBindings = null;
  6940. childScope.$on('$destroyed', destroyBindings);
  6941. }
  6942. } else {
  6943. childScope = scope;
  6944. }
  6945. if (nodeLinkFn.transcludeOnThisElement) {
  6946. childBoundTranscludeFn = createBoundTranscludeFn(
  6947. scope, nodeLinkFn.transclude, parentBoundTranscludeFn);
  6948. } else if (!nodeLinkFn.templateOnThisElement && parentBoundTranscludeFn) {
  6949. childBoundTranscludeFn = parentBoundTranscludeFn;
  6950. } else if (!parentBoundTranscludeFn && transcludeFn) {
  6951. childBoundTranscludeFn = createBoundTranscludeFn(scope, transcludeFn);
  6952. } else {
  6953. childBoundTranscludeFn = null;
  6954. }
  6955. nodeLinkFn(childLinkFn, childScope, node, $rootElement, childBoundTranscludeFn,
  6956. nodeLinkFn);
  6957. } else if (childLinkFn) {
  6958. childLinkFn(scope, node.childNodes, undefined, parentBoundTranscludeFn);
  6959. }
  6960. }
  6961. }
  6962. }
  6963. function createBoundTranscludeFn(scope, transcludeFn, previousBoundTranscludeFn) {
  6964. var boundTranscludeFn = function(transcludedScope, cloneFn, controllers, futureParentElement, containingScope) {
  6965. if (!transcludedScope) {
  6966. transcludedScope = scope.$new(false, containingScope);
  6967. transcludedScope.$$transcluded = true;
  6968. }
  6969. return transcludeFn(transcludedScope, cloneFn, {
  6970. parentBoundTranscludeFn: previousBoundTranscludeFn,
  6971. transcludeControllers: controllers,
  6972. futureParentElement: futureParentElement
  6973. });
  6974. };
  6975. return boundTranscludeFn;
  6976. }
  6977. /**
  6978. * Looks for directives on the given node and adds them to the directive collection which is
  6979. * sorted.
  6980. *
  6981. * @param node Node to search.
  6982. * @param directives An array to which the directives are added to. This array is sorted before
  6983. * the function returns.
  6984. * @param attrs The shared attrs object which is used to populate the normalized attributes.
  6985. * @param {number=} maxPriority Max directive priority.
  6986. */
  6987. function collectDirectives(node, directives, attrs, maxPriority, ignoreDirective) {
  6988. var nodeType = node.nodeType,
  6989. attrsMap = attrs.$attr,
  6990. match,
  6991. className;
  6992. switch (nodeType) {
  6993. case NODE_TYPE_ELEMENT: /* Element */
  6994. // use the node name: <directive>
  6995. addDirective(directives,
  6996. directiveNormalize(nodeName_(node)), 'E', maxPriority, ignoreDirective);
  6997. // iterate over the attributes
  6998. for (var attr, name, nName, ngAttrName, value, isNgAttr, nAttrs = node.attributes,
  6999. j = 0, jj = nAttrs && nAttrs.length; j < jj; j++) {
  7000. var attrStartName = false;
  7001. var attrEndName = false;
  7002. attr = nAttrs[j];
  7003. name = attr.name;
  7004. value = trim(attr.value);
  7005. // support ngAttr attribute binding
  7006. ngAttrName = directiveNormalize(name);
  7007. if (isNgAttr = NG_ATTR_BINDING.test(ngAttrName)) {
  7008. name = name.replace(PREFIX_REGEXP, '')
  7009. .substr(8).replace(/_(.)/g, function(match, letter) {
  7010. return letter.toUpperCase();
  7011. });
  7012. }
  7013. var directiveNName = ngAttrName.replace(/(Start|End)$/, '');
  7014. if (directiveIsMultiElement(directiveNName)) {
  7015. if (ngAttrName === directiveNName + 'Start') {
  7016. attrStartName = name;
  7017. attrEndName = name.substr(0, name.length - 5) + 'end';
  7018. name = name.substr(0, name.length - 6);
  7019. }
  7020. }
  7021. nName = directiveNormalize(name.toLowerCase());
  7022. attrsMap[nName] = name;
  7023. if (isNgAttr || !attrs.hasOwnProperty(nName)) {
  7024. attrs[nName] = value;
  7025. if (getBooleanAttrName(node, nName)) {
  7026. attrs[nName] = true; // presence means true
  7027. }
  7028. }
  7029. addAttrInterpolateDirective(node, directives, value, nName, isNgAttr);
  7030. addDirective(directives, nName, 'A', maxPriority, ignoreDirective, attrStartName,
  7031. attrEndName);
  7032. }
  7033. // use class as directive
  7034. className = node.className;
  7035. if (isObject(className)) {
  7036. // Maybe SVGAnimatedString
  7037. className = className.animVal;
  7038. }
  7039. if (isString(className) && className !== '') {
  7040. while (match = CLASS_DIRECTIVE_REGEXP.exec(className)) {
  7041. nName = directiveNormalize(match[2]);
  7042. if (addDirective(directives, nName, 'C', maxPriority, ignoreDirective)) {
  7043. attrs[nName] = trim(match[3]);
  7044. }
  7045. className = className.substr(match.index + match[0].length);
  7046. }
  7047. }
  7048. break;
  7049. case NODE_TYPE_TEXT: /* Text Node */
  7050. if (msie === 11) {
  7051. // Workaround for #11781
  7052. while (node.parentNode && node.nextSibling && node.nextSibling.nodeType === NODE_TYPE_TEXT) {
  7053. node.nodeValue = node.nodeValue + node.nextSibling.nodeValue;
  7054. node.parentNode.removeChild(node.nextSibling);
  7055. }
  7056. }
  7057. addTextInterpolateDirective(directives, node.nodeValue);
  7058. break;
  7059. case NODE_TYPE_COMMENT: /* Comment */
  7060. try {
  7061. match = COMMENT_DIRECTIVE_REGEXP.exec(node.nodeValue);
  7062. if (match) {
  7063. nName = directiveNormalize(match[1]);
  7064. if (addDirective(directives, nName, 'M', maxPriority, ignoreDirective)) {
  7065. attrs[nName] = trim(match[2]);
  7066. }
  7067. }
  7068. } catch (e) {
  7069. // turns out that under some circumstances IE9 throws errors when one attempts to read
  7070. // comment's node value.
  7071. // Just ignore it and continue. (Can't seem to reproduce in test case.)
  7072. }
  7073. break;
  7074. }
  7075. directives.sort(byPriority);
  7076. return directives;
  7077. }
  7078. /**
  7079. * Given a node with an directive-start it collects all of the siblings until it finds
  7080. * directive-end.
  7081. * @param node
  7082. * @param attrStart
  7083. * @param attrEnd
  7084. * @returns {*}
  7085. */
  7086. function groupScan(node, attrStart, attrEnd) {
  7087. var nodes = [];
  7088. var depth = 0;
  7089. if (attrStart && node.hasAttribute && node.hasAttribute(attrStart)) {
  7090. do {
  7091. if (!node) {
  7092. throw $compileMinErr('uterdir',
  7093. "Unterminated attribute, found '{0}' but no matching '{1}' found.",
  7094. attrStart, attrEnd);
  7095. }
  7096. if (node.nodeType == NODE_TYPE_ELEMENT) {
  7097. if (node.hasAttribute(attrStart)) depth++;
  7098. if (node.hasAttribute(attrEnd)) depth--;
  7099. }
  7100. nodes.push(node);
  7101. node = node.nextSibling;
  7102. } while (depth > 0);
  7103. } else {
  7104. nodes.push(node);
  7105. }
  7106. return jqLite(nodes);
  7107. }
  7108. /**
  7109. * Wrapper for linking function which converts normal linking function into a grouped
  7110. * linking function.
  7111. * @param linkFn
  7112. * @param attrStart
  7113. * @param attrEnd
  7114. * @returns {Function}
  7115. */
  7116. function groupElementsLinkFnWrapper(linkFn, attrStart, attrEnd) {
  7117. return function(scope, element, attrs, controllers, transcludeFn) {
  7118. element = groupScan(element[0], attrStart, attrEnd);
  7119. return linkFn(scope, element, attrs, controllers, transcludeFn);
  7120. };
  7121. }
  7122. /**
  7123. * Once the directives have been collected, their compile functions are executed. This method
  7124. * is responsible for inlining directive templates as well as terminating the application
  7125. * of the directives if the terminal directive has been reached.
  7126. *
  7127. * @param {Array} directives Array of collected directives to execute their compile function.
  7128. * this needs to be pre-sorted by priority order.
  7129. * @param {Node} compileNode The raw DOM node to apply the compile functions to
  7130. * @param {Object} templateAttrs The shared attribute function
  7131. * @param {function(angular.Scope, cloneAttachFn=)} transcludeFn A linking function, where the
  7132. * scope argument is auto-generated to the new
  7133. * child of the transcluded parent scope.
  7134. * @param {JQLite} jqCollection If we are working on the root of the compile tree then this
  7135. * argument has the root jqLite array so that we can replace nodes
  7136. * on it.
  7137. * @param {Object=} originalReplaceDirective An optional directive that will be ignored when
  7138. * compiling the transclusion.
  7139. * @param {Array.<Function>} preLinkFns
  7140. * @param {Array.<Function>} postLinkFns
  7141. * @param {Object} previousCompileContext Context used for previous compilation of the current
  7142. * node
  7143. * @returns {Function} linkFn
  7144. */
  7145. function applyDirectivesToNode(directives, compileNode, templateAttrs, transcludeFn,
  7146. jqCollection, originalReplaceDirective, preLinkFns, postLinkFns,
  7147. previousCompileContext) {
  7148. previousCompileContext = previousCompileContext || {};
  7149. var terminalPriority = -Number.MAX_VALUE,
  7150. newScopeDirective = previousCompileContext.newScopeDirective,
  7151. controllerDirectives = previousCompileContext.controllerDirectives,
  7152. newIsolateScopeDirective = previousCompileContext.newIsolateScopeDirective,
  7153. templateDirective = previousCompileContext.templateDirective,
  7154. nonTlbTranscludeDirective = previousCompileContext.nonTlbTranscludeDirective,
  7155. hasTranscludeDirective = false,
  7156. hasTemplate = false,
  7157. hasElementTranscludeDirective = previousCompileContext.hasElementTranscludeDirective,
  7158. $compileNode = templateAttrs.$$element = jqLite(compileNode),
  7159. directive,
  7160. directiveName,
  7161. $template,
  7162. replaceDirective = originalReplaceDirective,
  7163. childTranscludeFn = transcludeFn,
  7164. linkFn,
  7165. directiveValue;
  7166. // executes all directives on the current element
  7167. for (var i = 0, ii = directives.length; i < ii; i++) {
  7168. directive = directives[i];
  7169. var attrStart = directive.$$start;
  7170. var attrEnd = directive.$$end;
  7171. // collect multiblock sections
  7172. if (attrStart) {
  7173. $compileNode = groupScan(compileNode, attrStart, attrEnd);
  7174. }
  7175. $template = undefined;
  7176. if (terminalPriority > directive.priority) {
  7177. break; // prevent further processing of directives
  7178. }
  7179. if (directiveValue = directive.scope) {
  7180. // skip the check for directives with async templates, we'll check the derived sync
  7181. // directive when the template arrives
  7182. if (!directive.templateUrl) {
  7183. if (isObject(directiveValue)) {
  7184. // This directive is trying to add an isolated scope.
  7185. // Check that there is no scope of any kind already
  7186. assertNoDuplicate('new/isolated scope', newIsolateScopeDirective || newScopeDirective,
  7187. directive, $compileNode);
  7188. newIsolateScopeDirective = directive;
  7189. } else {
  7190. // This directive is trying to add a child scope.
  7191. // Check that there is no isolated scope already
  7192. assertNoDuplicate('new/isolated scope', newIsolateScopeDirective, directive,
  7193. $compileNode);
  7194. }
  7195. }
  7196. newScopeDirective = newScopeDirective || directive;
  7197. }
  7198. directiveName = directive.name;
  7199. if (!directive.templateUrl && directive.controller) {
  7200. directiveValue = directive.controller;
  7201. controllerDirectives = controllerDirectives || createMap();
  7202. assertNoDuplicate("'" + directiveName + "' controller",
  7203. controllerDirectives[directiveName], directive, $compileNode);
  7204. controllerDirectives[directiveName] = directive;
  7205. }
  7206. if (directiveValue = directive.transclude) {
  7207. hasTranscludeDirective = true;
  7208. // Special case ngIf and ngRepeat so that we don't complain about duplicate transclusion.
  7209. // This option should only be used by directives that know how to safely handle element transclusion,
  7210. // where the transcluded nodes are added or replaced after linking.
  7211. if (!directive.$$tlb) {
  7212. assertNoDuplicate('transclusion', nonTlbTranscludeDirective, directive, $compileNode);
  7213. nonTlbTranscludeDirective = directive;
  7214. }
  7215. if (directiveValue == 'element') {
  7216. hasElementTranscludeDirective = true;
  7217. terminalPriority = directive.priority;
  7218. $template = $compileNode;
  7219. $compileNode = templateAttrs.$$element =
  7220. jqLite(document.createComment(' ' + directiveName + ': ' +
  7221. templateAttrs[directiveName] + ' '));
  7222. compileNode = $compileNode[0];
  7223. replaceWith(jqCollection, sliceArgs($template), compileNode);
  7224. childTranscludeFn = compile($template, transcludeFn, terminalPriority,
  7225. replaceDirective && replaceDirective.name, {
  7226. // Don't pass in:
  7227. // - controllerDirectives - otherwise we'll create duplicates controllers
  7228. // - newIsolateScopeDirective or templateDirective - combining templates with
  7229. // element transclusion doesn't make sense.
  7230. //
  7231. // We need only nonTlbTranscludeDirective so that we prevent putting transclusion
  7232. // on the same element more than once.
  7233. nonTlbTranscludeDirective: nonTlbTranscludeDirective
  7234. });
  7235. } else {
  7236. $template = jqLite(jqLiteClone(compileNode)).contents();
  7237. $compileNode.empty(); // clear contents
  7238. childTranscludeFn = compile($template, transcludeFn);
  7239. }
  7240. }
  7241. if (directive.template) {
  7242. hasTemplate = true;
  7243. assertNoDuplicate('template', templateDirective, directive, $compileNode);
  7244. templateDirective = directive;
  7245. directiveValue = (isFunction(directive.template))
  7246. ? directive.template($compileNode, templateAttrs)
  7247. : directive.template;
  7248. directiveValue = denormalizeTemplate(directiveValue);
  7249. if (directive.replace) {
  7250. replaceDirective = directive;
  7251. if (jqLiteIsTextNode(directiveValue)) {
  7252. $template = [];
  7253. } else {
  7254. $template = removeComments(wrapTemplate(directive.templateNamespace, trim(directiveValue)));
  7255. }
  7256. compileNode = $template[0];
  7257. if ($template.length != 1 || compileNode.nodeType !== NODE_TYPE_ELEMENT) {
  7258. throw $compileMinErr('tplrt',
  7259. "Template for directive '{0}' must have exactly one root element. {1}",
  7260. directiveName, '');
  7261. }
  7262. replaceWith(jqCollection, $compileNode, compileNode);
  7263. var newTemplateAttrs = {$attr: {}};
  7264. // combine directives from the original node and from the template:
  7265. // - take the array of directives for this element
  7266. // - split it into two parts, those that already applied (processed) and those that weren't (unprocessed)
  7267. // - collect directives from the template and sort them by priority
  7268. // - combine directives as: processed + template + unprocessed
  7269. var templateDirectives = collectDirectives(compileNode, [], newTemplateAttrs);
  7270. var unprocessedDirectives = directives.splice(i + 1, directives.length - (i + 1));
  7271. if (newIsolateScopeDirective) {
  7272. markDirectivesAsIsolate(templateDirectives);
  7273. }
  7274. directives = directives.concat(templateDirectives).concat(unprocessedDirectives);
  7275. mergeTemplateAttributes(templateAttrs, newTemplateAttrs);
  7276. ii = directives.length;
  7277. } else {
  7278. $compileNode.html(directiveValue);
  7279. }
  7280. }
  7281. if (directive.templateUrl) {
  7282. hasTemplate = true;
  7283. assertNoDuplicate('template', templateDirective, directive, $compileNode);
  7284. templateDirective = directive;
  7285. if (directive.replace) {
  7286. replaceDirective = directive;
  7287. }
  7288. nodeLinkFn = compileTemplateUrl(directives.splice(i, directives.length - i), $compileNode,
  7289. templateAttrs, jqCollection, hasTranscludeDirective && childTranscludeFn, preLinkFns, postLinkFns, {
  7290. controllerDirectives: controllerDirectives,
  7291. newScopeDirective: (newScopeDirective !== directive) && newScopeDirective,
  7292. newIsolateScopeDirective: newIsolateScopeDirective,
  7293. templateDirective: templateDirective,
  7294. nonTlbTranscludeDirective: nonTlbTranscludeDirective
  7295. });
  7296. ii = directives.length;
  7297. } else if (directive.compile) {
  7298. try {
  7299. linkFn = directive.compile($compileNode, templateAttrs, childTranscludeFn);
  7300. if (isFunction(linkFn)) {
  7301. addLinkFns(null, linkFn, attrStart, attrEnd);
  7302. } else if (linkFn) {
  7303. addLinkFns(linkFn.pre, linkFn.post, attrStart, attrEnd);
  7304. }
  7305. } catch (e) {
  7306. $exceptionHandler(e, startingTag($compileNode));
  7307. }
  7308. }
  7309. if (directive.terminal) {
  7310. nodeLinkFn.terminal = true;
  7311. terminalPriority = Math.max(terminalPriority, directive.priority);
  7312. }
  7313. }
  7314. nodeLinkFn.scope = newScopeDirective && newScopeDirective.scope === true;
  7315. nodeLinkFn.transcludeOnThisElement = hasTranscludeDirective;
  7316. nodeLinkFn.templateOnThisElement = hasTemplate;
  7317. nodeLinkFn.transclude = childTranscludeFn;
  7318. previousCompileContext.hasElementTranscludeDirective = hasElementTranscludeDirective;
  7319. // might be normal or delayed nodeLinkFn depending on if templateUrl is present
  7320. return nodeLinkFn;
  7321. ////////////////////
  7322. function addLinkFns(pre, post, attrStart, attrEnd) {
  7323. if (pre) {
  7324. if (attrStart) pre = groupElementsLinkFnWrapper(pre, attrStart, attrEnd);
  7325. pre.require = directive.require;
  7326. pre.directiveName = directiveName;
  7327. if (newIsolateScopeDirective === directive || directive.$$isolateScope) {
  7328. pre = cloneAndAnnotateFn(pre, {isolateScope: true});
  7329. }
  7330. preLinkFns.push(pre);
  7331. }
  7332. if (post) {
  7333. if (attrStart) post = groupElementsLinkFnWrapper(post, attrStart, attrEnd);
  7334. post.require = directive.require;
  7335. post.directiveName = directiveName;
  7336. if (newIsolateScopeDirective === directive || directive.$$isolateScope) {
  7337. post = cloneAndAnnotateFn(post, {isolateScope: true});
  7338. }
  7339. postLinkFns.push(post);
  7340. }
  7341. }
  7342. function getControllers(directiveName, require, $element, elementControllers) {
  7343. var value;
  7344. if (isString(require)) {
  7345. var match = require.match(REQUIRE_PREFIX_REGEXP);
  7346. var name = require.substring(match[0].length);
  7347. var inheritType = match[1] || match[3];
  7348. var optional = match[2] === '?';
  7349. //If only parents then start at the parent element
  7350. if (inheritType === '^^') {
  7351. $element = $element.parent();
  7352. //Otherwise attempt getting the controller from elementControllers in case
  7353. //the element is transcluded (and has no data) and to avoid .data if possible
  7354. } else {
  7355. value = elementControllers && elementControllers[name];
  7356. value = value && value.instance;
  7357. }
  7358. if (!value) {
  7359. var dataName = '$' + name + 'Controller';
  7360. value = inheritType ? $element.inheritedData(dataName) : $element.data(dataName);
  7361. }
  7362. if (!value && !optional) {
  7363. throw $compileMinErr('ctreq',
  7364. "Controller '{0}', required by directive '{1}', can't be found!",
  7365. name, directiveName);
  7366. }
  7367. } else if (isArray(require)) {
  7368. value = [];
  7369. for (var i = 0, ii = require.length; i < ii; i++) {
  7370. value[i] = getControllers(directiveName, require[i], $element, elementControllers);
  7371. }
  7372. }
  7373. return value || null;
  7374. }
  7375. function setupControllers($element, attrs, transcludeFn, controllerDirectives, isolateScope, scope) {
  7376. var elementControllers = createMap();
  7377. for (var controllerKey in controllerDirectives) {
  7378. var directive = controllerDirectives[controllerKey];
  7379. var locals = {
  7380. $scope: directive === newIsolateScopeDirective || directive.$$isolateScope ? isolateScope : scope,
  7381. $element: $element,
  7382. $attrs: attrs,
  7383. $transclude: transcludeFn
  7384. };
  7385. var controller = directive.controller;
  7386. if (controller == '@') {
  7387. controller = attrs[directive.name];
  7388. }
  7389. var controllerInstance = $controller(controller, locals, true, directive.controllerAs);
  7390. // For directives with element transclusion the element is a comment,
  7391. // but jQuery .data doesn't support attaching data to comment nodes as it's hard to
  7392. // clean up (http://bugs.jquery.com/ticket/8335).
  7393. // Instead, we save the controllers for the element in a local hash and attach to .data
  7394. // later, once we have the actual element.
  7395. elementControllers[directive.name] = controllerInstance;
  7396. if (!hasElementTranscludeDirective) {
  7397. $element.data('$' + directive.name + 'Controller', controllerInstance.instance);
  7398. }
  7399. }
  7400. return elementControllers;
  7401. }
  7402. function nodeLinkFn(childLinkFn, scope, linkNode, $rootElement, boundTranscludeFn,
  7403. thisLinkFn) {
  7404. var i, ii, linkFn, controller, isolateScope, elementControllers, transcludeFn, $element,
  7405. attrs;
  7406. if (compileNode === linkNode) {
  7407. attrs = templateAttrs;
  7408. $element = templateAttrs.$$element;
  7409. } else {
  7410. $element = jqLite(linkNode);
  7411. attrs = new Attributes($element, templateAttrs);
  7412. }
  7413. if (newIsolateScopeDirective) {
  7414. isolateScope = scope.$new(true);
  7415. }
  7416. if (boundTranscludeFn) {
  7417. // track `boundTranscludeFn` so it can be unwrapped if `transcludeFn`
  7418. // is later passed as `parentBoundTranscludeFn` to `publicLinkFn`
  7419. transcludeFn = controllersBoundTransclude;
  7420. transcludeFn.$$boundTransclude = boundTranscludeFn;
  7421. }
  7422. if (controllerDirectives) {
  7423. elementControllers = setupControllers($element, attrs, transcludeFn, controllerDirectives, isolateScope, scope);
  7424. }
  7425. if (newIsolateScopeDirective) {
  7426. // Initialize isolate scope bindings for new isolate scope directive.
  7427. compile.$$addScopeInfo($element, isolateScope, true, !(templateDirective && (templateDirective === newIsolateScopeDirective ||
  7428. templateDirective === newIsolateScopeDirective.$$originalDirective)));
  7429. compile.$$addScopeClass($element, true);
  7430. isolateScope.$$isolateBindings =
  7431. newIsolateScopeDirective.$$isolateBindings;
  7432. initializeDirectiveBindings(scope, attrs, isolateScope,
  7433. isolateScope.$$isolateBindings,
  7434. newIsolateScopeDirective, isolateScope);
  7435. }
  7436. if (elementControllers) {
  7437. // Initialize bindToController bindings for new/isolate scopes
  7438. var scopeDirective = newIsolateScopeDirective || newScopeDirective;
  7439. var bindings;
  7440. var controllerForBindings;
  7441. if (scopeDirective && elementControllers[scopeDirective.name]) {
  7442. bindings = scopeDirective.$$bindings.bindToController;
  7443. controller = elementControllers[scopeDirective.name];
  7444. if (controller && controller.identifier && bindings) {
  7445. controllerForBindings = controller;
  7446. thisLinkFn.$$destroyBindings =
  7447. initializeDirectiveBindings(scope, attrs, controller.instance,
  7448. bindings, scopeDirective);
  7449. }
  7450. }
  7451. for (i in elementControllers) {
  7452. controller = elementControllers[i];
  7453. var controllerResult = controller();
  7454. if (controllerResult !== controller.instance) {
  7455. // If the controller constructor has a return value, overwrite the instance
  7456. // from setupControllers and update the element data
  7457. controller.instance = controllerResult;
  7458. $element.data('$' + i + 'Controller', controllerResult);
  7459. if (controller === controllerForBindings) {
  7460. // Remove and re-install bindToController bindings
  7461. thisLinkFn.$$destroyBindings();
  7462. thisLinkFn.$$destroyBindings =
  7463. initializeDirectiveBindings(scope, attrs, controllerResult, bindings, scopeDirective);
  7464. }
  7465. }
  7466. }
  7467. }
  7468. // PRELINKING
  7469. for (i = 0, ii = preLinkFns.length; i < ii; i++) {
  7470. linkFn = preLinkFns[i];
  7471. invokeLinkFn(linkFn,
  7472. linkFn.isolateScope ? isolateScope : scope,
  7473. $element,
  7474. attrs,
  7475. linkFn.require && getControllers(linkFn.directiveName, linkFn.require, $element, elementControllers),
  7476. transcludeFn
  7477. );
  7478. }
  7479. // RECURSION
  7480. // We only pass the isolate scope, if the isolate directive has a template,
  7481. // otherwise the child elements do not belong to the isolate directive.
  7482. var scopeToChild = scope;
  7483. if (newIsolateScopeDirective && (newIsolateScopeDirective.template || newIsolateScopeDirective.templateUrl === null)) {
  7484. scopeToChild = isolateScope;
  7485. }
  7486. childLinkFn && childLinkFn(scopeToChild, linkNode.childNodes, undefined, boundTranscludeFn);
  7487. // POSTLINKING
  7488. for (i = postLinkFns.length - 1; i >= 0; i--) {
  7489. linkFn = postLinkFns[i];
  7490. invokeLinkFn(linkFn,
  7491. linkFn.isolateScope ? isolateScope : scope,
  7492. $element,
  7493. attrs,
  7494. linkFn.require && getControllers(linkFn.directiveName, linkFn.require, $element, elementControllers),
  7495. transcludeFn
  7496. );
  7497. }
  7498. // This is the function that is injected as `$transclude`.
  7499. // Note: all arguments are optional!
  7500. function controllersBoundTransclude(scope, cloneAttachFn, futureParentElement) {
  7501. var transcludeControllers;
  7502. // No scope passed in:
  7503. if (!isScope(scope)) {
  7504. futureParentElement = cloneAttachFn;
  7505. cloneAttachFn = scope;
  7506. scope = undefined;
  7507. }
  7508. if (hasElementTranscludeDirective) {
  7509. transcludeControllers = elementControllers;
  7510. }
  7511. if (!futureParentElement) {
  7512. futureParentElement = hasElementTranscludeDirective ? $element.parent() : $element;
  7513. }
  7514. return boundTranscludeFn(scope, cloneAttachFn, transcludeControllers, futureParentElement, scopeToChild);
  7515. }
  7516. }
  7517. }
  7518. function markDirectivesAsIsolate(directives) {
  7519. // mark all directives as needing isolate scope.
  7520. for (var j = 0, jj = directives.length; j < jj; j++) {
  7521. directives[j] = inherit(directives[j], {$$isolateScope: true});
  7522. }
  7523. }
  7524. /**
  7525. * looks up the directive and decorates it with exception handling and proper parameters. We
  7526. * call this the boundDirective.
  7527. *
  7528. * @param {string} name name of the directive to look up.
  7529. * @param {string} location The directive must be found in specific format.
  7530. * String containing any of theses characters:
  7531. *
  7532. * * `E`: element name
  7533. * * `A': attribute
  7534. * * `C`: class
  7535. * * `M`: comment
  7536. * @returns {boolean} true if directive was added.
  7537. */
  7538. function addDirective(tDirectives, name, location, maxPriority, ignoreDirective, startAttrName,
  7539. endAttrName) {
  7540. if (name === ignoreDirective) return null;
  7541. var match = null;
  7542. if (hasDirectives.hasOwnProperty(name)) {
  7543. for (var directive, directives = $injector.get(name + Suffix),
  7544. i = 0, ii = directives.length; i < ii; i++) {
  7545. try {
  7546. directive = directives[i];
  7547. if ((isUndefined(maxPriority) || maxPriority > directive.priority) &&
  7548. directive.restrict.indexOf(location) != -1) {
  7549. if (startAttrName) {
  7550. directive = inherit(directive, {$$start: startAttrName, $$end: endAttrName});
  7551. }
  7552. tDirectives.push(directive);
  7553. match = directive;
  7554. }
  7555. } catch (e) { $exceptionHandler(e); }
  7556. }
  7557. }
  7558. return match;
  7559. }
  7560. /**
  7561. * looks up the directive and returns true if it is a multi-element directive,
  7562. * and therefore requires DOM nodes between -start and -end markers to be grouped
  7563. * together.
  7564. *
  7565. * @param {string} name name of the directive to look up.
  7566. * @returns true if directive was registered as multi-element.
  7567. */
  7568. function directiveIsMultiElement(name) {
  7569. if (hasDirectives.hasOwnProperty(name)) {
  7570. for (var directive, directives = $injector.get(name + Suffix),
  7571. i = 0, ii = directives.length; i < ii; i++) {
  7572. directive = directives[i];
  7573. if (directive.multiElement) {
  7574. return true;
  7575. }
  7576. }
  7577. }
  7578. return false;
  7579. }
  7580. /**
  7581. * When the element is replaced with HTML template then the new attributes
  7582. * on the template need to be merged with the existing attributes in the DOM.
  7583. * The desired effect is to have both of the attributes present.
  7584. *
  7585. * @param {object} dst destination attributes (original DOM)
  7586. * @param {object} src source attributes (from the directive template)
  7587. */
  7588. function mergeTemplateAttributes(dst, src) {
  7589. var srcAttr = src.$attr,
  7590. dstAttr = dst.$attr,
  7591. $element = dst.$$element;
  7592. // reapply the old attributes to the new element
  7593. forEach(dst, function(value, key) {
  7594. if (key.charAt(0) != '$') {
  7595. if (src[key] && src[key] !== value) {
  7596. value += (key === 'style' ? ';' : ' ') + src[key];
  7597. }
  7598. dst.$set(key, value, true, srcAttr[key]);
  7599. }
  7600. });
  7601. // copy the new attributes on the old attrs object
  7602. forEach(src, function(value, key) {
  7603. if (key == 'class') {
  7604. safeAddClass($element, value);
  7605. dst['class'] = (dst['class'] ? dst['class'] + ' ' : '') + value;
  7606. } else if (key == 'style') {
  7607. $element.attr('style', $element.attr('style') + ';' + value);
  7608. dst['style'] = (dst['style'] ? dst['style'] + ';' : '') + value;
  7609. // `dst` will never contain hasOwnProperty as DOM parser won't let it.
  7610. // You will get an "InvalidCharacterError: DOM Exception 5" error if you
  7611. // have an attribute like "has-own-property" or "data-has-own-property", etc.
  7612. } else if (key.charAt(0) != '$' && !dst.hasOwnProperty(key)) {
  7613. dst[key] = value;
  7614. dstAttr[key] = srcAttr[key];
  7615. }
  7616. });
  7617. }
  7618. function compileTemplateUrl(directives, $compileNode, tAttrs,
  7619. $rootElement, childTranscludeFn, preLinkFns, postLinkFns, previousCompileContext) {
  7620. var linkQueue = [],
  7621. afterTemplateNodeLinkFn,
  7622. afterTemplateChildLinkFn,
  7623. beforeTemplateCompileNode = $compileNode[0],
  7624. origAsyncDirective = directives.shift(),
  7625. derivedSyncDirective = inherit(origAsyncDirective, {
  7626. templateUrl: null, transclude: null, replace: null, $$originalDirective: origAsyncDirective
  7627. }),
  7628. templateUrl = (isFunction(origAsyncDirective.templateUrl))
  7629. ? origAsyncDirective.templateUrl($compileNode, tAttrs)
  7630. : origAsyncDirective.templateUrl,
  7631. templateNamespace = origAsyncDirective.templateNamespace;
  7632. $compileNode.empty();
  7633. $templateRequest(templateUrl)
  7634. .then(function(content) {
  7635. var compileNode, tempTemplateAttrs, $template, childBoundTranscludeFn;
  7636. content = denormalizeTemplate(content);
  7637. if (origAsyncDirective.replace) {
  7638. if (jqLiteIsTextNode(content)) {
  7639. $template = [];
  7640. } else {
  7641. $template = removeComments(wrapTemplate(templateNamespace, trim(content)));
  7642. }
  7643. compileNode = $template[0];
  7644. if ($template.length != 1 || compileNode.nodeType !== NODE_TYPE_ELEMENT) {
  7645. throw $compileMinErr('tplrt',
  7646. "Template for directive '{0}' must have exactly one root element. {1}",
  7647. origAsyncDirective.name, templateUrl);
  7648. }
  7649. tempTemplateAttrs = {$attr: {}};
  7650. replaceWith($rootElement, $compileNode, compileNode);
  7651. var templateDirectives = collectDirectives(compileNode, [], tempTemplateAttrs);
  7652. if (isObject(origAsyncDirective.scope)) {
  7653. markDirectivesAsIsolate(templateDirectives);
  7654. }
  7655. directives = templateDirectives.concat(directives);
  7656. mergeTemplateAttributes(tAttrs, tempTemplateAttrs);
  7657. } else {
  7658. compileNode = beforeTemplateCompileNode;
  7659. $compileNode.html(content);
  7660. }
  7661. directives.unshift(derivedSyncDirective);
  7662. afterTemplateNodeLinkFn = applyDirectivesToNode(directives, compileNode, tAttrs,
  7663. childTranscludeFn, $compileNode, origAsyncDirective, preLinkFns, postLinkFns,
  7664. previousCompileContext);
  7665. forEach($rootElement, function(node, i) {
  7666. if (node == compileNode) {
  7667. $rootElement[i] = $compileNode[0];
  7668. }
  7669. });
  7670. afterTemplateChildLinkFn = compileNodes($compileNode[0].childNodes, childTranscludeFn);
  7671. while (linkQueue.length) {
  7672. var scope = linkQueue.shift(),
  7673. beforeTemplateLinkNode = linkQueue.shift(),
  7674. linkRootElement = linkQueue.shift(),
  7675. boundTranscludeFn = linkQueue.shift(),
  7676. linkNode = $compileNode[0];
  7677. if (scope.$$destroyed) continue;
  7678. if (beforeTemplateLinkNode !== beforeTemplateCompileNode) {
  7679. var oldClasses = beforeTemplateLinkNode.className;
  7680. if (!(previousCompileContext.hasElementTranscludeDirective &&
  7681. origAsyncDirective.replace)) {
  7682. // it was cloned therefore we have to clone as well.
  7683. linkNode = jqLiteClone(compileNode);
  7684. }
  7685. replaceWith(linkRootElement, jqLite(beforeTemplateLinkNode), linkNode);
  7686. // Copy in CSS classes from original node
  7687. safeAddClass(jqLite(linkNode), oldClasses);
  7688. }
  7689. if (afterTemplateNodeLinkFn.transcludeOnThisElement) {
  7690. childBoundTranscludeFn = createBoundTranscludeFn(scope, afterTemplateNodeLinkFn.transclude, boundTranscludeFn);
  7691. } else {
  7692. childBoundTranscludeFn = boundTranscludeFn;
  7693. }
  7694. afterTemplateNodeLinkFn(afterTemplateChildLinkFn, scope, linkNode, $rootElement,
  7695. childBoundTranscludeFn, afterTemplateNodeLinkFn);
  7696. }
  7697. linkQueue = null;
  7698. });
  7699. return function delayedNodeLinkFn(ignoreChildLinkFn, scope, node, rootElement, boundTranscludeFn) {
  7700. var childBoundTranscludeFn = boundTranscludeFn;
  7701. if (scope.$$destroyed) return;
  7702. if (linkQueue) {
  7703. linkQueue.push(scope,
  7704. node,
  7705. rootElement,
  7706. childBoundTranscludeFn);
  7707. } else {
  7708. if (afterTemplateNodeLinkFn.transcludeOnThisElement) {
  7709. childBoundTranscludeFn = createBoundTranscludeFn(scope, afterTemplateNodeLinkFn.transclude, boundTranscludeFn);
  7710. }
  7711. afterTemplateNodeLinkFn(afterTemplateChildLinkFn, scope, node, rootElement, childBoundTranscludeFn,
  7712. afterTemplateNodeLinkFn);
  7713. }
  7714. };
  7715. }
  7716. /**
  7717. * Sorting function for bound directives.
  7718. */
  7719. function byPriority(a, b) {
  7720. var diff = b.priority - a.priority;
  7721. if (diff !== 0) return diff;
  7722. if (a.name !== b.name) return (a.name < b.name) ? -1 : 1;
  7723. return a.index - b.index;
  7724. }
  7725. function assertNoDuplicate(what, previousDirective, directive, element) {
  7726. function wrapModuleNameIfDefined(moduleName) {
  7727. return moduleName ?
  7728. (' (module: ' + moduleName + ')') :
  7729. '';
  7730. }
  7731. if (previousDirective) {
  7732. throw $compileMinErr('multidir', 'Multiple directives [{0}{1}, {2}{3}] asking for {4} on: {5}',
  7733. previousDirective.name, wrapModuleNameIfDefined(previousDirective.$$moduleName),
  7734. directive.name, wrapModuleNameIfDefined(directive.$$moduleName), what, startingTag(element));
  7735. }
  7736. }
  7737. function addTextInterpolateDirective(directives, text) {
  7738. var interpolateFn = $interpolate(text, true);
  7739. if (interpolateFn) {
  7740. directives.push({
  7741. priority: 0,
  7742. compile: function textInterpolateCompileFn(templateNode) {
  7743. var templateNodeParent = templateNode.parent(),
  7744. hasCompileParent = !!templateNodeParent.length;
  7745. // When transcluding a template that has bindings in the root
  7746. // we don't have a parent and thus need to add the class during linking fn.
  7747. if (hasCompileParent) compile.$$addBindingClass(templateNodeParent);
  7748. return function textInterpolateLinkFn(scope, node) {
  7749. var parent = node.parent();
  7750. if (!hasCompileParent) compile.$$addBindingClass(parent);
  7751. compile.$$addBindingInfo(parent, interpolateFn.expressions);
  7752. scope.$watch(interpolateFn, function interpolateFnWatchAction(value) {
  7753. node[0].nodeValue = value;
  7754. });
  7755. };
  7756. }
  7757. });
  7758. }
  7759. }
  7760. function wrapTemplate(type, template) {
  7761. type = lowercase(type || 'html');
  7762. switch (type) {
  7763. case 'svg':
  7764. case 'math':
  7765. var wrapper = document.createElement('div');
  7766. wrapper.innerHTML = '<' + type + '>' + template + '</' + type + '>';
  7767. return wrapper.childNodes[0].childNodes;
  7768. default:
  7769. return template;
  7770. }
  7771. }
  7772. function getTrustedContext(node, attrNormalizedName) {
  7773. if (attrNormalizedName == "srcdoc") {
  7774. return $sce.HTML;
  7775. }
  7776. var tag = nodeName_(node);
  7777. // maction[xlink:href] can source SVG. It's not limited to <maction>.
  7778. if (attrNormalizedName == "xlinkHref" ||
  7779. (tag == "form" && attrNormalizedName == "action") ||
  7780. (tag != "img" && (attrNormalizedName == "src" ||
  7781. attrNormalizedName == "ngSrc"))) {
  7782. return $sce.RESOURCE_URL;
  7783. }
  7784. }
  7785. function addAttrInterpolateDirective(node, directives, value, name, allOrNothing) {
  7786. var trustedContext = getTrustedContext(node, name);
  7787. allOrNothing = ALL_OR_NOTHING_ATTRS[name] || allOrNothing;
  7788. var interpolateFn = $interpolate(value, true, trustedContext, allOrNothing);
  7789. // no interpolation found -> ignore
  7790. if (!interpolateFn) return;
  7791. if (name === "multiple" && nodeName_(node) === "select") {
  7792. throw $compileMinErr("selmulti",
  7793. "Binding to the 'multiple' attribute is not supported. Element: {0}",
  7794. startingTag(node));
  7795. }
  7796. directives.push({
  7797. priority: 100,
  7798. compile: function() {
  7799. return {
  7800. pre: function attrInterpolatePreLinkFn(scope, element, attr) {
  7801. var $$observers = (attr.$$observers || (attr.$$observers = {}));
  7802. if (EVENT_HANDLER_ATTR_REGEXP.test(name)) {
  7803. throw $compileMinErr('nodomevents',
  7804. "Interpolations for HTML DOM event attributes are disallowed. Please use the " +
  7805. "ng- versions (such as ng-click instead of onclick) instead.");
  7806. }
  7807. // If the attribute has changed since last $interpolate()ed
  7808. var newValue = attr[name];
  7809. if (newValue !== value) {
  7810. // we need to interpolate again since the attribute value has been updated
  7811. // (e.g. by another directive's compile function)
  7812. // ensure unset/empty values make interpolateFn falsy
  7813. interpolateFn = newValue && $interpolate(newValue, true, trustedContext, allOrNothing);
  7814. value = newValue;
  7815. }
  7816. // if attribute was updated so that there is no interpolation going on we don't want to
  7817. // register any observers
  7818. if (!interpolateFn) return;
  7819. // initialize attr object so that it's ready in case we need the value for isolate
  7820. // scope initialization, otherwise the value would not be available from isolate
  7821. // directive's linking fn during linking phase
  7822. attr[name] = interpolateFn(scope);
  7823. ($$observers[name] || ($$observers[name] = [])).$$inter = true;
  7824. (attr.$$observers && attr.$$observers[name].$$scope || scope).
  7825. $watch(interpolateFn, function interpolateFnWatchAction(newValue, oldValue) {
  7826. //special case for class attribute addition + removal
  7827. //so that class changes can tap into the animation
  7828. //hooks provided by the $animate service. Be sure to
  7829. //skip animations when the first digest occurs (when
  7830. //both the new and the old values are the same) since
  7831. //the CSS classes are the non-interpolated values
  7832. if (name === 'class' && newValue != oldValue) {
  7833. attr.$updateClass(newValue, oldValue);
  7834. } else {
  7835. attr.$set(name, newValue);
  7836. }
  7837. });
  7838. }
  7839. };
  7840. }
  7841. });
  7842. }
  7843. /**
  7844. * This is a special jqLite.replaceWith, which can replace items which
  7845. * have no parents, provided that the containing jqLite collection is provided.
  7846. *
  7847. * @param {JqLite=} $rootElement The root of the compile tree. Used so that we can replace nodes
  7848. * in the root of the tree.
  7849. * @param {JqLite} elementsToRemove The jqLite element which we are going to replace. We keep
  7850. * the shell, but replace its DOM node reference.
  7851. * @param {Node} newNode The new DOM node.
  7852. */
  7853. function replaceWith($rootElement, elementsToRemove, newNode) {
  7854. var firstElementToRemove = elementsToRemove[0],
  7855. removeCount = elementsToRemove.length,
  7856. parent = firstElementToRemove.parentNode,
  7857. i, ii;
  7858. if ($rootElement) {
  7859. for (i = 0, ii = $rootElement.length; i < ii; i++) {
  7860. if ($rootElement[i] == firstElementToRemove) {
  7861. $rootElement[i++] = newNode;
  7862. for (var j = i, j2 = j + removeCount - 1,
  7863. jj = $rootElement.length;
  7864. j < jj; j++, j2++) {
  7865. if (j2 < jj) {
  7866. $rootElement[j] = $rootElement[j2];
  7867. } else {
  7868. delete $rootElement[j];
  7869. }
  7870. }
  7871. $rootElement.length -= removeCount - 1;
  7872. // If the replaced element is also the jQuery .context then replace it
  7873. // .context is a deprecated jQuery api, so we should set it only when jQuery set it
  7874. // http://api.jquery.com/context/
  7875. if ($rootElement.context === firstElementToRemove) {
  7876. $rootElement.context = newNode;
  7877. }
  7878. break;
  7879. }
  7880. }
  7881. }
  7882. if (parent) {
  7883. parent.replaceChild(newNode, firstElementToRemove);
  7884. }
  7885. // TODO(perf): what's this document fragment for? is it needed? can we at least reuse it?
  7886. var fragment = document.createDocumentFragment();
  7887. fragment.appendChild(firstElementToRemove);
  7888. if (jqLite.hasData(firstElementToRemove)) {
  7889. // Copy over user data (that includes Angular's $scope etc.). Don't copy private
  7890. // data here because there's no public interface in jQuery to do that and copying over
  7891. // event listeners (which is the main use of private data) wouldn't work anyway.
  7892. jqLite(newNode).data(jqLite(firstElementToRemove).data());
  7893. // Remove data of the replaced element. We cannot just call .remove()
  7894. // on the element it since that would deallocate scope that is needed
  7895. // for the new node. Instead, remove the data "manually".
  7896. if (!jQuery) {
  7897. delete jqLite.cache[firstElementToRemove[jqLite.expando]];
  7898. } else {
  7899. // jQuery 2.x doesn't expose the data storage. Use jQuery.cleanData to clean up after
  7900. // the replaced element. The cleanData version monkey-patched by Angular would cause
  7901. // the scope to be trashed and we do need the very same scope to work with the new
  7902. // element. However, we cannot just cache the non-patched version and use it here as
  7903. // that would break if another library patches the method after Angular does (one
  7904. // example is jQuery UI). Instead, set a flag indicating scope destroying should be
  7905. // skipped this one time.
  7906. skipDestroyOnNextJQueryCleanData = true;
  7907. jQuery.cleanData([firstElementToRemove]);
  7908. }
  7909. }
  7910. for (var k = 1, kk = elementsToRemove.length; k < kk; k++) {
  7911. var element = elementsToRemove[k];
  7912. jqLite(element).remove(); // must do this way to clean up expando
  7913. fragment.appendChild(element);
  7914. delete elementsToRemove[k];
  7915. }
  7916. elementsToRemove[0] = newNode;
  7917. elementsToRemove.length = 1;
  7918. }
  7919. function cloneAndAnnotateFn(fn, annotation) {
  7920. return extend(function() { return fn.apply(null, arguments); }, fn, annotation);
  7921. }
  7922. function invokeLinkFn(linkFn, scope, $element, attrs, controllers, transcludeFn) {
  7923. try {
  7924. linkFn(scope, $element, attrs, controllers, transcludeFn);
  7925. } catch (e) {
  7926. $exceptionHandler(e, startingTag($element));
  7927. }
  7928. }
  7929. // Set up $watches for isolate scope and controller bindings. This process
  7930. // only occurs for isolate scopes and new scopes with controllerAs.
  7931. function initializeDirectiveBindings(scope, attrs, destination, bindings,
  7932. directive, newScope) {
  7933. var onNewScopeDestroyed;
  7934. forEach(bindings, function(definition, scopeName) {
  7935. var attrName = definition.attrName,
  7936. optional = definition.optional,
  7937. mode = definition.mode, // @, =, or &
  7938. lastValue,
  7939. parentGet, parentSet, compare;
  7940. switch (mode) {
  7941. case '@':
  7942. if (!optional && !hasOwnProperty.call(attrs, attrName)) {
  7943. destination[scopeName] = attrs[attrName] = void 0;
  7944. }
  7945. attrs.$observe(attrName, function(value) {
  7946. if (isString(value)) {
  7947. destination[scopeName] = value;
  7948. }
  7949. });
  7950. attrs.$$observers[attrName].$$scope = scope;
  7951. if (isString(attrs[attrName])) {
  7952. // If the attribute has been provided then we trigger an interpolation to ensure
  7953. // the value is there for use in the link fn
  7954. destination[scopeName] = $interpolate(attrs[attrName])(scope);
  7955. }
  7956. break;
  7957. case '=':
  7958. if (!hasOwnProperty.call(attrs, attrName)) {
  7959. if (optional) break;
  7960. attrs[attrName] = void 0;
  7961. }
  7962. if (optional && !attrs[attrName]) break;
  7963. parentGet = $parse(attrs[attrName]);
  7964. if (parentGet.literal) {
  7965. compare = equals;
  7966. } else {
  7967. compare = function(a, b) { return a === b || (a !== a && b !== b); };
  7968. }
  7969. parentSet = parentGet.assign || function() {
  7970. // reset the change, or we will throw this exception on every $digest
  7971. lastValue = destination[scopeName] = parentGet(scope);
  7972. throw $compileMinErr('nonassign',
  7973. "Expression '{0}' used with directive '{1}' is non-assignable!",
  7974. attrs[attrName], directive.name);
  7975. };
  7976. lastValue = destination[scopeName] = parentGet(scope);
  7977. var parentValueWatch = function parentValueWatch(parentValue) {
  7978. if (!compare(parentValue, destination[scopeName])) {
  7979. // we are out of sync and need to copy
  7980. if (!compare(parentValue, lastValue)) {
  7981. // parent changed and it has precedence
  7982. destination[scopeName] = parentValue;
  7983. } else {
  7984. // if the parent can be assigned then do so
  7985. parentSet(scope, parentValue = destination[scopeName]);
  7986. }
  7987. }
  7988. return lastValue = parentValue;
  7989. };
  7990. parentValueWatch.$stateful = true;
  7991. var unwatch;
  7992. if (definition.collection) {
  7993. unwatch = scope.$watchCollection(attrs[attrName], parentValueWatch);
  7994. } else {
  7995. unwatch = scope.$watch($parse(attrs[attrName], parentValueWatch), null, parentGet.literal);
  7996. }
  7997. onNewScopeDestroyed = (onNewScopeDestroyed || []);
  7998. onNewScopeDestroyed.push(unwatch);
  7999. break;
  8000. case '&':
  8001. // Don't assign Object.prototype method to scope
  8002. parentGet = attrs.hasOwnProperty(attrName) ? $parse(attrs[attrName]) : noop;
  8003. // Don't assign noop to destination if expression is not valid
  8004. if (parentGet === noop && optional) break;
  8005. destination[scopeName] = function(locals) {
  8006. return parentGet(scope, locals);
  8007. };
  8008. break;
  8009. }
  8010. });
  8011. var destroyBindings = onNewScopeDestroyed ? function destroyBindings() {
  8012. for (var i = 0, ii = onNewScopeDestroyed.length; i < ii; ++i) {
  8013. onNewScopeDestroyed[i]();
  8014. }
  8015. } : noop;
  8016. if (newScope && destroyBindings !== noop) {
  8017. newScope.$on('$destroy', destroyBindings);
  8018. return noop;
  8019. }
  8020. return destroyBindings;
  8021. }
  8022. }];
  8023. }
  8024. var PREFIX_REGEXP = /^((?:x|data)[\:\-_])/i;
  8025. /**
  8026. * Converts all accepted directives format into proper directive name.
  8027. * @param name Name to normalize
  8028. */
  8029. function directiveNormalize(name) {
  8030. return camelCase(name.replace(PREFIX_REGEXP, ''));
  8031. }
  8032. /**
  8033. * @ngdoc type
  8034. * @name $compile.directive.Attributes
  8035. *
  8036. * @description
  8037. * A shared object between directive compile / linking functions which contains normalized DOM
  8038. * element attributes. The values reflect current binding state `{{ }}`. The normalization is
  8039. * needed since all of these are treated as equivalent in Angular:
  8040. *
  8041. * ```
  8042. * <span ng:bind="a" ng-bind="a" data-ng-bind="a" x-ng-bind="a">
  8043. * ```
  8044. */
  8045. /**
  8046. * @ngdoc property
  8047. * @name $compile.directive.Attributes#$attr
  8048. *
  8049. * @description
  8050. * A map of DOM element attribute names to the normalized name. This is
  8051. * needed to do reverse lookup from normalized name back to actual name.
  8052. */
  8053. /**
  8054. * @ngdoc method
  8055. * @name $compile.directive.Attributes#$set
  8056. * @kind function
  8057. *
  8058. * @description
  8059. * Set DOM element attribute value.
  8060. *
  8061. *
  8062. * @param {string} name Normalized element attribute name of the property to modify. The name is
  8063. * reverse-translated using the {@link ng.$compile.directive.Attributes#$attr $attr}
  8064. * property to the original name.
  8065. * @param {string} value Value to set the attribute to. The value can be an interpolated string.
  8066. */
  8067. /**
  8068. * Closure compiler type information
  8069. */
  8070. function nodesetLinkingFn(
  8071. /* angular.Scope */ scope,
  8072. /* NodeList */ nodeList,
  8073. /* Element */ rootElement,
  8074. /* function(Function) */ boundTranscludeFn
  8075. ) {}
  8076. function directiveLinkingFn(
  8077. /* nodesetLinkingFn */ nodesetLinkingFn,
  8078. /* angular.Scope */ scope,
  8079. /* Node */ node,
  8080. /* Element */ rootElement,
  8081. /* function(Function) */ boundTranscludeFn
  8082. ) {}
  8083. function tokenDifference(str1, str2) {
  8084. var values = '',
  8085. tokens1 = str1.split(/\s+/),
  8086. tokens2 = str2.split(/\s+/);
  8087. outer:
  8088. for (var i = 0; i < tokens1.length; i++) {
  8089. var token = tokens1[i];
  8090. for (var j = 0; j < tokens2.length; j++) {
  8091. if (token == tokens2[j]) continue outer;
  8092. }
  8093. values += (values.length > 0 ? ' ' : '') + token;
  8094. }
  8095. return values;
  8096. }
  8097. function removeComments(jqNodes) {
  8098. jqNodes = jqLite(jqNodes);
  8099. var i = jqNodes.length;
  8100. if (i <= 1) {
  8101. return jqNodes;
  8102. }
  8103. while (i--) {
  8104. var node = jqNodes[i];
  8105. if (node.nodeType === NODE_TYPE_COMMENT) {
  8106. splice.call(jqNodes, i, 1);
  8107. }
  8108. }
  8109. return jqNodes;
  8110. }
  8111. var $controllerMinErr = minErr('$controller');
  8112. var CNTRL_REG = /^(\S+)(\s+as\s+(\w+))?$/;
  8113. function identifierForController(controller, ident) {
  8114. if (ident && isString(ident)) return ident;
  8115. if (isString(controller)) {
  8116. var match = CNTRL_REG.exec(controller);
  8117. if (match) return match[3];
  8118. }
  8119. }
  8120. /**
  8121. * @ngdoc provider
  8122. * @name $controllerProvider
  8123. * @description
  8124. * The {@link ng.$controller $controller service} is used by Angular to create new
  8125. * controllers.
  8126. *
  8127. * This provider allows controller registration via the
  8128. * {@link ng.$controllerProvider#register register} method.
  8129. */
  8130. function $ControllerProvider() {
  8131. var controllers = {},
  8132. globals = false;
  8133. /**
  8134. * @ngdoc method
  8135. * @name $controllerProvider#register
  8136. * @param {string|Object} name Controller name, or an object map of controllers where the keys are
  8137. * the names and the values are the constructors.
  8138. * @param {Function|Array} constructor Controller constructor fn (optionally decorated with DI
  8139. * annotations in the array notation).
  8140. */
  8141. this.register = function(name, constructor) {
  8142. assertNotHasOwnProperty(name, 'controller');
  8143. if (isObject(name)) {
  8144. extend(controllers, name);
  8145. } else {
  8146. controllers[name] = constructor;
  8147. }
  8148. };
  8149. /**
  8150. * @ngdoc method
  8151. * @name $controllerProvider#allowGlobals
  8152. * @description If called, allows `$controller` to find controller constructors on `window`
  8153. */
  8154. this.allowGlobals = function() {
  8155. globals = true;
  8156. };
  8157. this.$get = ['$injector', '$window', function($injector, $window) {
  8158. /**
  8159. * @ngdoc service
  8160. * @name $controller
  8161. * @requires $injector
  8162. *
  8163. * @param {Function|string} constructor If called with a function then it's considered to be the
  8164. * controller constructor function. Otherwise it's considered to be a string which is used
  8165. * to retrieve the controller constructor using the following steps:
  8166. *
  8167. * * check if a controller with given name is registered via `$controllerProvider`
  8168. * * check if evaluating the string on the current scope returns a constructor
  8169. * * if $controllerProvider#allowGlobals, check `window[constructor]` on the global
  8170. * `window` object (not recommended)
  8171. *
  8172. * The string can use the `controller as property` syntax, where the controller instance is published
  8173. * as the specified property on the `scope`; the `scope` must be injected into `locals` param for this
  8174. * to work correctly.
  8175. *
  8176. * @param {Object} locals Injection locals for Controller.
  8177. * @return {Object} Instance of given controller.
  8178. *
  8179. * @description
  8180. * `$controller` service is responsible for instantiating controllers.
  8181. *
  8182. * It's just a simple call to {@link auto.$injector $injector}, but extracted into
  8183. * a service, so that one can override this service with [BC version](https://gist.github.com/1649788).
  8184. */
  8185. return function(expression, locals, later, ident) {
  8186. // PRIVATE API:
  8187. // param `later` --- indicates that the controller's constructor is invoked at a later time.
  8188. // If true, $controller will allocate the object with the correct
  8189. // prototype chain, but will not invoke the controller until a returned
  8190. // callback is invoked.
  8191. // param `ident` --- An optional label which overrides the label parsed from the controller
  8192. // expression, if any.
  8193. var instance, match, constructor, identifier;
  8194. later = later === true;
  8195. if (ident && isString(ident)) {
  8196. identifier = ident;
  8197. }
  8198. if (isString(expression)) {
  8199. match = expression.match(CNTRL_REG);
  8200. if (!match) {
  8201. throw $controllerMinErr('ctrlfmt',
  8202. "Badly formed controller string '{0}'. " +
  8203. "Must match `__name__ as __id__` or `__name__`.", expression);
  8204. }
  8205. constructor = match[1],
  8206. identifier = identifier || match[3];
  8207. expression = controllers.hasOwnProperty(constructor)
  8208. ? controllers[constructor]
  8209. : getter(locals.$scope, constructor, true) ||
  8210. (globals ? getter($window, constructor, true) : undefined);
  8211. assertArgFn(expression, constructor, true);
  8212. }
  8213. if (later) {
  8214. // Instantiate controller later:
  8215. // This machinery is used to create an instance of the object before calling the
  8216. // controller's constructor itself.
  8217. //
  8218. // This allows properties to be added to the controller before the constructor is
  8219. // invoked. Primarily, this is used for isolate scope bindings in $compile.
  8220. //
  8221. // This feature is not intended for use by applications, and is thus not documented
  8222. // publicly.
  8223. // Object creation: http://jsperf.com/create-constructor/2
  8224. var controllerPrototype = (isArray(expression) ?
  8225. expression[expression.length - 1] : expression).prototype;
  8226. instance = Object.create(controllerPrototype || null);
  8227. if (identifier) {
  8228. addIdentifier(locals, identifier, instance, constructor || expression.name);
  8229. }
  8230. var instantiate;
  8231. return instantiate = extend(function() {
  8232. var result = $injector.invoke(expression, instance, locals, constructor);
  8233. if (result !== instance && (isObject(result) || isFunction(result))) {
  8234. instance = result;
  8235. if (identifier) {
  8236. // If result changed, re-assign controllerAs value to scope.
  8237. addIdentifier(locals, identifier, instance, constructor || expression.name);
  8238. }
  8239. }
  8240. return instance;
  8241. }, {
  8242. instance: instance,
  8243. identifier: identifier
  8244. });
  8245. }
  8246. instance = $injector.instantiate(expression, locals, constructor);
  8247. if (identifier) {
  8248. addIdentifier(locals, identifier, instance, constructor || expression.name);
  8249. }
  8250. return instance;
  8251. };
  8252. function addIdentifier(locals, identifier, instance, name) {
  8253. if (!(locals && isObject(locals.$scope))) {
  8254. throw minErr('$controller')('noscp',
  8255. "Cannot export controller '{0}' as '{1}'! No $scope object provided via `locals`.",
  8256. name, identifier);
  8257. }
  8258. locals.$scope[identifier] = instance;
  8259. }
  8260. }];
  8261. }
  8262. /**
  8263. * @ngdoc service
  8264. * @name $document
  8265. * @requires $window
  8266. *
  8267. * @description
  8268. * A {@link angular.element jQuery or jqLite} wrapper for the browser's `window.document` object.
  8269. *
  8270. * @example
  8271. <example module="documentExample">
  8272. <file name="index.html">
  8273. <div ng-controller="ExampleController">
  8274. <p>$document title: <b ng-bind="title"></b></p>
  8275. <p>window.document title: <b ng-bind="windowTitle"></b></p>
  8276. </div>
  8277. </file>
  8278. <file name="script.js">
  8279. angular.module('documentExample', [])
  8280. .controller('ExampleController', ['$scope', '$document', function($scope, $document) {
  8281. $scope.title = $document[0].title;
  8282. $scope.windowTitle = angular.element(window.document)[0].title;
  8283. }]);
  8284. </file>
  8285. </example>
  8286. */
  8287. function $DocumentProvider() {
  8288. this.$get = ['$window', function(window) {
  8289. return jqLite(window.document);
  8290. }];
  8291. }
  8292. /**
  8293. * @ngdoc service
  8294. * @name $exceptionHandler
  8295. * @requires ng.$log
  8296. *
  8297. * @description
  8298. * Any uncaught exception in angular expressions is delegated to this service.
  8299. * The default implementation simply delegates to `$log.error` which logs it into
  8300. * the browser console.
  8301. *
  8302. * In unit tests, if `angular-mocks.js` is loaded, this service is overridden by
  8303. * {@link ngMock.$exceptionHandler mock $exceptionHandler} which aids in testing.
  8304. *
  8305. * ## Example:
  8306. *
  8307. * ```js
  8308. * angular.module('exceptionOverride', []).factory('$exceptionHandler', function() {
  8309. * return function(exception, cause) {
  8310. * exception.message += ' (caused by "' + cause + '")';
  8311. * throw exception;
  8312. * };
  8313. * });
  8314. * ```
  8315. *
  8316. * This example will override the normal action of `$exceptionHandler`, to make angular
  8317. * exceptions fail hard when they happen, instead of just logging to the console.
  8318. *
  8319. * <hr />
  8320. * Note, that code executed in event-listeners (even those registered using jqLite's `on`/`bind`
  8321. * methods) does not delegate exceptions to the {@link ng.$exceptionHandler $exceptionHandler}
  8322. * (unless executed during a digest).
  8323. *
  8324. * If you wish, you can manually delegate exceptions, e.g.
  8325. * `try { ... } catch(e) { $exceptionHandler(e); }`
  8326. *
  8327. * @param {Error} exception Exception associated with the error.
  8328. * @param {string=} cause optional information about the context in which
  8329. * the error was thrown.
  8330. *
  8331. */
  8332. function $ExceptionHandlerProvider() {
  8333. this.$get = ['$log', function($log) {
  8334. return function(exception, cause) {
  8335. $log.error.apply($log, arguments);
  8336. };
  8337. }];
  8338. }
  8339. var $$ForceReflowProvider = function() {
  8340. this.$get = ['$document', function($document) {
  8341. return function(domNode) {
  8342. //the line below will force the browser to perform a repaint so
  8343. //that all the animated elements within the animation frame will
  8344. //be properly updated and drawn on screen. This is required to
  8345. //ensure that the preparation animation is properly flushed so that
  8346. //the active state picks up from there. DO NOT REMOVE THIS LINE.
  8347. //DO NOT OPTIMIZE THIS LINE. THE MINIFIER WILL REMOVE IT OTHERWISE WHICH
  8348. //WILL RESULT IN AN UNPREDICTABLE BUG THAT IS VERY HARD TO TRACK DOWN AND
  8349. //WILL TAKE YEARS AWAY FROM YOUR LIFE.
  8350. if (domNode) {
  8351. if (!domNode.nodeType && domNode instanceof jqLite) {
  8352. domNode = domNode[0];
  8353. }
  8354. } else {
  8355. domNode = $document[0].body;
  8356. }
  8357. return domNode.offsetWidth + 1;
  8358. };
  8359. }];
  8360. };
  8361. var APPLICATION_JSON = 'application/json';
  8362. var CONTENT_TYPE_APPLICATION_JSON = {'Content-Type': APPLICATION_JSON + ';charset=utf-8'};
  8363. var JSON_START = /^\[|^\{(?!\{)/;
  8364. var JSON_ENDS = {
  8365. '[': /]$/,
  8366. '{': /}$/
  8367. };
  8368. var JSON_PROTECTION_PREFIX = /^\)\]\}',?\n/;
  8369. var $httpMinErr = minErr('$http');
  8370. var $httpMinErrLegacyFn = function(method) {
  8371. return function() {
  8372. throw $httpMinErr('legacy', 'The method `{0}` on the promise returned from `$http` has been disabled.', method);
  8373. };
  8374. };
  8375. function serializeValue(v) {
  8376. if (isObject(v)) {
  8377. return isDate(v) ? v.toISOString() : toJson(v);
  8378. }
  8379. return v;
  8380. }
  8381. function $HttpParamSerializerProvider() {
  8382. /**
  8383. * @ngdoc service
  8384. * @name $httpParamSerializer
  8385. * @description
  8386. *
  8387. * Default {@link $http `$http`} params serializer that converts objects to strings
  8388. * according to the following rules:
  8389. *
  8390. * * `{'foo': 'bar'}` results in `foo=bar`
  8391. * * `{'foo': Date.now()}` results in `foo=2015-04-01T09%3A50%3A49.262Z` (`toISOString()` and encoded representation of a Date object)
  8392. * * `{'foo': ['bar', 'baz']}` results in `foo=bar&foo=baz` (repeated key for each array element)
  8393. * * `{'foo': {'bar':'baz'}}` results in `foo=%7B%22bar%22%3A%22baz%22%7D"` (stringified and encoded representation of an object)
  8394. *
  8395. * Note that serializer will sort the request parameters alphabetically.
  8396. * */
  8397. this.$get = function() {
  8398. return function ngParamSerializer(params) {
  8399. if (!params) return '';
  8400. var parts = [];
  8401. forEachSorted(params, function(value, key) {
  8402. if (value === null || isUndefined(value)) return;
  8403. if (isArray(value)) {
  8404. forEach(value, function(v, k) {
  8405. parts.push(encodeUriQuery(key) + '=' + encodeUriQuery(serializeValue(v)));
  8406. });
  8407. } else {
  8408. parts.push(encodeUriQuery(key) + '=' + encodeUriQuery(serializeValue(value)));
  8409. }
  8410. });
  8411. return parts.join('&');
  8412. };
  8413. };
  8414. }
  8415. function $HttpParamSerializerJQLikeProvider() {
  8416. /**
  8417. * @ngdoc service
  8418. * @name $httpParamSerializerJQLike
  8419. * @description
  8420. *
  8421. * Alternative {@link $http `$http`} params serializer that follows
  8422. * jQuery's [`param()`](http://api.jquery.com/jquery.param/) method logic.
  8423. * The serializer will also sort the params alphabetically.
  8424. *
  8425. * To use it for serializing `$http` request parameters, set it as the `paramSerializer` property:
  8426. *
  8427. * ```js
  8428. * $http({
  8429. * url: myUrl,
  8430. * method: 'GET',
  8431. * params: myParams,
  8432. * paramSerializer: '$httpParamSerializerJQLike'
  8433. * });
  8434. * ```
  8435. *
  8436. * It is also possible to set it as the default `paramSerializer` in the
  8437. * {@link $httpProvider#defaults `$httpProvider`}.
  8438. *
  8439. * Additionally, you can inject the serializer and use it explicitly, for example to serialize
  8440. * form data for submission:
  8441. *
  8442. * ```js
  8443. * .controller(function($http, $httpParamSerializerJQLike) {
  8444. * //...
  8445. *
  8446. * $http({
  8447. * url: myUrl,
  8448. * method: 'POST',
  8449. * data: $httpParamSerializerJQLike(myData),
  8450. * headers: {
  8451. * 'Content-Type': 'application/x-www-form-urlencoded'
  8452. * }
  8453. * });
  8454. *
  8455. * });
  8456. * ```
  8457. *
  8458. * */
  8459. this.$get = function() {
  8460. return function jQueryLikeParamSerializer(params) {
  8461. if (!params) return '';
  8462. var parts = [];
  8463. serialize(params, '', true);
  8464. return parts.join('&');
  8465. function serialize(toSerialize, prefix, topLevel) {
  8466. if (toSerialize === null || isUndefined(toSerialize)) return;
  8467. if (isArray(toSerialize)) {
  8468. forEach(toSerialize, function(value, index) {
  8469. serialize(value, prefix + '[' + (isObject(value) ? index : '') + ']');
  8470. });
  8471. } else if (isObject(toSerialize) && !isDate(toSerialize)) {
  8472. forEachSorted(toSerialize, function(value, key) {
  8473. serialize(value, prefix +
  8474. (topLevel ? '' : '[') +
  8475. key +
  8476. (topLevel ? '' : ']'));
  8477. });
  8478. } else {
  8479. parts.push(encodeUriQuery(prefix) + '=' + encodeUriQuery(serializeValue(toSerialize)));
  8480. }
  8481. }
  8482. };
  8483. };
  8484. }
  8485. function defaultHttpResponseTransform(data, headers) {
  8486. if (isString(data)) {
  8487. // Strip json vulnerability protection prefix and trim whitespace
  8488. var tempData = data.replace(JSON_PROTECTION_PREFIX, '').trim();
  8489. if (tempData) {
  8490. var contentType = headers('Content-Type');
  8491. if ((contentType && (contentType.indexOf(APPLICATION_JSON) === 0)) || isJsonLike(tempData)) {
  8492. data = fromJson(tempData);
  8493. }
  8494. }
  8495. }
  8496. return data;
  8497. }
  8498. function isJsonLike(str) {
  8499. var jsonStart = str.match(JSON_START);
  8500. return jsonStart && JSON_ENDS[jsonStart[0]].test(str);
  8501. }
  8502. /**
  8503. * Parse headers into key value object
  8504. *
  8505. * @param {string} headers Raw headers as a string
  8506. * @returns {Object} Parsed headers as key value object
  8507. */
  8508. function parseHeaders(headers) {
  8509. var parsed = createMap(), i;
  8510. function fillInParsed(key, val) {
  8511. if (key) {
  8512. parsed[key] = parsed[key] ? parsed[key] + ', ' + val : val;
  8513. }
  8514. }
  8515. if (isString(headers)) {
  8516. forEach(headers.split('\n'), function(line) {
  8517. i = line.indexOf(':');
  8518. fillInParsed(lowercase(trim(line.substr(0, i))), trim(line.substr(i + 1)));
  8519. });
  8520. } else if (isObject(headers)) {
  8521. forEach(headers, function(headerVal, headerKey) {
  8522. fillInParsed(lowercase(headerKey), trim(headerVal));
  8523. });
  8524. }
  8525. return parsed;
  8526. }
  8527. /**
  8528. * Returns a function that provides access to parsed headers.
  8529. *
  8530. * Headers are lazy parsed when first requested.
  8531. * @see parseHeaders
  8532. *
  8533. * @param {(string|Object)} headers Headers to provide access to.
  8534. * @returns {function(string=)} Returns a getter function which if called with:
  8535. *
  8536. * - if called with single an argument returns a single header value or null
  8537. * - if called with no arguments returns an object containing all headers.
  8538. */
  8539. function headersGetter(headers) {
  8540. var headersObj;
  8541. return function(name) {
  8542. if (!headersObj) headersObj = parseHeaders(headers);
  8543. if (name) {
  8544. var value = headersObj[lowercase(name)];
  8545. if (value === void 0) {
  8546. value = null;
  8547. }
  8548. return value;
  8549. }
  8550. return headersObj;
  8551. };
  8552. }
  8553. /**
  8554. * Chain all given functions
  8555. *
  8556. * This function is used for both request and response transforming
  8557. *
  8558. * @param {*} data Data to transform.
  8559. * @param {function(string=)} headers HTTP headers getter fn.
  8560. * @param {number} status HTTP status code of the response.
  8561. * @param {(Function|Array.<Function>)} fns Function or an array of functions.
  8562. * @returns {*} Transformed data.
  8563. */
  8564. function transformData(data, headers, status, fns) {
  8565. if (isFunction(fns)) {
  8566. return fns(data, headers, status);
  8567. }
  8568. forEach(fns, function(fn) {
  8569. data = fn(data, headers, status);
  8570. });
  8571. return data;
  8572. }
  8573. function isSuccess(status) {
  8574. return 200 <= status && status < 300;
  8575. }
  8576. /**
  8577. * @ngdoc provider
  8578. * @name $httpProvider
  8579. * @description
  8580. * Use `$httpProvider` to change the default behavior of the {@link ng.$http $http} service.
  8581. * */
  8582. function $HttpProvider() {
  8583. /**
  8584. * @ngdoc property
  8585. * @name $httpProvider#defaults
  8586. * @description
  8587. *
  8588. * Object containing default values for all {@link ng.$http $http} requests.
  8589. *
  8590. * - **`defaults.cache`** - {Object} - an object built with {@link ng.$cacheFactory `$cacheFactory`}
  8591. * that will provide the cache for all requests who set their `cache` property to `true`.
  8592. * If you set the `defaults.cache = false` then only requests that specify their own custom
  8593. * cache object will be cached. See {@link $http#caching $http Caching} for more information.
  8594. *
  8595. * - **`defaults.xsrfCookieName`** - {string} - Name of cookie containing the XSRF token.
  8596. * Defaults value is `'XSRF-TOKEN'`.
  8597. *
  8598. * - **`defaults.xsrfHeaderName`** - {string} - Name of HTTP header to populate with the
  8599. * XSRF token. Defaults value is `'X-XSRF-TOKEN'`.
  8600. *
  8601. * - **`defaults.headers`** - {Object} - Default headers for all $http requests.
  8602. * Refer to {@link ng.$http#setting-http-headers $http} for documentation on
  8603. * setting default headers.
  8604. * - **`defaults.headers.common`**
  8605. * - **`defaults.headers.post`**
  8606. * - **`defaults.headers.put`**
  8607. * - **`defaults.headers.patch`**
  8608. *
  8609. *
  8610. * - **`defaults.paramSerializer`** - `{string|function(Object<string,string>):string}` - A function
  8611. * used to the prepare string representation of request parameters (specified as an object).
  8612. * If specified as string, it is interpreted as a function registered with the {@link auto.$injector $injector}.
  8613. * Defaults to {@link ng.$httpParamSerializer $httpParamSerializer}.
  8614. *
  8615. **/
  8616. var defaults = this.defaults = {
  8617. // transform incoming response data
  8618. transformResponse: [defaultHttpResponseTransform],
  8619. // transform outgoing request data
  8620. transformRequest: [function(d) {
  8621. return isObject(d) && !isFile(d) && !isBlob(d) && !isFormData(d) ? toJson(d) : d;
  8622. }],
  8623. // default headers
  8624. headers: {
  8625. common: {
  8626. 'Accept': 'application/json, text/plain, */*'
  8627. },
  8628. post: shallowCopy(CONTENT_TYPE_APPLICATION_JSON),
  8629. put: shallowCopy(CONTENT_TYPE_APPLICATION_JSON),
  8630. patch: shallowCopy(CONTENT_TYPE_APPLICATION_JSON)
  8631. },
  8632. xsrfCookieName: 'XSRF-TOKEN',
  8633. xsrfHeaderName: 'X-XSRF-TOKEN',
  8634. paramSerializer: '$httpParamSerializer'
  8635. };
  8636. var useApplyAsync = false;
  8637. /**
  8638. * @ngdoc method
  8639. * @name $httpProvider#useApplyAsync
  8640. * @description
  8641. *
  8642. * Configure $http service to combine processing of multiple http responses received at around
  8643. * the same time via {@link ng.$rootScope.Scope#$applyAsync $rootScope.$applyAsync}. This can result in
  8644. * significant performance improvement for bigger applications that make many HTTP requests
  8645. * concurrently (common during application bootstrap).
  8646. *
  8647. * Defaults to false. If no value is specified, returns the current configured value.
  8648. *
  8649. * @param {boolean=} value If true, when requests are loaded, they will schedule a deferred
  8650. * "apply" on the next tick, giving time for subsequent requests in a roughly ~10ms window
  8651. * to load and share the same digest cycle.
  8652. *
  8653. * @returns {boolean|Object} If a value is specified, returns the $httpProvider for chaining.
  8654. * otherwise, returns the current configured value.
  8655. **/
  8656. this.useApplyAsync = function(value) {
  8657. if (isDefined(value)) {
  8658. useApplyAsync = !!value;
  8659. return this;
  8660. }
  8661. return useApplyAsync;
  8662. };
  8663. var useLegacyPromise = true;
  8664. /**
  8665. * @ngdoc method
  8666. * @name $httpProvider#useLegacyPromiseExtensions
  8667. * @description
  8668. *
  8669. * Configure `$http` service to return promises without the shorthand methods `success` and `error`.
  8670. * This should be used to make sure that applications work without these methods.
  8671. *
  8672. * Defaults to false. If no value is specified, returns the current configured value.
  8673. *
  8674. * @param {boolean=} value If true, `$http` will return a normal promise without the `success` and `error` methods.
  8675. *
  8676. * @returns {boolean|Object} If a value is specified, returns the $httpProvider for chaining.
  8677. * otherwise, returns the current configured value.
  8678. **/
  8679. this.useLegacyPromiseExtensions = function(value) {
  8680. if (isDefined(value)) {
  8681. useLegacyPromise = !!value;
  8682. return this;
  8683. }
  8684. return useLegacyPromise;
  8685. };
  8686. /**
  8687. * @ngdoc property
  8688. * @name $httpProvider#interceptors
  8689. * @description
  8690. *
  8691. * Array containing service factories for all synchronous or asynchronous {@link ng.$http $http}
  8692. * pre-processing of request or postprocessing of responses.
  8693. *
  8694. * These service factories are ordered by request, i.e. they are applied in the same order as the
  8695. * array, on request, but reverse order, on response.
  8696. *
  8697. * {@link ng.$http#interceptors Interceptors detailed info}
  8698. **/
  8699. var interceptorFactories = this.interceptors = [];
  8700. this.$get = ['$httpBackend', '$$cookieReader', '$cacheFactory', '$rootScope', '$q', '$injector',
  8701. function($httpBackend, $$cookieReader, $cacheFactory, $rootScope, $q, $injector) {
  8702. var defaultCache = $cacheFactory('$http');
  8703. /**
  8704. * Make sure that default param serializer is exposed as a function
  8705. */
  8706. defaults.paramSerializer = isString(defaults.paramSerializer) ?
  8707. $injector.get(defaults.paramSerializer) : defaults.paramSerializer;
  8708. /**
  8709. * Interceptors stored in reverse order. Inner interceptors before outer interceptors.
  8710. * The reversal is needed so that we can build up the interception chain around the
  8711. * server request.
  8712. */
  8713. var reversedInterceptors = [];
  8714. forEach(interceptorFactories, function(interceptorFactory) {
  8715. reversedInterceptors.unshift(isString(interceptorFactory)
  8716. ? $injector.get(interceptorFactory) : $injector.invoke(interceptorFactory));
  8717. });
  8718. /**
  8719. * @ngdoc service
  8720. * @kind function
  8721. * @name $http
  8722. * @requires ng.$httpBackend
  8723. * @requires $cacheFactory
  8724. * @requires $rootScope
  8725. * @requires $q
  8726. * @requires $injector
  8727. *
  8728. * @description
  8729. * The `$http` service is a core Angular service that facilitates communication with the remote
  8730. * HTTP servers via the browser's [XMLHttpRequest](https://developer.mozilla.org/en/xmlhttprequest)
  8731. * object or via [JSONP](http://en.wikipedia.org/wiki/JSONP).
  8732. *
  8733. * For unit testing applications that use `$http` service, see
  8734. * {@link ngMock.$httpBackend $httpBackend mock}.
  8735. *
  8736. * For a higher level of abstraction, please check out the {@link ngResource.$resource
  8737. * $resource} service.
  8738. *
  8739. * The $http API is based on the {@link ng.$q deferred/promise APIs} exposed by
  8740. * the $q service. While for simple usage patterns this doesn't matter much, for advanced usage
  8741. * it is important to familiarize yourself with these APIs and the guarantees they provide.
  8742. *
  8743. *
  8744. * ## General usage
  8745. * The `$http` service is a function which takes a single argument — a configuration object —
  8746. * that is used to generate an HTTP request and returns a {@link ng.$q promise}.
  8747. *
  8748. * ```js
  8749. * // Simple GET request example :
  8750. * $http.get('/someUrl').
  8751. * then(function(response) {
  8752. * // this callback will be called asynchronously
  8753. * // when the response is available
  8754. * }, function(response) {
  8755. * // called asynchronously if an error occurs
  8756. * // or server returns response with an error status.
  8757. * });
  8758. * ```
  8759. *
  8760. * ```js
  8761. * // Simple POST request example (passing data) :
  8762. * $http.post('/someUrl', {msg:'hello word!'}).
  8763. * then(function(response) {
  8764. * // this callback will be called asynchronously
  8765. * // when the response is available
  8766. * }, function(response) {
  8767. * // called asynchronously if an error occurs
  8768. * // or server returns response with an error status.
  8769. * });
  8770. * ```
  8771. *
  8772. * The response object has these properties:
  8773. *
  8774. * - **data** – `{string|Object}` – The response body transformed with the transform
  8775. * functions.
  8776. * - **status** – `{number}` – HTTP status code of the response.
  8777. * - **headers** – `{function([headerName])}` – Header getter function.
  8778. * - **config** – `{Object}` – The configuration object that was used to generate the request.
  8779. * - **statusText** – `{string}` – HTTP status text of the response.
  8780. *
  8781. * A response status code between 200 and 299 is considered a success status and
  8782. * will result in the success callback being called. Note that if the response is a redirect,
  8783. * XMLHttpRequest will transparently follow it, meaning that the error callback will not be
  8784. * called for such responses.
  8785. *
  8786. * ## Writing Unit Tests that use $http
  8787. * When unit testing (using {@link ngMock ngMock}), it is necessary to call
  8788. * {@link ngMock.$httpBackend#flush $httpBackend.flush()} to flush each pending
  8789. * request using trained responses.
  8790. *
  8791. * ```
  8792. * $httpBackend.expectGET(...);
  8793. * $http.get(...);
  8794. * $httpBackend.flush();
  8795. * ```
  8796. *
  8797. * ## Shortcut methods
  8798. *
  8799. * Shortcut methods are also available. All shortcut methods require passing in the URL, and
  8800. * request data must be passed in for POST/PUT requests.
  8801. *
  8802. * ```js
  8803. * $http.get('/someUrl').then(successCallback);
  8804. * $http.post('/someUrl', data).then(successCallback);
  8805. * ```
  8806. *
  8807. * Complete list of shortcut methods:
  8808. *
  8809. * - {@link ng.$http#get $http.get}
  8810. * - {@link ng.$http#head $http.head}
  8811. * - {@link ng.$http#post $http.post}
  8812. * - {@link ng.$http#put $http.put}
  8813. * - {@link ng.$http#delete $http.delete}
  8814. * - {@link ng.$http#jsonp $http.jsonp}
  8815. * - {@link ng.$http#patch $http.patch}
  8816. *
  8817. *
  8818. * ## Deprecation Notice
  8819. * <div class="alert alert-danger">
  8820. * The `$http` legacy promise methods `success` and `error` have been deprecated.
  8821. * Use the standard `then` method instead.
  8822. * If {@link $httpProvider#useLegacyPromiseExtensions `$httpProvider.useLegacyPromiseExtensions`} is set to
  8823. * `false` then these methods will throw {@link $http:legacy `$http/legacy`} error.
  8824. * </div>
  8825. *
  8826. * ## Setting HTTP Headers
  8827. *
  8828. * The $http service will automatically add certain HTTP headers to all requests. These defaults
  8829. * can be fully configured by accessing the `$httpProvider.defaults.headers` configuration
  8830. * object, which currently contains this default configuration:
  8831. *
  8832. * - `$httpProvider.defaults.headers.common` (headers that are common for all requests):
  8833. * - `Accept: application/json, text/plain, * / *`
  8834. * - `$httpProvider.defaults.headers.post`: (header defaults for POST requests)
  8835. * - `Content-Type: application/json`
  8836. * - `$httpProvider.defaults.headers.put` (header defaults for PUT requests)
  8837. * - `Content-Type: application/json`
  8838. *
  8839. * To add or overwrite these defaults, simply add or remove a property from these configuration
  8840. * objects. To add headers for an HTTP method other than POST or PUT, simply add a new object
  8841. * with the lowercased HTTP method name as the key, e.g.
  8842. * `$httpProvider.defaults.headers.get = { 'My-Header' : 'value' }`.
  8843. *
  8844. * The defaults can also be set at runtime via the `$http.defaults` object in the same
  8845. * fashion. For example:
  8846. *
  8847. * ```
  8848. * module.run(function($http) {
  8849. * $http.defaults.headers.common.Authorization = 'Basic YmVlcDpib29w'
  8850. * });
  8851. * ```
  8852. *
  8853. * In addition, you can supply a `headers` property in the config object passed when
  8854. * calling `$http(config)`, which overrides the defaults without changing them globally.
  8855. *
  8856. * To explicitly remove a header automatically added via $httpProvider.defaults.headers on a per request basis,
  8857. * Use the `headers` property, setting the desired header to `undefined`. For example:
  8858. *
  8859. * ```js
  8860. * var req = {
  8861. * method: 'POST',
  8862. * url: 'http://example.com',
  8863. * headers: {
  8864. * 'Content-Type': undefined
  8865. * },
  8866. * data: { test: 'test' }
  8867. * }
  8868. *
  8869. * $http(req).then(function(){...}, function(){...});
  8870. * ```
  8871. *
  8872. * ## Transforming Requests and Responses
  8873. *
  8874. * Both requests and responses can be transformed using transformation functions: `transformRequest`
  8875. * and `transformResponse`. These properties can be a single function that returns
  8876. * the transformed value (`function(data, headersGetter, status)`) or an array of such transformation functions,
  8877. * which allows you to `push` or `unshift` a new transformation function into the transformation chain.
  8878. *
  8879. * ### Default Transformations
  8880. *
  8881. * The `$httpProvider` provider and `$http` service expose `defaults.transformRequest` and
  8882. * `defaults.transformResponse` properties. If a request does not provide its own transformations
  8883. * then these will be applied.
  8884. *
  8885. * You can augment or replace the default transformations by modifying these properties by adding to or
  8886. * replacing the array.
  8887. *
  8888. * Angular provides the following default transformations:
  8889. *
  8890. * Request transformations (`$httpProvider.defaults.transformRequest` and `$http.defaults.transformRequest`):
  8891. *
  8892. * - If the `data` property of the request configuration object contains an object, serialize it
  8893. * into JSON format.
  8894. *
  8895. * Response transformations (`$httpProvider.defaults.transformResponse` and `$http.defaults.transformResponse`):
  8896. *
  8897. * - If XSRF prefix is detected, strip it (see Security Considerations section below).
  8898. * - If JSON response is detected, deserialize it using a JSON parser.
  8899. *
  8900. *
  8901. * ### Overriding the Default Transformations Per Request
  8902. *
  8903. * If you wish override the request/response transformations only for a single request then provide
  8904. * `transformRequest` and/or `transformResponse` properties on the configuration object passed
  8905. * into `$http`.
  8906. *
  8907. * Note that if you provide these properties on the config object the default transformations will be
  8908. * overwritten. If you wish to augment the default transformations then you must include them in your
  8909. * local transformation array.
  8910. *
  8911. * The following code demonstrates adding a new response transformation to be run after the default response
  8912. * transformations have been run.
  8913. *
  8914. * ```js
  8915. * function appendTransform(defaults, transform) {
  8916. *
  8917. * // We can't guarantee that the default transformation is an array
  8918. * defaults = angular.isArray(defaults) ? defaults : [defaults];
  8919. *
  8920. * // Append the new transformation to the defaults
  8921. * return defaults.concat(transform);
  8922. * }
  8923. *
  8924. * $http({
  8925. * url: '...',
  8926. * method: 'GET',
  8927. * transformResponse: appendTransform($http.defaults.transformResponse, function(value) {
  8928. * return doTransform(value);
  8929. * })
  8930. * });
  8931. * ```
  8932. *
  8933. *
  8934. * ## Caching
  8935. *
  8936. * To enable caching, set the request configuration `cache` property to `true` (to use default
  8937. * cache) or to a custom cache object (built with {@link ng.$cacheFactory `$cacheFactory`}).
  8938. * When the cache is enabled, `$http` stores the response from the server in the specified
  8939. * cache. The next time the same request is made, the response is served from the cache without
  8940. * sending a request to the server.
  8941. *
  8942. * Note that even if the response is served from cache, delivery of the data is asynchronous in
  8943. * the same way that real requests are.
  8944. *
  8945. * If there are multiple GET requests for the same URL that should be cached using the same
  8946. * cache, but the cache is not populated yet, only one request to the server will be made and
  8947. * the remaining requests will be fulfilled using the response from the first request.
  8948. *
  8949. * You can change the default cache to a new object (built with
  8950. * {@link ng.$cacheFactory `$cacheFactory`}) by updating the
  8951. * {@link ng.$http#defaults `$http.defaults.cache`} property. All requests who set
  8952. * their `cache` property to `true` will now use this cache object.
  8953. *
  8954. * If you set the default cache to `false` then only requests that specify their own custom
  8955. * cache object will be cached.
  8956. *
  8957. * ## Interceptors
  8958. *
  8959. * Before you start creating interceptors, be sure to understand the
  8960. * {@link ng.$q $q and deferred/promise APIs}.
  8961. *
  8962. * For purposes of global error handling, authentication, or any kind of synchronous or
  8963. * asynchronous pre-processing of request or postprocessing of responses, it is desirable to be
  8964. * able to intercept requests before they are handed to the server and
  8965. * responses before they are handed over to the application code that
  8966. * initiated these requests. The interceptors leverage the {@link ng.$q
  8967. * promise APIs} to fulfill this need for both synchronous and asynchronous pre-processing.
  8968. *
  8969. * The interceptors are service factories that are registered with the `$httpProvider` by
  8970. * adding them to the `$httpProvider.interceptors` array. The factory is called and
  8971. * injected with dependencies (if specified) and returns the interceptor.
  8972. *
  8973. * There are two kinds of interceptors (and two kinds of rejection interceptors):
  8974. *
  8975. * * `request`: interceptors get called with a http `config` object. The function is free to
  8976. * modify the `config` object or create a new one. The function needs to return the `config`
  8977. * object directly, or a promise containing the `config` or a new `config` object.
  8978. * * `requestError`: interceptor gets called when a previous interceptor threw an error or
  8979. * resolved with a rejection.
  8980. * * `response`: interceptors get called with http `response` object. The function is free to
  8981. * modify the `response` object or create a new one. The function needs to return the `response`
  8982. * object directly, or as a promise containing the `response` or a new `response` object.
  8983. * * `responseError`: interceptor gets called when a previous interceptor threw an error or
  8984. * resolved with a rejection.
  8985. *
  8986. *
  8987. * ```js
  8988. * // register the interceptor as a service
  8989. * $provide.factory('myHttpInterceptor', function($q, dependency1, dependency2) {
  8990. * return {
  8991. * // optional method
  8992. * 'request': function(config) {
  8993. * // do something on success
  8994. * return config;
  8995. * },
  8996. *
  8997. * // optional method
  8998. * 'requestError': function(rejection) {
  8999. * // do something on error
  9000. * if (canRecover(rejection)) {
  9001. * return responseOrNewPromise
  9002. * }
  9003. * return $q.reject(rejection);
  9004. * },
  9005. *
  9006. *
  9007. *
  9008. * // optional method
  9009. * 'response': function(response) {
  9010. * // do something on success
  9011. * return response;
  9012. * },
  9013. *
  9014. * // optional method
  9015. * 'responseError': function(rejection) {
  9016. * // do something on error
  9017. * if (canRecover(rejection)) {
  9018. * return responseOrNewPromise
  9019. * }
  9020. * return $q.reject(rejection);
  9021. * }
  9022. * };
  9023. * });
  9024. *
  9025. * $httpProvider.interceptors.push('myHttpInterceptor');
  9026. *
  9027. *
  9028. * // alternatively, register the interceptor via an anonymous factory
  9029. * $httpProvider.interceptors.push(function($q, dependency1, dependency2) {
  9030. * return {
  9031. * 'request': function(config) {
  9032. * // same as above
  9033. * },
  9034. *
  9035. * 'response': function(response) {
  9036. * // same as above
  9037. * }
  9038. * };
  9039. * });
  9040. * ```
  9041. *
  9042. * ## Security Considerations
  9043. *
  9044. * When designing web applications, consider security threats from:
  9045. *
  9046. * - [JSON vulnerability](http://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-json-vulnerability.aspx)
  9047. * - [XSRF](http://en.wikipedia.org/wiki/Cross-site_request_forgery)
  9048. *
  9049. * Both server and the client must cooperate in order to eliminate these threats. Angular comes
  9050. * pre-configured with strategies that address these issues, but for this to work backend server
  9051. * cooperation is required.
  9052. *
  9053. * ### JSON Vulnerability Protection
  9054. *
  9055. * A [JSON vulnerability](http://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-json-vulnerability.aspx)
  9056. * allows third party website to turn your JSON resource URL into
  9057. * [JSONP](http://en.wikipedia.org/wiki/JSONP) request under some conditions. To
  9058. * counter this your server can prefix all JSON requests with following string `")]}',\n"`.
  9059. * Angular will automatically strip the prefix before processing it as JSON.
  9060. *
  9061. * For example if your server needs to return:
  9062. * ```js
  9063. * ['one','two']
  9064. * ```
  9065. *
  9066. * which is vulnerable to attack, your server can return:
  9067. * ```js
  9068. * )]}',
  9069. * ['one','two']
  9070. * ```
  9071. *
  9072. * Angular will strip the prefix, before processing the JSON.
  9073. *
  9074. *
  9075. * ### Cross Site Request Forgery (XSRF) Protection
  9076. *
  9077. * [XSRF](http://en.wikipedia.org/wiki/Cross-site_request_forgery) is a technique by which
  9078. * an unauthorized site can gain your user's private data. Angular provides a mechanism
  9079. * to counter XSRF. When performing XHR requests, the $http service reads a token from a cookie
  9080. * (by default, `XSRF-TOKEN`) and sets it as an HTTP header (`X-XSRF-TOKEN`). Since only
  9081. * JavaScript that runs on your domain could read the cookie, your server can be assured that
  9082. * the XHR came from JavaScript running on your domain. The header will not be set for
  9083. * cross-domain requests.
  9084. *
  9085. * To take advantage of this, your server needs to set a token in a JavaScript readable session
  9086. * cookie called `XSRF-TOKEN` on the first HTTP GET request. On subsequent XHR requests the
  9087. * server can verify that the cookie matches `X-XSRF-TOKEN` HTTP header, and therefore be sure
  9088. * that only JavaScript running on your domain could have sent the request. The token must be
  9089. * unique for each user and must be verifiable by the server (to prevent the JavaScript from
  9090. * making up its own tokens). We recommend that the token is a digest of your site's
  9091. * authentication cookie with a [salt](https://en.wikipedia.org/wiki/Salt_(cryptography&#41;)
  9092. * for added security.
  9093. *
  9094. * The name of the headers can be specified using the xsrfHeaderName and xsrfCookieName
  9095. * properties of either $httpProvider.defaults at config-time, $http.defaults at run-time,
  9096. * or the per-request config object.
  9097. *
  9098. * In order to prevent collisions in environments where multiple Angular apps share the
  9099. * same domain or subdomain, we recommend that each application uses unique cookie name.
  9100. *
  9101. * @param {object} config Object describing the request to be made and how it should be
  9102. * processed. The object has following properties:
  9103. *
  9104. * - **method** – `{string}` – HTTP method (e.g. 'GET', 'POST', etc)
  9105. * - **url** – `{string}` – Absolute or relative URL of the resource that is being requested.
  9106. * - **params** – `{Object.<string|Object>}` – Map of strings or objects which will be serialized
  9107. * with the `paramSerializer` and appended as GET parameters.
  9108. * - **data** – `{string|Object}` – Data to be sent as the request message data.
  9109. * - **headers** – `{Object}` – Map of strings or functions which return strings representing
  9110. * HTTP headers to send to the server. If the return value of a function is null, the
  9111. * header will not be sent. Functions accept a config object as an argument.
  9112. * - **xsrfHeaderName** – `{string}` – Name of HTTP header to populate with the XSRF token.
  9113. * - **xsrfCookieName** – `{string}` – Name of cookie containing the XSRF token.
  9114. * - **transformRequest** –
  9115. * `{function(data, headersGetter)|Array.<function(data, headersGetter)>}` –
  9116. * transform function or an array of such functions. The transform function takes the http
  9117. * request body and headers and returns its transformed (typically serialized) version.
  9118. * See {@link ng.$http#overriding-the-default-transformations-per-request
  9119. * Overriding the Default Transformations}
  9120. * - **transformResponse** –
  9121. * `{function(data, headersGetter, status)|Array.<function(data, headersGetter, status)>}` –
  9122. * transform function or an array of such functions. The transform function takes the http
  9123. * response body, headers and status and returns its transformed (typically deserialized) version.
  9124. * See {@link ng.$http#overriding-the-default-transformations-per-request
  9125. * Overriding the Default TransformationjqLiks}
  9126. * - **paramSerializer** - `{string|function(Object<string,string>):string}` - A function used to
  9127. * prepare the string representation of request parameters (specified as an object).
  9128. * If specified as string, it is interpreted as function registered with the
  9129. * {@link $injector $injector}, which means you can create your own serializer
  9130. * by registering it as a {@link auto.$provide#service service}.
  9131. * The default serializer is the {@link $httpParamSerializer $httpParamSerializer};
  9132. * alternatively, you can use the {@link $httpParamSerializerJQLike $httpParamSerializerJQLike}
  9133. * - **cache** – `{boolean|Cache}` – If true, a default $http cache will be used to cache the
  9134. * GET request, otherwise if a cache instance built with
  9135. * {@link ng.$cacheFactory $cacheFactory}, this cache will be used for
  9136. * caching.
  9137. * - **timeout** – `{number|Promise}` – timeout in milliseconds, or {@link ng.$q promise}
  9138. * that should abort the request when resolved.
  9139. * - **withCredentials** - `{boolean}` - whether to set the `withCredentials` flag on the
  9140. * XHR object. See [requests with credentials](https://developer.mozilla.org/docs/Web/HTTP/Access_control_CORS#Requests_with_credentials)
  9141. * for more information.
  9142. * - **responseType** - `{string}` - see
  9143. * [XMLHttpRequest.responseType](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest#xmlhttprequest-responsetype).
  9144. *
  9145. * @returns {HttpPromise} Returns a {@link ng.$q `Promise}` that will be resolved to a response object
  9146. * when the request succeeds or fails.
  9147. *
  9148. *
  9149. * @property {Array.<Object>} pendingRequests Array of config objects for currently pending
  9150. * requests. This is primarily meant to be used for debugging purposes.
  9151. *
  9152. *
  9153. * @example
  9154. <example module="httpExample">
  9155. <file name="index.html">
  9156. <div ng-controller="FetchController">
  9157. <select ng-model="method" aria-label="Request method">
  9158. <option>GET</option>
  9159. <option>JSONP</option>
  9160. </select>
  9161. <input type="text" ng-model="url" size="80" aria-label="URL" />
  9162. <button id="fetchbtn" ng-click="fetch()">fetch</button><br>
  9163. <button id="samplegetbtn" ng-click="updateModel('GET', 'http-hello.html')">Sample GET</button>
  9164. <button id="samplejsonpbtn"
  9165. ng-click="updateModel('JSONP',
  9166. 'https://angularjs.org/greet.php?callback=JSON_CALLBACK&name=Super%20Hero')">
  9167. Sample JSONP
  9168. </button>
  9169. <button id="invalidjsonpbtn"
  9170. ng-click="updateModel('JSONP', 'https://angularjs.org/doesntexist&callback=JSON_CALLBACK')">
  9171. Invalid JSONP
  9172. </button>
  9173. <pre>http status code: {{status}}</pre>
  9174. <pre>http response data: {{data}}</pre>
  9175. </div>
  9176. </file>
  9177. <file name="script.js">
  9178. angular.module('httpExample', [])
  9179. .controller('FetchController', ['$scope', '$http', '$templateCache',
  9180. function($scope, $http, $templateCache) {
  9181. $scope.method = 'GET';
  9182. $scope.url = 'http-hello.html';
  9183. $scope.fetch = function() {
  9184. $scope.code = null;
  9185. $scope.response = null;
  9186. $http({method: $scope.method, url: $scope.url, cache: $templateCache}).
  9187. then(function(response) {
  9188. $scope.status = response.status;
  9189. $scope.data = response.data;
  9190. }, function(response) {
  9191. $scope.data = response.data || "Request failed";
  9192. $scope.status = response.status;
  9193. });
  9194. };
  9195. $scope.updateModel = function(method, url) {
  9196. $scope.method = method;
  9197. $scope.url = url;
  9198. };
  9199. }]);
  9200. </file>
  9201. <file name="http-hello.html">
  9202. Hello, $http!
  9203. </file>
  9204. <file name="protractor.js" type="protractor">
  9205. var status = element(by.binding('status'));
  9206. var data = element(by.binding('data'));
  9207. var fetchBtn = element(by.id('fetchbtn'));
  9208. var sampleGetBtn = element(by.id('samplegetbtn'));
  9209. var sampleJsonpBtn = element(by.id('samplejsonpbtn'));
  9210. var invalidJsonpBtn = element(by.id('invalidjsonpbtn'));
  9211. it('should make an xhr GET request', function() {
  9212. sampleGetBtn.click();
  9213. fetchBtn.click();
  9214. expect(status.getText()).toMatch('200');
  9215. expect(data.getText()).toMatch(/Hello, \$http!/);
  9216. });
  9217. // Commented out due to flakes. See https://github.com/angular/angular.js/issues/9185
  9218. // it('should make a JSONP request to angularjs.org', function() {
  9219. // sampleJsonpBtn.click();
  9220. // fetchBtn.click();
  9221. // expect(status.getText()).toMatch('200');
  9222. // expect(data.getText()).toMatch(/Super Hero!/);
  9223. // });
  9224. it('should make JSONP request to invalid URL and invoke the error handler',
  9225. function() {
  9226. invalidJsonpBtn.click();
  9227. fetchBtn.click();
  9228. expect(status.getText()).toMatch('0');
  9229. expect(data.getText()).toMatch('Request failed');
  9230. });
  9231. </file>
  9232. </example>
  9233. */
  9234. function $http(requestConfig) {
  9235. if (!angular.isObject(requestConfig)) {
  9236. throw minErr('$http')('badreq', 'Http request configuration must be an object. Received: {0}', requestConfig);
  9237. }
  9238. var config = extend({
  9239. method: 'get',
  9240. transformRequest: defaults.transformRequest,
  9241. transformResponse: defaults.transformResponse,
  9242. paramSerializer: defaults.paramSerializer
  9243. }, requestConfig);
  9244. config.headers = mergeHeaders(requestConfig);
  9245. config.method = uppercase(config.method);
  9246. config.paramSerializer = isString(config.paramSerializer) ?
  9247. $injector.get(config.paramSerializer) : config.paramSerializer;
  9248. var serverRequest = function(config) {
  9249. var headers = config.headers;
  9250. var reqData = transformData(config.data, headersGetter(headers), undefined, config.transformRequest);
  9251. // strip content-type if data is undefined
  9252. if (isUndefined(reqData)) {
  9253. forEach(headers, function(value, header) {
  9254. if (lowercase(header) === 'content-type') {
  9255. delete headers[header];
  9256. }
  9257. });
  9258. }
  9259. if (isUndefined(config.withCredentials) && !isUndefined(defaults.withCredentials)) {
  9260. config.withCredentials = defaults.withCredentials;
  9261. }
  9262. // send request
  9263. return sendReq(config, reqData).then(transformResponse, transformResponse);
  9264. };
  9265. var chain = [serverRequest, undefined];
  9266. var promise = $q.when(config);
  9267. // apply interceptors
  9268. forEach(reversedInterceptors, function(interceptor) {
  9269. if (interceptor.request || interceptor.requestError) {
  9270. chain.unshift(interceptor.request, interceptor.requestError);
  9271. }
  9272. if (interceptor.response || interceptor.responseError) {
  9273. chain.push(interceptor.response, interceptor.responseError);
  9274. }
  9275. });
  9276. while (chain.length) {
  9277. var thenFn = chain.shift();
  9278. var rejectFn = chain.shift();
  9279. promise = promise.then(thenFn, rejectFn);
  9280. }
  9281. if (useLegacyPromise) {
  9282. promise.success = function(fn) {
  9283. assertArgFn(fn, 'fn');
  9284. promise.then(function(response) {
  9285. fn(response.data, response.status, response.headers, config);
  9286. });
  9287. return promise;
  9288. };
  9289. promise.error = function(fn) {
  9290. assertArgFn(fn, 'fn');
  9291. promise.then(null, function(response) {
  9292. fn(response.data, response.status, response.headers, config);
  9293. });
  9294. return promise;
  9295. };
  9296. } else {
  9297. promise.success = $httpMinErrLegacyFn('success');
  9298. promise.error = $httpMinErrLegacyFn('error');
  9299. }
  9300. return promise;
  9301. function transformResponse(response) {
  9302. // make a copy since the response must be cacheable
  9303. var resp = extend({}, response);
  9304. if (!response.data) {
  9305. resp.data = response.data;
  9306. } else {
  9307. resp.data = transformData(response.data, response.headers, response.status, config.transformResponse);
  9308. }
  9309. return (isSuccess(response.status))
  9310. ? resp
  9311. : $q.reject(resp);
  9312. }
  9313. function executeHeaderFns(headers, config) {
  9314. var headerContent, processedHeaders = {};
  9315. forEach(headers, function(headerFn, header) {
  9316. if (isFunction(headerFn)) {
  9317. headerContent = headerFn(config);
  9318. if (headerContent != null) {
  9319. processedHeaders[header] = headerContent;
  9320. }
  9321. } else {
  9322. processedHeaders[header] = headerFn;
  9323. }
  9324. });
  9325. return processedHeaders;
  9326. }
  9327. function mergeHeaders(config) {
  9328. var defHeaders = defaults.headers,
  9329. reqHeaders = extend({}, config.headers),
  9330. defHeaderName, lowercaseDefHeaderName, reqHeaderName;
  9331. defHeaders = extend({}, defHeaders.common, defHeaders[lowercase(config.method)]);
  9332. // using for-in instead of forEach to avoid unecessary iteration after header has been found
  9333. defaultHeadersIteration:
  9334. for (defHeaderName in defHeaders) {
  9335. lowercaseDefHeaderName = lowercase(defHeaderName);
  9336. for (reqHeaderName in reqHeaders) {
  9337. if (lowercase(reqHeaderName) === lowercaseDefHeaderName) {
  9338. continue defaultHeadersIteration;
  9339. }
  9340. }
  9341. reqHeaders[defHeaderName] = defHeaders[defHeaderName];
  9342. }
  9343. // execute if header value is a function for merged headers
  9344. return executeHeaderFns(reqHeaders, shallowCopy(config));
  9345. }
  9346. }
  9347. $http.pendingRequests = [];
  9348. /**
  9349. * @ngdoc method
  9350. * @name $http#get
  9351. *
  9352. * @description
  9353. * Shortcut method to perform `GET` request.
  9354. *
  9355. * @param {string} url Relative or absolute URL specifying the destination of the request
  9356. * @param {Object=} config Optional configuration object
  9357. * @returns {HttpPromise} Future object
  9358. */
  9359. /**
  9360. * @ngdoc method
  9361. * @name $http#delete
  9362. *
  9363. * @description
  9364. * Shortcut method to perform `DELETE` request.
  9365. *
  9366. * @param {string} url Relative or absolute URL specifying the destination of the request
  9367. * @param {Object=} config Optional configuration object
  9368. * @returns {HttpPromise} Future object
  9369. */
  9370. /**
  9371. * @ngdoc method
  9372. * @name $http#head
  9373. *
  9374. * @description
  9375. * Shortcut method to perform `HEAD` request.
  9376. *
  9377. * @param {string} url Relative or absolute URL specifying the destination of the request
  9378. * @param {Object=} config Optional configuration object
  9379. * @returns {HttpPromise} Future object
  9380. */
  9381. /**
  9382. * @ngdoc method
  9383. * @name $http#jsonp
  9384. *
  9385. * @description
  9386. * Shortcut method to perform `JSONP` request.
  9387. *
  9388. * @param {string} url Relative or absolute URL specifying the destination of the request.
  9389. * The name of the callback should be the string `JSON_CALLBACK`.
  9390. * @param {Object=} config Optional configuration object
  9391. * @returns {HttpPromise} Future object
  9392. */
  9393. createShortMethods('get', 'delete', 'head', 'jsonp');
  9394. /**
  9395. * @ngdoc method
  9396. * @name $http#post
  9397. *
  9398. * @description
  9399. * Shortcut method to perform `POST` request.
  9400. *
  9401. * @param {string} url Relative or absolute URL specifying the destination of the request
  9402. * @param {*} data Request content
  9403. * @param {Object=} config Optional configuration object
  9404. * @returns {HttpPromise} Future object
  9405. */
  9406. /**
  9407. * @ngdoc method
  9408. * @name $http#put
  9409. *
  9410. * @description
  9411. * Shortcut method to perform `PUT` request.
  9412. *
  9413. * @param {string} url Relative or absolute URL specifying the destination of the request
  9414. * @param {*} data Request content
  9415. * @param {Object=} config Optional configuration object
  9416. * @returns {HttpPromise} Future object
  9417. */
  9418. /**
  9419. * @ngdoc method
  9420. * @name $http#patch
  9421. *
  9422. * @description
  9423. * Shortcut method to perform `PATCH` request.
  9424. *
  9425. * @param {string} url Relative or absolute URL specifying the destination of the request
  9426. * @param {*} data Request content
  9427. * @param {Object=} config Optional configuration object
  9428. * @returns {HttpPromise} Future object
  9429. */
  9430. createShortMethodsWithData('post', 'put', 'patch');
  9431. /**
  9432. * @ngdoc property
  9433. * @name $http#defaults
  9434. *
  9435. * @description
  9436. * Runtime equivalent of the `$httpProvider.defaults` property. Allows configuration of
  9437. * default headers, withCredentials as well as request and response transformations.
  9438. *
  9439. * See "Setting HTTP Headers" and "Transforming Requests and Responses" sections above.
  9440. */
  9441. $http.defaults = defaults;
  9442. return $http;
  9443. function createShortMethods(names) {
  9444. forEach(arguments, function(name) {
  9445. $http[name] = function(url, config) {
  9446. return $http(extend({}, config || {}, {
  9447. method: name,
  9448. url: url
  9449. }));
  9450. };
  9451. });
  9452. }
  9453. function createShortMethodsWithData(name) {
  9454. forEach(arguments, function(name) {
  9455. $http[name] = function(url, data, config) {
  9456. return $http(extend({}, config || {}, {
  9457. method: name,
  9458. url: url,
  9459. data: data
  9460. }));
  9461. };
  9462. });
  9463. }
  9464. /**
  9465. * Makes the request.
  9466. *
  9467. * !!! ACCESSES CLOSURE VARS:
  9468. * $httpBackend, defaults, $log, $rootScope, defaultCache, $http.pendingRequests
  9469. */
  9470. function sendReq(config, reqData) {
  9471. var deferred = $q.defer(),
  9472. promise = deferred.promise,
  9473. cache,
  9474. cachedResp,
  9475. reqHeaders = config.headers,
  9476. url = buildUrl(config.url, config.paramSerializer(config.params));
  9477. $http.pendingRequests.push(config);
  9478. promise.then(removePendingReq, removePendingReq);
  9479. if ((config.cache || defaults.cache) && config.cache !== false &&
  9480. (config.method === 'GET' || config.method === 'JSONP')) {
  9481. cache = isObject(config.cache) ? config.cache
  9482. : isObject(defaults.cache) ? defaults.cache
  9483. : defaultCache;
  9484. }
  9485. if (cache) {
  9486. cachedResp = cache.get(url);
  9487. if (isDefined(cachedResp)) {
  9488. if (isPromiseLike(cachedResp)) {
  9489. // cached request has already been sent, but there is no response yet
  9490. cachedResp.then(resolvePromiseWithResult, resolvePromiseWithResult);
  9491. } else {
  9492. // serving from cache
  9493. if (isArray(cachedResp)) {
  9494. resolvePromise(cachedResp[1], cachedResp[0], shallowCopy(cachedResp[2]), cachedResp[3]);
  9495. } else {
  9496. resolvePromise(cachedResp, 200, {}, 'OK');
  9497. }
  9498. }
  9499. } else {
  9500. // put the promise for the non-transformed response into cache as a placeholder
  9501. cache.put(url, promise);
  9502. }
  9503. }
  9504. // if we won't have the response in cache, set the xsrf headers and
  9505. // send the request to the backend
  9506. if (isUndefined(cachedResp)) {
  9507. var xsrfValue = urlIsSameOrigin(config.url)
  9508. ? $$cookieReader()[config.xsrfCookieName || defaults.xsrfCookieName]
  9509. : undefined;
  9510. if (xsrfValue) {
  9511. reqHeaders[(config.xsrfHeaderName || defaults.xsrfHeaderName)] = xsrfValue;
  9512. }
  9513. $httpBackend(config.method, url, reqData, done, reqHeaders, config.timeout,
  9514. config.withCredentials, config.responseType);
  9515. }
  9516. return promise;
  9517. /**
  9518. * Callback registered to $httpBackend():
  9519. * - caches the response if desired
  9520. * - resolves the raw $http promise
  9521. * - calls $apply
  9522. */
  9523. function done(status, response, headersString, statusText) {
  9524. if (cache) {
  9525. if (isSuccess(status)) {
  9526. cache.put(url, [status, response, parseHeaders(headersString), statusText]);
  9527. } else {
  9528. // remove promise from the cache
  9529. cache.remove(url);
  9530. }
  9531. }
  9532. function resolveHttpPromise() {
  9533. resolvePromise(response, status, headersString, statusText);
  9534. }
  9535. if (useApplyAsync) {
  9536. $rootScope.$applyAsync(resolveHttpPromise);
  9537. } else {
  9538. resolveHttpPromise();
  9539. if (!$rootScope.$$phase) $rootScope.$apply();
  9540. }
  9541. }
  9542. /**
  9543. * Resolves the raw $http promise.
  9544. */
  9545. function resolvePromise(response, status, headers, statusText) {
  9546. //status: HTTP response status code, 0, -1 (aborted by timeout / promise)
  9547. status = status >= -1 ? status : 0;
  9548. (isSuccess(status) ? deferred.resolve : deferred.reject)({
  9549. data: response,
  9550. status: status,
  9551. headers: headersGetter(headers),
  9552. config: config,
  9553. statusText: statusText
  9554. });
  9555. }
  9556. function resolvePromiseWithResult(result) {
  9557. resolvePromise(result.data, result.status, shallowCopy(result.headers()), result.statusText);
  9558. }
  9559. function removePendingReq() {
  9560. var idx = $http.pendingRequests.indexOf(config);
  9561. if (idx !== -1) $http.pendingRequests.splice(idx, 1);
  9562. }
  9563. }
  9564. function buildUrl(url, serializedParams) {
  9565. if (serializedParams.length > 0) {
  9566. url += ((url.indexOf('?') == -1) ? '?' : '&') + serializedParams;
  9567. }
  9568. return url;
  9569. }
  9570. }];
  9571. }
  9572. function createXhr() {
  9573. return new window.XMLHttpRequest();
  9574. }
  9575. /**
  9576. * @ngdoc service
  9577. * @name $httpBackend
  9578. * @requires $window
  9579. * @requires $document
  9580. *
  9581. * @description
  9582. * HTTP backend used by the {@link ng.$http service} that delegates to
  9583. * XMLHttpRequest object or JSONP and deals with browser incompatibilities.
  9584. *
  9585. * You should never need to use this service directly, instead use the higher-level abstractions:
  9586. * {@link ng.$http $http} or {@link ngResource.$resource $resource}.
  9587. *
  9588. * During testing this implementation is swapped with {@link ngMock.$httpBackend mock
  9589. * $httpBackend} which can be trained with responses.
  9590. */
  9591. function $HttpBackendProvider() {
  9592. this.$get = ['$browser', '$window', '$document', function($browser, $window, $document) {
  9593. return createHttpBackend($browser, createXhr, $browser.defer, $window.angular.callbacks, $document[0]);
  9594. }];
  9595. }
  9596. function createHttpBackend($browser, createXhr, $browserDefer, callbacks, rawDocument) {
  9597. // TODO(vojta): fix the signature
  9598. return function(method, url, post, callback, headers, timeout, withCredentials, responseType) {
  9599. $browser.$$incOutstandingRequestCount();
  9600. url = url || $browser.url();
  9601. if (lowercase(method) == 'jsonp') {
  9602. var callbackId = '_' + (callbacks.counter++).toString(36);
  9603. callbacks[callbackId] = function(data) {
  9604. callbacks[callbackId].data = data;
  9605. callbacks[callbackId].called = true;
  9606. };
  9607. var jsonpDone = jsonpReq(url.replace('JSON_CALLBACK', 'angular.callbacks.' + callbackId),
  9608. callbackId, function(status, text) {
  9609. completeRequest(callback, status, callbacks[callbackId].data, "", text);
  9610. callbacks[callbackId] = noop;
  9611. });
  9612. } else {
  9613. var xhr = createXhr();
  9614. xhr.open(method, url, true);
  9615. forEach(headers, function(value, key) {
  9616. if (isDefined(value)) {
  9617. xhr.setRequestHeader(key, value);
  9618. }
  9619. });
  9620. xhr.onload = function requestLoaded() {
  9621. var statusText = xhr.statusText || '';
  9622. // responseText is the old-school way of retrieving response (supported by IE9)
  9623. // response/responseType properties were introduced in XHR Level2 spec (supported by IE10)
  9624. var response = ('response' in xhr) ? xhr.response : xhr.responseText;
  9625. // normalize IE9 bug (http://bugs.jquery.com/ticket/1450)
  9626. var status = xhr.status === 1223 ? 204 : xhr.status;
  9627. // fix status code when it is 0 (0 status is undocumented).
  9628. // Occurs when accessing file resources or on Android 4.1 stock browser
  9629. // while retrieving files from application cache.
  9630. if (status === 0) {
  9631. status = response ? 200 : urlResolve(url).protocol == 'file' ? 404 : 0;
  9632. }
  9633. completeRequest(callback,
  9634. status,
  9635. response,
  9636. xhr.getAllResponseHeaders(),
  9637. statusText);
  9638. };
  9639. var requestError = function() {
  9640. // The response is always empty
  9641. // See https://xhr.spec.whatwg.org/#request-error-steps and https://fetch.spec.whatwg.org/#concept-network-error
  9642. completeRequest(callback, -1, null, null, '');
  9643. };
  9644. xhr.onerror = requestError;
  9645. xhr.onabort = requestError;
  9646. if (withCredentials) {
  9647. xhr.withCredentials = true;
  9648. }
  9649. if (responseType) {
  9650. try {
  9651. xhr.responseType = responseType;
  9652. } catch (e) {
  9653. // WebKit added support for the json responseType value on 09/03/2013
  9654. // https://bugs.webkit.org/show_bug.cgi?id=73648. Versions of Safari prior to 7 are
  9655. // known to throw when setting the value "json" as the response type. Other older
  9656. // browsers implementing the responseType
  9657. //
  9658. // The json response type can be ignored if not supported, because JSON payloads are
  9659. // parsed on the client-side regardless.
  9660. if (responseType !== 'json') {
  9661. throw e;
  9662. }
  9663. }
  9664. }
  9665. xhr.send(isUndefined(post) ? null : post);
  9666. }
  9667. if (timeout > 0) {
  9668. var timeoutId = $browserDefer(timeoutRequest, timeout);
  9669. } else if (isPromiseLike(timeout)) {
  9670. timeout.then(timeoutRequest);
  9671. }
  9672. function timeoutRequest() {
  9673. jsonpDone && jsonpDone();
  9674. xhr && xhr.abort();
  9675. }
  9676. function completeRequest(callback, status, response, headersString, statusText) {
  9677. // cancel timeout and subsequent timeout promise resolution
  9678. if (isDefined(timeoutId)) {
  9679. $browserDefer.cancel(timeoutId);
  9680. }
  9681. jsonpDone = xhr = null;
  9682. callback(status, response, headersString, statusText);
  9683. $browser.$$completeOutstandingRequest(noop);
  9684. }
  9685. };
  9686. function jsonpReq(url, callbackId, done) {
  9687. // we can't use jQuery/jqLite here because jQuery does crazy stuff with script elements, e.g.:
  9688. // - fetches local scripts via XHR and evals them
  9689. // - adds and immediately removes script elements from the document
  9690. var script = rawDocument.createElement('script'), callback = null;
  9691. script.type = "text/javascript";
  9692. script.src = url;
  9693. script.async = true;
  9694. callback = function(event) {
  9695. removeEventListenerFn(script, "load", callback);
  9696. removeEventListenerFn(script, "error", callback);
  9697. rawDocument.body.removeChild(script);
  9698. script = null;
  9699. var status = -1;
  9700. var text = "unknown";
  9701. if (event) {
  9702. if (event.type === "load" && !callbacks[callbackId].called) {
  9703. event = { type: "error" };
  9704. }
  9705. text = event.type;
  9706. status = event.type === "error" ? 404 : 200;
  9707. }
  9708. if (done) {
  9709. done(status, text);
  9710. }
  9711. };
  9712. addEventListenerFn(script, "load", callback);
  9713. addEventListenerFn(script, "error", callback);
  9714. rawDocument.body.appendChild(script);
  9715. return callback;
  9716. }
  9717. }
  9718. var $interpolateMinErr = angular.$interpolateMinErr = minErr('$interpolate');
  9719. $interpolateMinErr.throwNoconcat = function(text) {
  9720. throw $interpolateMinErr('noconcat',
  9721. "Error while interpolating: {0}\nStrict Contextual Escaping disallows " +
  9722. "interpolations that concatenate multiple expressions when a trusted value is " +
  9723. "required. See http://docs.angularjs.org/api/ng.$sce", text);
  9724. };
  9725. $interpolateMinErr.interr = function(text, err) {
  9726. return $interpolateMinErr('interr', "Can't interpolate: {0}\n{1}", text, err.toString());
  9727. };
  9728. /**
  9729. * @ngdoc provider
  9730. * @name $interpolateProvider
  9731. *
  9732. * @description
  9733. *
  9734. * Used for configuring the interpolation markup. Defaults to `{{` and `}}`.
  9735. *
  9736. * @example
  9737. <example module="customInterpolationApp">
  9738. <file name="index.html">
  9739. <script>
  9740. var customInterpolationApp = angular.module('customInterpolationApp', []);
  9741. customInterpolationApp.config(function($interpolateProvider) {
  9742. $interpolateProvider.startSymbol('//');
  9743. $interpolateProvider.endSymbol('//');
  9744. });
  9745. customInterpolationApp.controller('DemoController', function() {
  9746. this.label = "This binding is brought you by // interpolation symbols.";
  9747. });
  9748. </script>
  9749. <div ng-app="App" ng-controller="DemoController as demo">
  9750. //demo.label//
  9751. </div>
  9752. </file>
  9753. <file name="protractor.js" type="protractor">
  9754. it('should interpolate binding with custom symbols', function() {
  9755. expect(element(by.binding('demo.label')).getText()).toBe('This binding is brought you by // interpolation symbols.');
  9756. });
  9757. </file>
  9758. </example>
  9759. */
  9760. function $InterpolateProvider() {
  9761. var startSymbol = '{{';
  9762. var endSymbol = '}}';
  9763. /**
  9764. * @ngdoc method
  9765. * @name $interpolateProvider#startSymbol
  9766. * @description
  9767. * Symbol to denote start of expression in the interpolated string. Defaults to `{{`.
  9768. *
  9769. * @param {string=} value new value to set the starting symbol to.
  9770. * @returns {string|self} Returns the symbol when used as getter and self if used as setter.
  9771. */
  9772. this.startSymbol = function(value) {
  9773. if (value) {
  9774. startSymbol = value;
  9775. return this;
  9776. } else {
  9777. return startSymbol;
  9778. }
  9779. };
  9780. /**
  9781. * @ngdoc method
  9782. * @name $interpolateProvider#endSymbol
  9783. * @description
  9784. * Symbol to denote the end of expression in the interpolated string. Defaults to `}}`.
  9785. *
  9786. * @param {string=} value new value to set the ending symbol to.
  9787. * @returns {string|self} Returns the symbol when used as getter and self if used as setter.
  9788. */
  9789. this.endSymbol = function(value) {
  9790. if (value) {
  9791. endSymbol = value;
  9792. return this;
  9793. } else {
  9794. return endSymbol;
  9795. }
  9796. };
  9797. this.$get = ['$parse', '$exceptionHandler', '$sce', function($parse, $exceptionHandler, $sce) {
  9798. var startSymbolLength = startSymbol.length,
  9799. endSymbolLength = endSymbol.length,
  9800. escapedStartRegexp = new RegExp(startSymbol.replace(/./g, escape), 'g'),
  9801. escapedEndRegexp = new RegExp(endSymbol.replace(/./g, escape), 'g');
  9802. function escape(ch) {
  9803. return '\\\\\\' + ch;
  9804. }
  9805. function unescapeText(text) {
  9806. return text.replace(escapedStartRegexp, startSymbol).
  9807. replace(escapedEndRegexp, endSymbol);
  9808. }
  9809. function stringify(value) {
  9810. if (value == null) { // null || undefined
  9811. return '';
  9812. }
  9813. switch (typeof value) {
  9814. case 'string':
  9815. break;
  9816. case 'number':
  9817. value = '' + value;
  9818. break;
  9819. default:
  9820. value = toJson(value);
  9821. }
  9822. return value;
  9823. }
  9824. /**
  9825. * @ngdoc service
  9826. * @name $interpolate
  9827. * @kind function
  9828. *
  9829. * @requires $parse
  9830. * @requires $sce
  9831. *
  9832. * @description
  9833. *
  9834. * Compiles a string with markup into an interpolation function. This service is used by the
  9835. * HTML {@link ng.$compile $compile} service for data binding. See
  9836. * {@link ng.$interpolateProvider $interpolateProvider} for configuring the
  9837. * interpolation markup.
  9838. *
  9839. *
  9840. * ```js
  9841. * var $interpolate = ...; // injected
  9842. * var exp = $interpolate('Hello {{name | uppercase}}!');
  9843. * expect(exp({name:'Angular'})).toEqual('Hello ANGULAR!');
  9844. * ```
  9845. *
  9846. * `$interpolate` takes an optional fourth argument, `allOrNothing`. If `allOrNothing` is
  9847. * `true`, the interpolation function will return `undefined` unless all embedded expressions
  9848. * evaluate to a value other than `undefined`.
  9849. *
  9850. * ```js
  9851. * var $interpolate = ...; // injected
  9852. * var context = {greeting: 'Hello', name: undefined };
  9853. *
  9854. * // default "forgiving" mode
  9855. * var exp = $interpolate('{{greeting}} {{name}}!');
  9856. * expect(exp(context)).toEqual('Hello !');
  9857. *
  9858. * // "allOrNothing" mode
  9859. * exp = $interpolate('{{greeting}} {{name}}!', false, null, true);
  9860. * expect(exp(context)).toBeUndefined();
  9861. * context.name = 'Angular';
  9862. * expect(exp(context)).toEqual('Hello Angular!');
  9863. * ```
  9864. *
  9865. * `allOrNothing` is useful for interpolating URLs. `ngSrc` and `ngSrcset` use this behavior.
  9866. *
  9867. * ####Escaped Interpolation
  9868. * $interpolate provides a mechanism for escaping interpolation markers. Start and end markers
  9869. * can be escaped by preceding each of their characters with a REVERSE SOLIDUS U+005C (backslash).
  9870. * It will be rendered as a regular start/end marker, and will not be interpreted as an expression
  9871. * or binding.
  9872. *
  9873. * This enables web-servers to prevent script injection attacks and defacing attacks, to some
  9874. * degree, while also enabling code examples to work without relying on the
  9875. * {@link ng.directive:ngNonBindable ngNonBindable} directive.
  9876. *
  9877. * **For security purposes, it is strongly encouraged that web servers escape user-supplied data,
  9878. * replacing angle brackets (&lt;, &gt;) with &amp;lt; and &amp;gt; respectively, and replacing all
  9879. * interpolation start/end markers with their escaped counterparts.**
  9880. *
  9881. * Escaped interpolation markers are only replaced with the actual interpolation markers in rendered
  9882. * output when the $interpolate service processes the text. So, for HTML elements interpolated
  9883. * by {@link ng.$compile $compile}, or otherwise interpolated with the `mustHaveExpression` parameter
  9884. * set to `true`, the interpolated text must contain an unescaped interpolation expression. As such,
  9885. * this is typically useful only when user-data is used in rendering a template from the server, or
  9886. * when otherwise untrusted data is used by a directive.
  9887. *
  9888. * <example>
  9889. * <file name="index.html">
  9890. * <div ng-init="username='A user'">
  9891. * <p ng-init="apptitle='Escaping demo'">{{apptitle}}: \{\{ username = "defaced value"; \}\}
  9892. * </p>
  9893. * <p><strong>{{username}}</strong> attempts to inject code which will deface the
  9894. * application, but fails to accomplish their task, because the server has correctly
  9895. * escaped the interpolation start/end markers with REVERSE SOLIDUS U+005C (backslash)
  9896. * characters.</p>
  9897. * <p>Instead, the result of the attempted script injection is visible, and can be removed
  9898. * from the database by an administrator.</p>
  9899. * </div>
  9900. * </file>
  9901. * </example>
  9902. *
  9903. * @param {string} text The text with markup to interpolate.
  9904. * @param {boolean=} mustHaveExpression if set to true then the interpolation string must have
  9905. * embedded expression in order to return an interpolation function. Strings with no
  9906. * embedded expression will return null for the interpolation function.
  9907. * @param {string=} trustedContext when provided, the returned function passes the interpolated
  9908. * result through {@link ng.$sce#getTrusted $sce.getTrusted(interpolatedResult,
  9909. * trustedContext)} before returning it. Refer to the {@link ng.$sce $sce} service that
  9910. * provides Strict Contextual Escaping for details.
  9911. * @param {boolean=} allOrNothing if `true`, then the returned function returns undefined
  9912. * unless all embedded expressions evaluate to a value other than `undefined`.
  9913. * @returns {function(context)} an interpolation function which is used to compute the
  9914. * interpolated string. The function has these parameters:
  9915. *
  9916. * - `context`: evaluation context for all expressions embedded in the interpolated text
  9917. */
  9918. function $interpolate(text, mustHaveExpression, trustedContext, allOrNothing) {
  9919. allOrNothing = !!allOrNothing;
  9920. var startIndex,
  9921. endIndex,
  9922. index = 0,
  9923. expressions = [],
  9924. parseFns = [],
  9925. textLength = text.length,
  9926. exp,
  9927. concat = [],
  9928. expressionPositions = [];
  9929. while (index < textLength) {
  9930. if (((startIndex = text.indexOf(startSymbol, index)) != -1) &&
  9931. ((endIndex = text.indexOf(endSymbol, startIndex + startSymbolLength)) != -1)) {
  9932. if (index !== startIndex) {
  9933. concat.push(unescapeText(text.substring(index, startIndex)));
  9934. }
  9935. exp = text.substring(startIndex + startSymbolLength, endIndex);
  9936. expressions.push(exp);
  9937. parseFns.push($parse(exp, parseStringifyInterceptor));
  9938. index = endIndex + endSymbolLength;
  9939. expressionPositions.push(concat.length);
  9940. concat.push('');
  9941. } else {
  9942. // we did not find an interpolation, so we have to add the remainder to the separators array
  9943. if (index !== textLength) {
  9944. concat.push(unescapeText(text.substring(index)));
  9945. }
  9946. break;
  9947. }
  9948. }
  9949. // Concatenating expressions makes it hard to reason about whether some combination of
  9950. // concatenated values are unsafe to use and could easily lead to XSS. By requiring that a
  9951. // single expression be used for iframe[src], object[src], etc., we ensure that the value
  9952. // that's used is assigned or constructed by some JS code somewhere that is more testable or
  9953. // make it obvious that you bound the value to some user controlled value. This helps reduce
  9954. // the load when auditing for XSS issues.
  9955. if (trustedContext && concat.length > 1) {
  9956. $interpolateMinErr.throwNoconcat(text);
  9957. }
  9958. if (!mustHaveExpression || expressions.length) {
  9959. var compute = function(values) {
  9960. for (var i = 0, ii = expressions.length; i < ii; i++) {
  9961. if (allOrNothing && isUndefined(values[i])) return;
  9962. concat[expressionPositions[i]] = values[i];
  9963. }
  9964. return concat.join('');
  9965. };
  9966. var getValue = function(value) {
  9967. return trustedContext ?
  9968. $sce.getTrusted(trustedContext, value) :
  9969. $sce.valueOf(value);
  9970. };
  9971. return extend(function interpolationFn(context) {
  9972. var i = 0;
  9973. var ii = expressions.length;
  9974. var values = new Array(ii);
  9975. try {
  9976. for (; i < ii; i++) {
  9977. values[i] = parseFns[i](context);
  9978. }
  9979. return compute(values);
  9980. } catch (err) {
  9981. $exceptionHandler($interpolateMinErr.interr(text, err));
  9982. }
  9983. }, {
  9984. // all of these properties are undocumented for now
  9985. exp: text, //just for compatibility with regular watchers created via $watch
  9986. expressions: expressions,
  9987. $$watchDelegate: function(scope, listener) {
  9988. var lastValue;
  9989. return scope.$watchGroup(parseFns, function interpolateFnWatcher(values, oldValues) {
  9990. var currValue = compute(values);
  9991. if (isFunction(listener)) {
  9992. listener.call(this, currValue, values !== oldValues ? lastValue : currValue, scope);
  9993. }
  9994. lastValue = currValue;
  9995. });
  9996. }
  9997. });
  9998. }
  9999. function parseStringifyInterceptor(value) {
  10000. try {
  10001. value = getValue(value);
  10002. return allOrNothing && !isDefined(value) ? value : stringify(value);
  10003. } catch (err) {
  10004. $exceptionHandler($interpolateMinErr.interr(text, err));
  10005. }
  10006. }
  10007. }
  10008. /**
  10009. * @ngdoc method
  10010. * @name $interpolate#startSymbol
  10011. * @description
  10012. * Symbol to denote the start of expression in the interpolated string. Defaults to `{{`.
  10013. *
  10014. * Use {@link ng.$interpolateProvider#startSymbol `$interpolateProvider.startSymbol`} to change
  10015. * the symbol.
  10016. *
  10017. * @returns {string} start symbol.
  10018. */
  10019. $interpolate.startSymbol = function() {
  10020. return startSymbol;
  10021. };
  10022. /**
  10023. * @ngdoc method
  10024. * @name $interpolate#endSymbol
  10025. * @description
  10026. * Symbol to denote the end of expression in the interpolated string. Defaults to `}}`.
  10027. *
  10028. * Use {@link ng.$interpolateProvider#endSymbol `$interpolateProvider.endSymbol`} to change
  10029. * the symbol.
  10030. *
  10031. * @returns {string} end symbol.
  10032. */
  10033. $interpolate.endSymbol = function() {
  10034. return endSymbol;
  10035. };
  10036. return $interpolate;
  10037. }];
  10038. }
  10039. function $IntervalProvider() {
  10040. this.$get = ['$rootScope', '$window', '$q', '$$q',
  10041. function($rootScope, $window, $q, $$q) {
  10042. var intervals = {};
  10043. /**
  10044. * @ngdoc service
  10045. * @name $interval
  10046. *
  10047. * @description
  10048. * Angular's wrapper for `window.setInterval`. The `fn` function is executed every `delay`
  10049. * milliseconds.
  10050. *
  10051. * The return value of registering an interval function is a promise. This promise will be
  10052. * notified upon each tick of the interval, and will be resolved after `count` iterations, or
  10053. * run indefinitely if `count` is not defined. The value of the notification will be the
  10054. * number of iterations that have run.
  10055. * To cancel an interval, call `$interval.cancel(promise)`.
  10056. *
  10057. * In tests you can use {@link ngMock.$interval#flush `$interval.flush(millis)`} to
  10058. * move forward by `millis` milliseconds and trigger any functions scheduled to run in that
  10059. * time.
  10060. *
  10061. * <div class="alert alert-warning">
  10062. * **Note**: Intervals created by this service must be explicitly destroyed when you are finished
  10063. * with them. In particular they are not automatically destroyed when a controller's scope or a
  10064. * directive's element are destroyed.
  10065. * You should take this into consideration and make sure to always cancel the interval at the
  10066. * appropriate moment. See the example below for more details on how and when to do this.
  10067. * </div>
  10068. *
  10069. * @param {function()} fn A function that should be called repeatedly.
  10070. * @param {number} delay Number of milliseconds between each function call.
  10071. * @param {number=} [count=0] Number of times to repeat. If not set, or 0, will repeat
  10072. * indefinitely.
  10073. * @param {boolean=} [invokeApply=true] If set to `false` skips model dirty checking, otherwise
  10074. * will invoke `fn` within the {@link ng.$rootScope.Scope#$apply $apply} block.
  10075. * @param {...*=} Pass additional parameters to the executed function.
  10076. * @returns {promise} A promise which will be notified on each iteration.
  10077. *
  10078. * @example
  10079. * <example module="intervalExample">
  10080. * <file name="index.html">
  10081. * <script>
  10082. * angular.module('intervalExample', [])
  10083. * .controller('ExampleController', ['$scope', '$interval',
  10084. * function($scope, $interval) {
  10085. * $scope.format = 'M/d/yy h:mm:ss a';
  10086. * $scope.blood_1 = 100;
  10087. * $scope.blood_2 = 120;
  10088. *
  10089. * var stop;
  10090. * $scope.fight = function() {
  10091. * // Don't start a new fight if we are already fighting
  10092. * if ( angular.isDefined(stop) ) return;
  10093. *
  10094. * stop = $interval(function() {
  10095. * if ($scope.blood_1 > 0 && $scope.blood_2 > 0) {
  10096. * $scope.blood_1 = $scope.blood_1 - 3;
  10097. * $scope.blood_2 = $scope.blood_2 - 4;
  10098. * } else {
  10099. * $scope.stopFight();
  10100. * }
  10101. * }, 100);
  10102. * };
  10103. *
  10104. * $scope.stopFight = function() {
  10105. * if (angular.isDefined(stop)) {
  10106. * $interval.cancel(stop);
  10107. * stop = undefined;
  10108. * }
  10109. * };
  10110. *
  10111. * $scope.resetFight = function() {
  10112. * $scope.blood_1 = 100;
  10113. * $scope.blood_2 = 120;
  10114. * };
  10115. *
  10116. * $scope.$on('$destroy', function() {
  10117. * // Make sure that the interval is destroyed too
  10118. * $scope.stopFight();
  10119. * });
  10120. * }])
  10121. * // Register the 'myCurrentTime' directive factory method.
  10122. * // We inject $interval and dateFilter service since the factory method is DI.
  10123. * .directive('myCurrentTime', ['$interval', 'dateFilter',
  10124. * function($interval, dateFilter) {
  10125. * // return the directive link function. (compile function not needed)
  10126. * return function(scope, element, attrs) {
  10127. * var format, // date format
  10128. * stopTime; // so that we can cancel the time updates
  10129. *
  10130. * // used to update the UI
  10131. * function updateTime() {
  10132. * element.text(dateFilter(new Date(), format));
  10133. * }
  10134. *
  10135. * // watch the expression, and update the UI on change.
  10136. * scope.$watch(attrs.myCurrentTime, function(value) {
  10137. * format = value;
  10138. * updateTime();
  10139. * });
  10140. *
  10141. * stopTime = $interval(updateTime, 1000);
  10142. *
  10143. * // listen on DOM destroy (removal) event, and cancel the next UI update
  10144. * // to prevent updating time after the DOM element was removed.
  10145. * element.on('$destroy', function() {
  10146. * $interval.cancel(stopTime);
  10147. * });
  10148. * }
  10149. * }]);
  10150. * </script>
  10151. *
  10152. * <div>
  10153. * <div ng-controller="ExampleController">
  10154. * <label>Date format: <input ng-model="format"></label> <hr/>
  10155. * Current time is: <span my-current-time="format"></span>
  10156. * <hr/>
  10157. * Blood 1 : <font color='red'>{{blood_1}}</font>
  10158. * Blood 2 : <font color='red'>{{blood_2}}</font>
  10159. * <button type="button" data-ng-click="fight()">Fight</button>
  10160. * <button type="button" data-ng-click="stopFight()">StopFight</button>
  10161. * <button type="button" data-ng-click="resetFight()">resetFight</button>
  10162. * </div>
  10163. * </div>
  10164. *
  10165. * </file>
  10166. * </example>
  10167. */
  10168. function interval(fn, delay, count, invokeApply) {
  10169. var hasParams = arguments.length > 4,
  10170. args = hasParams ? sliceArgs(arguments, 4) : [],
  10171. setInterval = $window.setInterval,
  10172. clearInterval = $window.clearInterval,
  10173. iteration = 0,
  10174. skipApply = (isDefined(invokeApply) && !invokeApply),
  10175. deferred = (skipApply ? $$q : $q).defer(),
  10176. promise = deferred.promise;
  10177. count = isDefined(count) ? count : 0;
  10178. promise.then(null, null, (!hasParams) ? fn : function() {
  10179. fn.apply(null, args);
  10180. });
  10181. promise.$$intervalId = setInterval(function tick() {
  10182. deferred.notify(iteration++);
  10183. if (count > 0 && iteration >= count) {
  10184. deferred.resolve(iteration);
  10185. clearInterval(promise.$$intervalId);
  10186. delete intervals[promise.$$intervalId];
  10187. }
  10188. if (!skipApply) $rootScope.$apply();
  10189. }, delay);
  10190. intervals[promise.$$intervalId] = deferred;
  10191. return promise;
  10192. }
  10193. /**
  10194. * @ngdoc method
  10195. * @name $interval#cancel
  10196. *
  10197. * @description
  10198. * Cancels a task associated with the `promise`.
  10199. *
  10200. * @param {Promise=} promise returned by the `$interval` function.
  10201. * @returns {boolean} Returns `true` if the task was successfully canceled.
  10202. */
  10203. interval.cancel = function(promise) {
  10204. if (promise && promise.$$intervalId in intervals) {
  10205. intervals[promise.$$intervalId].reject('canceled');
  10206. $window.clearInterval(promise.$$intervalId);
  10207. delete intervals[promise.$$intervalId];
  10208. return true;
  10209. }
  10210. return false;
  10211. };
  10212. return interval;
  10213. }];
  10214. }
  10215. /**
  10216. * @ngdoc service
  10217. * @name $locale
  10218. *
  10219. * @description
  10220. * $locale service provides localization rules for various Angular components. As of right now the
  10221. * only public api is:
  10222. *
  10223. * * `id` – `{string}` – locale id formatted as `languageId-countryId` (e.g. `en-us`)
  10224. */
  10225. var PATH_MATCH = /^([^\?#]*)(\?([^#]*))?(#(.*))?$/,
  10226. DEFAULT_PORTS = {'http': 80, 'https': 443, 'ftp': 21};
  10227. var $locationMinErr = minErr('$location');
  10228. /**
  10229. * Encode path using encodeUriSegment, ignoring forward slashes
  10230. *
  10231. * @param {string} path Path to encode
  10232. * @returns {string}
  10233. */
  10234. function encodePath(path) {
  10235. var segments = path.split('/'),
  10236. i = segments.length;
  10237. while (i--) {
  10238. segments[i] = encodeUriSegment(segments[i]);
  10239. }
  10240. return segments.join('/');
  10241. }
  10242. function parseAbsoluteUrl(absoluteUrl, locationObj) {
  10243. var parsedUrl = urlResolve(absoluteUrl);
  10244. locationObj.$$protocol = parsedUrl.protocol;
  10245. locationObj.$$host = parsedUrl.hostname;
  10246. locationObj.$$port = toInt(parsedUrl.port) || DEFAULT_PORTS[parsedUrl.protocol] || null;
  10247. }
  10248. function parseAppUrl(relativeUrl, locationObj) {
  10249. var prefixed = (relativeUrl.charAt(0) !== '/');
  10250. if (prefixed) {
  10251. relativeUrl = '/' + relativeUrl;
  10252. }
  10253. var match = urlResolve(relativeUrl);
  10254. locationObj.$$path = decodeURIComponent(prefixed && match.pathname.charAt(0) === '/' ?
  10255. match.pathname.substring(1) : match.pathname);
  10256. locationObj.$$search = parseKeyValue(match.search);
  10257. locationObj.$$hash = decodeURIComponent(match.hash);
  10258. // make sure path starts with '/';
  10259. if (locationObj.$$path && locationObj.$$path.charAt(0) != '/') {
  10260. locationObj.$$path = '/' + locationObj.$$path;
  10261. }
  10262. }
  10263. /**
  10264. *
  10265. * @param {string} begin
  10266. * @param {string} whole
  10267. * @returns {string} returns text from whole after begin or undefined if it does not begin with
  10268. * expected string.
  10269. */
  10270. function beginsWith(begin, whole) {
  10271. if (whole.indexOf(begin) === 0) {
  10272. return whole.substr(begin.length);
  10273. }
  10274. }
  10275. function stripHash(url) {
  10276. var index = url.indexOf('#');
  10277. return index == -1 ? url : url.substr(0, index);
  10278. }
  10279. function trimEmptyHash(url) {
  10280. return url.replace(/(#.+)|#$/, '$1');
  10281. }
  10282. function stripFile(url) {
  10283. return url.substr(0, stripHash(url).lastIndexOf('/') + 1);
  10284. }
  10285. /* return the server only (scheme://host:port) */
  10286. function serverBase(url) {
  10287. return url.substring(0, url.indexOf('/', url.indexOf('//') + 2));
  10288. }
  10289. /**
  10290. * LocationHtml5Url represents an url
  10291. * This object is exposed as $location service when HTML5 mode is enabled and supported
  10292. *
  10293. * @constructor
  10294. * @param {string} appBase application base URL
  10295. * @param {string} appBaseNoFile application base URL stripped of any filename
  10296. * @param {string} basePrefix url path prefix
  10297. */
  10298. function LocationHtml5Url(appBase, appBaseNoFile, basePrefix) {
  10299. this.$$html5 = true;
  10300. basePrefix = basePrefix || '';
  10301. parseAbsoluteUrl(appBase, this);
  10302. /**
  10303. * Parse given html5 (regular) url string into properties
  10304. * @param {string} url HTML5 url
  10305. * @private
  10306. */
  10307. this.$$parse = function(url) {
  10308. var pathUrl = beginsWith(appBaseNoFile, url);
  10309. if (!isString(pathUrl)) {
  10310. throw $locationMinErr('ipthprfx', 'Invalid url "{0}", missing path prefix "{1}".', url,
  10311. appBaseNoFile);
  10312. }
  10313. parseAppUrl(pathUrl, this);
  10314. if (!this.$$path) {
  10315. this.$$path = '/';
  10316. }
  10317. this.$$compose();
  10318. };
  10319. /**
  10320. * Compose url and update `absUrl` property
  10321. * @private
  10322. */
  10323. this.$$compose = function() {
  10324. var search = toKeyValue(this.$$search),
  10325. hash = this.$$hash ? '#' + encodeUriSegment(this.$$hash) : '';
  10326. this.$$url = encodePath(this.$$path) + (search ? '?' + search : '') + hash;
  10327. this.$$absUrl = appBaseNoFile + this.$$url.substr(1); // first char is always '/'
  10328. };
  10329. this.$$parseLinkUrl = function(url, relHref) {
  10330. if (relHref && relHref[0] === '#') {
  10331. // special case for links to hash fragments:
  10332. // keep the old url and only replace the hash fragment
  10333. this.hash(relHref.slice(1));
  10334. return true;
  10335. }
  10336. var appUrl, prevAppUrl;
  10337. var rewrittenUrl;
  10338. if (isDefined(appUrl = beginsWith(appBase, url))) {
  10339. prevAppUrl = appUrl;
  10340. if (isDefined(appUrl = beginsWith(basePrefix, appUrl))) {
  10341. rewrittenUrl = appBaseNoFile + (beginsWith('/', appUrl) || appUrl);
  10342. } else {
  10343. rewrittenUrl = appBase + prevAppUrl;
  10344. }
  10345. } else if (isDefined(appUrl = beginsWith(appBaseNoFile, url))) {
  10346. rewrittenUrl = appBaseNoFile + appUrl;
  10347. } else if (appBaseNoFile == url + '/') {
  10348. rewrittenUrl = appBaseNoFile;
  10349. }
  10350. if (rewrittenUrl) {
  10351. this.$$parse(rewrittenUrl);
  10352. }
  10353. return !!rewrittenUrl;
  10354. };
  10355. }
  10356. /**
  10357. * LocationHashbangUrl represents url
  10358. * This object is exposed as $location service when developer doesn't opt into html5 mode.
  10359. * It also serves as the base class for html5 mode fallback on legacy browsers.
  10360. *
  10361. * @constructor
  10362. * @param {string} appBase application base URL
  10363. * @param {string} appBaseNoFile application base URL stripped of any filename
  10364. * @param {string} hashPrefix hashbang prefix
  10365. */
  10366. function LocationHashbangUrl(appBase, appBaseNoFile, hashPrefix) {
  10367. parseAbsoluteUrl(appBase, this);
  10368. /**
  10369. * Parse given hashbang url into properties
  10370. * @param {string} url Hashbang url
  10371. * @private
  10372. */
  10373. this.$$parse = function(url) {
  10374. var withoutBaseUrl = beginsWith(appBase, url) || beginsWith(appBaseNoFile, url);
  10375. var withoutHashUrl;
  10376. if (!isUndefined(withoutBaseUrl) && withoutBaseUrl.charAt(0) === '#') {
  10377. // The rest of the url starts with a hash so we have
  10378. // got either a hashbang path or a plain hash fragment
  10379. withoutHashUrl = beginsWith(hashPrefix, withoutBaseUrl);
  10380. if (isUndefined(withoutHashUrl)) {
  10381. // There was no hashbang prefix so we just have a hash fragment
  10382. withoutHashUrl = withoutBaseUrl;
  10383. }
  10384. } else {
  10385. // There was no hashbang path nor hash fragment:
  10386. // If we are in HTML5 mode we use what is left as the path;
  10387. // Otherwise we ignore what is left
  10388. if (this.$$html5) {
  10389. withoutHashUrl = withoutBaseUrl;
  10390. } else {
  10391. withoutHashUrl = '';
  10392. if (isUndefined(withoutBaseUrl)) {
  10393. appBase = url;
  10394. this.replace();
  10395. }
  10396. }
  10397. }
  10398. parseAppUrl(withoutHashUrl, this);
  10399. this.$$path = removeWindowsDriveName(this.$$path, withoutHashUrl, appBase);
  10400. this.$$compose();
  10401. /*
  10402. * In Windows, on an anchor node on documents loaded from
  10403. * the filesystem, the browser will return a pathname
  10404. * prefixed with the drive name ('/C:/path') when a
  10405. * pathname without a drive is set:
  10406. * * a.setAttribute('href', '/foo')
  10407. * * a.pathname === '/C:/foo' //true
  10408. *
  10409. * Inside of Angular, we're always using pathnames that
  10410. * do not include drive names for routing.
  10411. */
  10412. function removeWindowsDriveName(path, url, base) {
  10413. /*
  10414. Matches paths for file protocol on windows,
  10415. such as /C:/foo/bar, and captures only /foo/bar.
  10416. */
  10417. var windowsFilePathExp = /^\/[A-Z]:(\/.*)/;
  10418. var firstPathSegmentMatch;
  10419. //Get the relative path from the input URL.
  10420. if (url.indexOf(base) === 0) {
  10421. url = url.replace(base, '');
  10422. }
  10423. // The input URL intentionally contains a first path segment that ends with a colon.
  10424. if (windowsFilePathExp.exec(url)) {
  10425. return path;
  10426. }
  10427. firstPathSegmentMatch = windowsFilePathExp.exec(path);
  10428. return firstPathSegmentMatch ? firstPathSegmentMatch[1] : path;
  10429. }
  10430. };
  10431. /**
  10432. * Compose hashbang url and update `absUrl` property
  10433. * @private
  10434. */
  10435. this.$$compose = function() {
  10436. var search = toKeyValue(this.$$search),
  10437. hash = this.$$hash ? '#' + encodeUriSegment(this.$$hash) : '';
  10438. this.$$url = encodePath(this.$$path) + (search ? '?' + search : '') + hash;
  10439. this.$$absUrl = appBase + (this.$$url ? hashPrefix + this.$$url : '');
  10440. };
  10441. this.$$parseLinkUrl = function(url, relHref) {
  10442. if (stripHash(appBase) == stripHash(url)) {
  10443. this.$$parse(url);
  10444. return true;
  10445. }
  10446. return false;
  10447. };
  10448. }
  10449. /**
  10450. * LocationHashbangUrl represents url
  10451. * This object is exposed as $location service when html5 history api is enabled but the browser
  10452. * does not support it.
  10453. *
  10454. * @constructor
  10455. * @param {string} appBase application base URL
  10456. * @param {string} appBaseNoFile application base URL stripped of any filename
  10457. * @param {string} hashPrefix hashbang prefix
  10458. */
  10459. function LocationHashbangInHtml5Url(appBase, appBaseNoFile, hashPrefix) {
  10460. this.$$html5 = true;
  10461. LocationHashbangUrl.apply(this, arguments);
  10462. this.$$parseLinkUrl = function(url, relHref) {
  10463. if (relHref && relHref[0] === '#') {
  10464. // special case for links to hash fragments:
  10465. // keep the old url and only replace the hash fragment
  10466. this.hash(relHref.slice(1));
  10467. return true;
  10468. }
  10469. var rewrittenUrl;
  10470. var appUrl;
  10471. if (appBase == stripHash(url)) {
  10472. rewrittenUrl = url;
  10473. } else if ((appUrl = beginsWith(appBaseNoFile, url))) {
  10474. rewrittenUrl = appBase + hashPrefix + appUrl;
  10475. } else if (appBaseNoFile === url + '/') {
  10476. rewrittenUrl = appBaseNoFile;
  10477. }
  10478. if (rewrittenUrl) {
  10479. this.$$parse(rewrittenUrl);
  10480. }
  10481. return !!rewrittenUrl;
  10482. };
  10483. this.$$compose = function() {
  10484. var search = toKeyValue(this.$$search),
  10485. hash = this.$$hash ? '#' + encodeUriSegment(this.$$hash) : '';
  10486. this.$$url = encodePath(this.$$path) + (search ? '?' + search : '') + hash;
  10487. // include hashPrefix in $$absUrl when $$url is empty so IE9 does not reload page because of removal of '#'
  10488. this.$$absUrl = appBase + hashPrefix + this.$$url;
  10489. };
  10490. }
  10491. var locationPrototype = {
  10492. /**
  10493. * Are we in html5 mode?
  10494. * @private
  10495. */
  10496. $$html5: false,
  10497. /**
  10498. * Has any change been replacing?
  10499. * @private
  10500. */
  10501. $$replace: false,
  10502. /**
  10503. * @ngdoc method
  10504. * @name $location#absUrl
  10505. *
  10506. * @description
  10507. * This method is getter only.
  10508. *
  10509. * Return full url representation with all segments encoded according to rules specified in
  10510. * [RFC 3986](http://www.ietf.org/rfc/rfc3986.txt).
  10511. *
  10512. *
  10513. * ```js
  10514. * // given url http://example.com/#/some/path?foo=bar&baz=xoxo
  10515. * var absUrl = $location.absUrl();
  10516. * // => "http://example.com/#/some/path?foo=bar&baz=xoxo"
  10517. * ```
  10518. *
  10519. * @return {string} full url
  10520. */
  10521. absUrl: locationGetter('$$absUrl'),
  10522. /**
  10523. * @ngdoc method
  10524. * @name $location#url
  10525. *
  10526. * @description
  10527. * This method is getter / setter.
  10528. *
  10529. * Return url (e.g. `/path?a=b#hash`) when called without any parameter.
  10530. *
  10531. * Change path, search and hash, when called with parameter and return `$location`.
  10532. *
  10533. *
  10534. * ```js
  10535. * // given url http://example.com/#/some/path?foo=bar&baz=xoxo
  10536. * var url = $location.url();
  10537. * // => "/some/path?foo=bar&baz=xoxo"
  10538. * ```
  10539. *
  10540. * @param {string=} url New url without base prefix (e.g. `/path?a=b#hash`)
  10541. * @return {string} url
  10542. */
  10543. url: function(url) {
  10544. if (isUndefined(url)) {
  10545. return this.$$url;
  10546. }
  10547. var match = PATH_MATCH.exec(url);
  10548. if (match[1] || url === '') this.path(decodeURIComponent(match[1]));
  10549. if (match[2] || match[1] || url === '') this.search(match[3] || '');
  10550. this.hash(match[5] || '');
  10551. return this;
  10552. },
  10553. /**
  10554. * @ngdoc method
  10555. * @name $location#protocol
  10556. *
  10557. * @description
  10558. * This method is getter only.
  10559. *
  10560. * Return protocol of current url.
  10561. *
  10562. *
  10563. * ```js
  10564. * // given url http://example.com/#/some/path?foo=bar&baz=xoxo
  10565. * var protocol = $location.protocol();
  10566. * // => "http"
  10567. * ```
  10568. *
  10569. * @return {string} protocol of current url
  10570. */
  10571. protocol: locationGetter('$$protocol'),
  10572. /**
  10573. * @ngdoc method
  10574. * @name $location#host
  10575. *
  10576. * @description
  10577. * This method is getter only.
  10578. *
  10579. * Return host of current url.
  10580. *
  10581. * Note: compared to the non-angular version `location.host` which returns `hostname:port`, this returns the `hostname` portion only.
  10582. *
  10583. *
  10584. * ```js
  10585. * // given url http://example.com/#/some/path?foo=bar&baz=xoxo
  10586. * var host = $location.host();
  10587. * // => "example.com"
  10588. *
  10589. * // given url http://user:password@example.com:8080/#/some/path?foo=bar&baz=xoxo
  10590. * host = $location.host();
  10591. * // => "example.com"
  10592. * host = location.host;
  10593. * // => "example.com:8080"
  10594. * ```
  10595. *
  10596. * @return {string} host of current url.
  10597. */
  10598. host: locationGetter('$$host'),
  10599. /**
  10600. * @ngdoc method
  10601. * @name $location#port
  10602. *
  10603. * @description
  10604. * This method is getter only.
  10605. *
  10606. * Return port of current url.
  10607. *
  10608. *
  10609. * ```js
  10610. * // given url http://example.com/#/some/path?foo=bar&baz=xoxo
  10611. * var port = $location.port();
  10612. * // => 80
  10613. * ```
  10614. *
  10615. * @return {Number} port
  10616. */
  10617. port: locationGetter('$$port'),
  10618. /**
  10619. * @ngdoc method
  10620. * @name $location#path
  10621. *
  10622. * @description
  10623. * This method is getter / setter.
  10624. *
  10625. * Return path of current url when called without any parameter.
  10626. *
  10627. * Change path when called with parameter and return `$location`.
  10628. *
  10629. * Note: Path should always begin with forward slash (/), this method will add the forward slash
  10630. * if it is missing.
  10631. *
  10632. *
  10633. * ```js
  10634. * // given url http://example.com/#/some/path?foo=bar&baz=xoxo
  10635. * var path = $location.path();
  10636. * // => "/some/path"
  10637. * ```
  10638. *
  10639. * @param {(string|number)=} path New path
  10640. * @return {string} path
  10641. */
  10642. path: locationGetterSetter('$$path', function(path) {
  10643. path = path !== null ? path.toString() : '';
  10644. return path.charAt(0) == '/' ? path : '/' + path;
  10645. }),
  10646. /**
  10647. * @ngdoc method
  10648. * @name $location#search
  10649. *
  10650. * @description
  10651. * This method is getter / setter.
  10652. *
  10653. * Return search part (as object) of current url when called without any parameter.
  10654. *
  10655. * Change search part when called with parameter and return `$location`.
  10656. *
  10657. *
  10658. * ```js
  10659. * // given url http://example.com/#/some/path?foo=bar&baz=xoxo
  10660. * var searchObject = $location.search();
  10661. * // => {foo: 'bar', baz: 'xoxo'}
  10662. *
  10663. * // set foo to 'yipee'
  10664. * $location.search('foo', 'yipee');
  10665. * // $location.search() => {foo: 'yipee', baz: 'xoxo'}
  10666. * ```
  10667. *
  10668. * @param {string|Object.<string>|Object.<Array.<string>>} search New search params - string or
  10669. * hash object.
  10670. *
  10671. * When called with a single argument the method acts as a setter, setting the `search` component
  10672. * of `$location` to the specified value.
  10673. *
  10674. * If the argument is a hash object containing an array of values, these values will be encoded
  10675. * as duplicate search parameters in the url.
  10676. *
  10677. * @param {(string|Number|Array<string>|boolean)=} paramValue If `search` is a string or number, then `paramValue`
  10678. * will override only a single search property.
  10679. *
  10680. * If `paramValue` is an array, it will override the property of the `search` component of
  10681. * `$location` specified via the first argument.
  10682. *
  10683. * If `paramValue` is `null`, the property specified via the first argument will be deleted.
  10684. *
  10685. * If `paramValue` is `true`, the property specified via the first argument will be added with no
  10686. * value nor trailing equal sign.
  10687. *
  10688. * @return {Object} If called with no arguments returns the parsed `search` object. If called with
  10689. * one or more arguments returns `$location` object itself.
  10690. */
  10691. search: function(search, paramValue) {
  10692. switch (arguments.length) {
  10693. case 0:
  10694. return this.$$search;
  10695. case 1:
  10696. if (isString(search) || isNumber(search)) {
  10697. search = search.toString();
  10698. this.$$search = parseKeyValue(search);
  10699. } else if (isObject(search)) {
  10700. search = copy(search, {});
  10701. // remove object undefined or null properties
  10702. forEach(search, function(value, key) {
  10703. if (value == null) delete search[key];
  10704. });
  10705. this.$$search = search;
  10706. } else {
  10707. throw $locationMinErr('isrcharg',
  10708. 'The first argument of the `$location#search()` call must be a string or an object.');
  10709. }
  10710. break;
  10711. default:
  10712. if (isUndefined(paramValue) || paramValue === null) {
  10713. delete this.$$search[search];
  10714. } else {
  10715. this.$$search[search] = paramValue;
  10716. }
  10717. }
  10718. this.$$compose();
  10719. return this;
  10720. },
  10721. /**
  10722. * @ngdoc method
  10723. * @name $location#hash
  10724. *
  10725. * @description
  10726. * This method is getter / setter.
  10727. *
  10728. * Return hash fragment when called without any parameter.
  10729. *
  10730. * Change hash fragment when called with parameter and return `$location`.
  10731. *
  10732. *
  10733. * ```js
  10734. * // given url http://example.com/#/some/path?foo=bar&baz=xoxo#hashValue
  10735. * var hash = $location.hash();
  10736. * // => "hashValue"
  10737. * ```
  10738. *
  10739. * @param {(string|number)=} hash New hash fragment
  10740. * @return {string} hash
  10741. */
  10742. hash: locationGetterSetter('$$hash', function(hash) {
  10743. return hash !== null ? hash.toString() : '';
  10744. }),
  10745. /**
  10746. * @ngdoc method
  10747. * @name $location#replace
  10748. *
  10749. * @description
  10750. * If called, all changes to $location during current `$digest` will be replacing current history
  10751. * record, instead of adding new one.
  10752. */
  10753. replace: function() {
  10754. this.$$replace = true;
  10755. return this;
  10756. }
  10757. };
  10758. forEach([LocationHashbangInHtml5Url, LocationHashbangUrl, LocationHtml5Url], function(Location) {
  10759. Location.prototype = Object.create(locationPrototype);
  10760. /**
  10761. * @ngdoc method
  10762. * @name $location#state
  10763. *
  10764. * @description
  10765. * This method is getter / setter.
  10766. *
  10767. * Return the history state object when called without any parameter.
  10768. *
  10769. * Change the history state object when called with one parameter and return `$location`.
  10770. * The state object is later passed to `pushState` or `replaceState`.
  10771. *
  10772. * NOTE: This method is supported only in HTML5 mode and only in browsers supporting
  10773. * the HTML5 History API (i.e. methods `pushState` and `replaceState`). If you need to support
  10774. * older browsers (like IE9 or Android < 4.0), don't use this method.
  10775. *
  10776. * @param {object=} state State object for pushState or replaceState
  10777. * @return {object} state
  10778. */
  10779. Location.prototype.state = function(state) {
  10780. if (!arguments.length) {
  10781. return this.$$state;
  10782. }
  10783. if (Location !== LocationHtml5Url || !this.$$html5) {
  10784. throw $locationMinErr('nostate', 'History API state support is available only ' +
  10785. 'in HTML5 mode and only in browsers supporting HTML5 History API');
  10786. }
  10787. // The user might modify `stateObject` after invoking `$location.state(stateObject)`
  10788. // but we're changing the $$state reference to $browser.state() during the $digest
  10789. // so the modification window is narrow.
  10790. this.$$state = isUndefined(state) ? null : state;
  10791. return this;
  10792. };
  10793. });
  10794. function locationGetter(property) {
  10795. return function() {
  10796. return this[property];
  10797. };
  10798. }
  10799. function locationGetterSetter(property, preprocess) {
  10800. return function(value) {
  10801. if (isUndefined(value)) {
  10802. return this[property];
  10803. }
  10804. this[property] = preprocess(value);
  10805. this.$$compose();
  10806. return this;
  10807. };
  10808. }
  10809. /**
  10810. * @ngdoc service
  10811. * @name $location
  10812. *
  10813. * @requires $rootElement
  10814. *
  10815. * @description
  10816. * The $location service parses the URL in the browser address bar (based on the
  10817. * [window.location](https://developer.mozilla.org/en/window.location)) and makes the URL
  10818. * available to your application. Changes to the URL in the address bar are reflected into
  10819. * $location service and changes to $location are reflected into the browser address bar.
  10820. *
  10821. * **The $location service:**
  10822. *
  10823. * - Exposes the current URL in the browser address bar, so you can
  10824. * - Watch and observe the URL.
  10825. * - Change the URL.
  10826. * - Synchronizes the URL with the browser when the user
  10827. * - Changes the address bar.
  10828. * - Clicks the back or forward button (or clicks a History link).
  10829. * - Clicks on a link.
  10830. * - Represents the URL object as a set of methods (protocol, host, port, path, search, hash).
  10831. *
  10832. * For more information see {@link guide/$location Developer Guide: Using $location}
  10833. */
  10834. /**
  10835. * @ngdoc provider
  10836. * @name $locationProvider
  10837. * @description
  10838. * Use the `$locationProvider` to configure how the application deep linking paths are stored.
  10839. */
  10840. function $LocationProvider() {
  10841. var hashPrefix = '',
  10842. html5Mode = {
  10843. enabled: false,
  10844. requireBase: true,
  10845. rewriteLinks: true
  10846. };
  10847. /**
  10848. * @ngdoc method
  10849. * @name $locationProvider#hashPrefix
  10850. * @description
  10851. * @param {string=} prefix Prefix for hash part (containing path and search)
  10852. * @returns {*} current value if used as getter or itself (chaining) if used as setter
  10853. */
  10854. this.hashPrefix = function(prefix) {
  10855. if (isDefined(prefix)) {
  10856. hashPrefix = prefix;
  10857. return this;
  10858. } else {
  10859. return hashPrefix;
  10860. }
  10861. };
  10862. /**
  10863. * @ngdoc method
  10864. * @name $locationProvider#html5Mode
  10865. * @description
  10866. * @param {(boolean|Object)=} mode If boolean, sets `html5Mode.enabled` to value.
  10867. * If object, sets `enabled`, `requireBase` and `rewriteLinks` to respective values. Supported
  10868. * properties:
  10869. * - **enabled** – `{boolean}` – (default: false) If true, will rely on `history.pushState` to
  10870. * change urls where supported. Will fall back to hash-prefixed paths in browsers that do not
  10871. * support `pushState`.
  10872. * - **requireBase** - `{boolean}` - (default: `true`) When html5Mode is enabled, specifies
  10873. * whether or not a <base> tag is required to be present. If `enabled` and `requireBase` are
  10874. * true, and a base tag is not present, an error will be thrown when `$location` is injected.
  10875. * See the {@link guide/$location $location guide for more information}
  10876. * - **rewriteLinks** - `{boolean}` - (default: `true`) When html5Mode is enabled,
  10877. * enables/disables url rewriting for relative links.
  10878. *
  10879. * @returns {Object} html5Mode object if used as getter or itself (chaining) if used as setter
  10880. */
  10881. this.html5Mode = function(mode) {
  10882. if (isBoolean(mode)) {
  10883. html5Mode.enabled = mode;
  10884. return this;
  10885. } else if (isObject(mode)) {
  10886. if (isBoolean(mode.enabled)) {
  10887. html5Mode.enabled = mode.enabled;
  10888. }
  10889. if (isBoolean(mode.requireBase)) {
  10890. html5Mode.requireBase = mode.requireBase;
  10891. }
  10892. if (isBoolean(mode.rewriteLinks)) {
  10893. html5Mode.rewriteLinks = mode.rewriteLinks;
  10894. }
  10895. return this;
  10896. } else {
  10897. return html5Mode;
  10898. }
  10899. };
  10900. /**
  10901. * @ngdoc event
  10902. * @name $location#$locationChangeStart
  10903. * @eventType broadcast on root scope
  10904. * @description
  10905. * Broadcasted before a URL will change.
  10906. *
  10907. * This change can be prevented by calling
  10908. * `preventDefault` method of the event. See {@link ng.$rootScope.Scope#$on} for more
  10909. * details about event object. Upon successful change
  10910. * {@link ng.$location#$locationChangeSuccess $locationChangeSuccess} is fired.
  10911. *
  10912. * The `newState` and `oldState` parameters may be defined only in HTML5 mode and when
  10913. * the browser supports the HTML5 History API.
  10914. *
  10915. * @param {Object} angularEvent Synthetic event object.
  10916. * @param {string} newUrl New URL
  10917. * @param {string=} oldUrl URL that was before it was changed.
  10918. * @param {string=} newState New history state object
  10919. * @param {string=} oldState History state object that was before it was changed.
  10920. */
  10921. /**
  10922. * @ngdoc event
  10923. * @name $location#$locationChangeSuccess
  10924. * @eventType broadcast on root scope
  10925. * @description
  10926. * Broadcasted after a URL was changed.
  10927. *
  10928. * The `newState` and `oldState` parameters may be defined only in HTML5 mode and when
  10929. * the browser supports the HTML5 History API.
  10930. *
  10931. * @param {Object} angularEvent Synthetic event object.
  10932. * @param {string} newUrl New URL
  10933. * @param {string=} oldUrl URL that was before it was changed.
  10934. * @param {string=} newState New history state object
  10935. * @param {string=} oldState History state object that was before it was changed.
  10936. */
  10937. this.$get = ['$rootScope', '$browser', '$sniffer', '$rootElement', '$window',
  10938. function($rootScope, $browser, $sniffer, $rootElement, $window) {
  10939. var $location,
  10940. LocationMode,
  10941. baseHref = $browser.baseHref(), // if base[href] is undefined, it defaults to ''
  10942. initialUrl = $browser.url(),
  10943. appBase;
  10944. if (html5Mode.enabled) {
  10945. if (!baseHref && html5Mode.requireBase) {
  10946. throw $locationMinErr('nobase',
  10947. "$location in HTML5 mode requires a <base> tag to be present!");
  10948. }
  10949. appBase = serverBase(initialUrl) + (baseHref || '/');
  10950. LocationMode = $sniffer.history ? LocationHtml5Url : LocationHashbangInHtml5Url;
  10951. } else {
  10952. appBase = stripHash(initialUrl);
  10953. LocationMode = LocationHashbangUrl;
  10954. }
  10955. var appBaseNoFile = stripFile(appBase);
  10956. $location = new LocationMode(appBase, appBaseNoFile, '#' + hashPrefix);
  10957. $location.$$parseLinkUrl(initialUrl, initialUrl);
  10958. $location.$$state = $browser.state();
  10959. var IGNORE_URI_REGEXP = /^\s*(javascript|mailto):/i;
  10960. function setBrowserUrlWithFallback(url, replace, state) {
  10961. var oldUrl = $location.url();
  10962. var oldState = $location.$$state;
  10963. try {
  10964. $browser.url(url, replace, state);
  10965. // Make sure $location.state() returns referentially identical (not just deeply equal)
  10966. // state object; this makes possible quick checking if the state changed in the digest
  10967. // loop. Checking deep equality would be too expensive.
  10968. $location.$$state = $browser.state();
  10969. } catch (e) {
  10970. // Restore old values if pushState fails
  10971. $location.url(oldUrl);
  10972. $location.$$state = oldState;
  10973. throw e;
  10974. }
  10975. }
  10976. $rootElement.on('click', function(event) {
  10977. // TODO(vojta): rewrite link when opening in new tab/window (in legacy browser)
  10978. // currently we open nice url link and redirect then
  10979. if (!html5Mode.rewriteLinks || event.ctrlKey || event.metaKey || event.shiftKey || event.which == 2 || event.button == 2) return;
  10980. var elm = jqLite(event.target);
  10981. // traverse the DOM up to find first A tag
  10982. while (nodeName_(elm[0]) !== 'a') {
  10983. // ignore rewriting if no A tag (reached root element, or no parent - removed from document)
  10984. if (elm[0] === $rootElement[0] || !(elm = elm.parent())[0]) return;
  10985. }
  10986. var absHref = elm.prop('href');
  10987. // get the actual href attribute - see
  10988. // http://msdn.microsoft.com/en-us/library/ie/dd347148(v=vs.85).aspx
  10989. var relHref = elm.attr('href') || elm.attr('xlink:href');
  10990. if (isObject(absHref) && absHref.toString() === '[object SVGAnimatedString]') {
  10991. // SVGAnimatedString.animVal should be identical to SVGAnimatedString.baseVal, unless during
  10992. // an animation.
  10993. absHref = urlResolve(absHref.animVal).href;
  10994. }
  10995. // Ignore when url is started with javascript: or mailto:
  10996. if (IGNORE_URI_REGEXP.test(absHref)) return;
  10997. if (absHref && !elm.attr('target') && !event.isDefaultPrevented()) {
  10998. if ($location.$$parseLinkUrl(absHref, relHref)) {
  10999. // We do a preventDefault for all urls that are part of the angular application,
  11000. // in html5mode and also without, so that we are able to abort navigation without
  11001. // getting double entries in the location history.
  11002. event.preventDefault();
  11003. // update location manually
  11004. if ($location.absUrl() != $browser.url()) {
  11005. $rootScope.$apply();
  11006. // hack to work around FF6 bug 684208 when scenario runner clicks on links
  11007. $window.angular['ff-684208-preventDefault'] = true;
  11008. }
  11009. }
  11010. }
  11011. });
  11012. // rewrite hashbang url <> html5 url
  11013. if (trimEmptyHash($location.absUrl()) != trimEmptyHash(initialUrl)) {
  11014. $browser.url($location.absUrl(), true);
  11015. }
  11016. var initializing = true;
  11017. // update $location when $browser url changes
  11018. $browser.onUrlChange(function(newUrl, newState) {
  11019. if (isUndefined(beginsWith(appBaseNoFile, newUrl))) {
  11020. // If we are navigating outside of the app then force a reload
  11021. $window.location.href = newUrl;
  11022. return;
  11023. }
  11024. $rootScope.$evalAsync(function() {
  11025. var oldUrl = $location.absUrl();
  11026. var oldState = $location.$$state;
  11027. var defaultPrevented;
  11028. $location.$$parse(newUrl);
  11029. $location.$$state = newState;
  11030. defaultPrevented = $rootScope.$broadcast('$locationChangeStart', newUrl, oldUrl,
  11031. newState, oldState).defaultPrevented;
  11032. // if the location was changed by a `$locationChangeStart` handler then stop
  11033. // processing this location change
  11034. if ($location.absUrl() !== newUrl) return;
  11035. if (defaultPrevented) {
  11036. $location.$$parse(oldUrl);
  11037. $location.$$state = oldState;
  11038. setBrowserUrlWithFallback(oldUrl, false, oldState);
  11039. } else {
  11040. initializing = false;
  11041. afterLocationChange(oldUrl, oldState);
  11042. }
  11043. });
  11044. if (!$rootScope.$$phase) $rootScope.$digest();
  11045. });
  11046. // update browser
  11047. $rootScope.$watch(function $locationWatch() {
  11048. var oldUrl = trimEmptyHash($browser.url());
  11049. var newUrl = trimEmptyHash($location.absUrl());
  11050. var oldState = $browser.state();
  11051. var currentReplace = $location.$$replace;
  11052. var urlOrStateChanged = oldUrl !== newUrl ||
  11053. ($location.$$html5 && $sniffer.history && oldState !== $location.$$state);
  11054. if (initializing || urlOrStateChanged) {
  11055. initializing = false;
  11056. $rootScope.$evalAsync(function() {
  11057. var newUrl = $location.absUrl();
  11058. var defaultPrevented = $rootScope.$broadcast('$locationChangeStart', newUrl, oldUrl,
  11059. $location.$$state, oldState).defaultPrevented;
  11060. // if the location was changed by a `$locationChangeStart` handler then stop
  11061. // processing this location change
  11062. if ($location.absUrl() !== newUrl) return;
  11063. if (defaultPrevented) {
  11064. $location.$$parse(oldUrl);
  11065. $location.$$state = oldState;
  11066. } else {
  11067. if (urlOrStateChanged) {
  11068. setBrowserUrlWithFallback(newUrl, currentReplace,
  11069. oldState === $location.$$state ? null : $location.$$state);
  11070. }
  11071. afterLocationChange(oldUrl, oldState);
  11072. }
  11073. });
  11074. }
  11075. $location.$$replace = false;
  11076. // we don't need to return anything because $evalAsync will make the digest loop dirty when
  11077. // there is a change
  11078. });
  11079. return $location;
  11080. function afterLocationChange(oldUrl, oldState) {
  11081. $rootScope.$broadcast('$locationChangeSuccess', $location.absUrl(), oldUrl,
  11082. $location.$$state, oldState);
  11083. }
  11084. }];
  11085. }
  11086. /**
  11087. * @ngdoc service
  11088. * @name $log
  11089. * @requires $window
  11090. *
  11091. * @description
  11092. * Simple service for logging. Default implementation safely writes the message
  11093. * into the browser's console (if present).
  11094. *
  11095. * The main purpose of this service is to simplify debugging and troubleshooting.
  11096. *
  11097. * The default is to log `debug` messages. You can use
  11098. * {@link ng.$logProvider ng.$logProvider#debugEnabled} to change this.
  11099. *
  11100. * @example
  11101. <example module="logExample">
  11102. <file name="script.js">
  11103. angular.module('logExample', [])
  11104. .controller('LogController', ['$scope', '$log', function($scope, $log) {
  11105. $scope.$log = $log;
  11106. $scope.message = 'Hello World!';
  11107. }]);
  11108. </file>
  11109. <file name="index.html">
  11110. <div ng-controller="LogController">
  11111. <p>Reload this page with open console, enter text and hit the log button...</p>
  11112. <label>Message:
  11113. <input type="text" ng-model="message" /></label>
  11114. <button ng-click="$log.log(message)">log</button>
  11115. <button ng-click="$log.warn(message)">warn</button>
  11116. <button ng-click="$log.info(message)">info</button>
  11117. <button ng-click="$log.error(message)">error</button>
  11118. <button ng-click="$log.debug(message)">debug</button>
  11119. </div>
  11120. </file>
  11121. </example>
  11122. */
  11123. /**
  11124. * @ngdoc provider
  11125. * @name $logProvider
  11126. * @description
  11127. * Use the `$logProvider` to configure how the application logs messages
  11128. */
  11129. function $LogProvider() {
  11130. var debug = true,
  11131. self = this;
  11132. /**
  11133. * @ngdoc method
  11134. * @name $logProvider#debugEnabled
  11135. * @description
  11136. * @param {boolean=} flag enable or disable debug level messages
  11137. * @returns {*} current value if used as getter or itself (chaining) if used as setter
  11138. */
  11139. this.debugEnabled = function(flag) {
  11140. if (isDefined(flag)) {
  11141. debug = flag;
  11142. return this;
  11143. } else {
  11144. return debug;
  11145. }
  11146. };
  11147. this.$get = ['$window', function($window) {
  11148. return {
  11149. /**
  11150. * @ngdoc method
  11151. * @name $log#log
  11152. *
  11153. * @description
  11154. * Write a log message
  11155. */
  11156. log: consoleLog('log'),
  11157. /**
  11158. * @ngdoc method
  11159. * @name $log#info
  11160. *
  11161. * @description
  11162. * Write an information message
  11163. */
  11164. info: consoleLog('info'),
  11165. /**
  11166. * @ngdoc method
  11167. * @name $log#warn
  11168. *
  11169. * @description
  11170. * Write a warning message
  11171. */
  11172. warn: consoleLog('warn'),
  11173. /**
  11174. * @ngdoc method
  11175. * @name $log#error
  11176. *
  11177. * @description
  11178. * Write an error message
  11179. */
  11180. error: consoleLog('error'),
  11181. /**
  11182. * @ngdoc method
  11183. * @name $log#debug
  11184. *
  11185. * @description
  11186. * Write a debug message
  11187. */
  11188. debug: (function() {
  11189. var fn = consoleLog('debug');
  11190. return function() {
  11191. if (debug) {
  11192. fn.apply(self, arguments);
  11193. }
  11194. };
  11195. }())
  11196. };
  11197. function formatError(arg) {
  11198. if (arg instanceof Error) {
  11199. if (arg.stack) {
  11200. arg = (arg.message && arg.stack.indexOf(arg.message) === -1)
  11201. ? 'Error: ' + arg.message + '\n' + arg.stack
  11202. : arg.stack;
  11203. } else if (arg.sourceURL) {
  11204. arg = arg.message + '\n' + arg.sourceURL + ':' + arg.line;
  11205. }
  11206. }
  11207. return arg;
  11208. }
  11209. function consoleLog(type) {
  11210. var console = $window.console || {},
  11211. logFn = console[type] || console.log || noop,
  11212. hasApply = false;
  11213. // Note: reading logFn.apply throws an error in IE11 in IE8 document mode.
  11214. // The reason behind this is that console.log has type "object" in IE8...
  11215. try {
  11216. hasApply = !!logFn.apply;
  11217. } catch (e) {}
  11218. if (hasApply) {
  11219. return function() {
  11220. var args = [];
  11221. forEach(arguments, function(arg) {
  11222. args.push(formatError(arg));
  11223. });
  11224. return logFn.apply(console, args);
  11225. };
  11226. }
  11227. // we are IE which either doesn't have window.console => this is noop and we do nothing,
  11228. // or we are IE where console.log doesn't have apply so we log at least first 2 args
  11229. return function(arg1, arg2) {
  11230. logFn(arg1, arg2 == null ? '' : arg2);
  11231. };
  11232. }
  11233. }];
  11234. }
  11235. /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
  11236. * Any commits to this file should be reviewed with security in mind. *
  11237. * Changes to this file can potentially create security vulnerabilities. *
  11238. * An approval from 2 Core members with history of modifying *
  11239. * this file is required. *
  11240. * *
  11241. * Does the change somehow allow for arbitrary javascript to be executed? *
  11242. * Or allows for someone to change the prototype of built-in objects? *
  11243. * Or gives undesired access to variables likes document or window? *
  11244. * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
  11245. var $parseMinErr = minErr('$parse');
  11246. // Sandboxing Angular Expressions
  11247. // ------------------------------
  11248. // Angular expressions are generally considered safe because these expressions only have direct
  11249. // access to `$scope` and locals. However, one can obtain the ability to execute arbitrary JS code by
  11250. // obtaining a reference to native JS functions such as the Function constructor.
  11251. //
  11252. // As an example, consider the following Angular expression:
  11253. //
  11254. // {}.toString.constructor('alert("evil JS code")')
  11255. //
  11256. // This sandboxing technique is not perfect and doesn't aim to be. The goal is to prevent exploits
  11257. // against the expression language, but not to prevent exploits that were enabled by exposing
  11258. // sensitive JavaScript or browser APIs on Scope. Exposing such objects on a Scope is never a good
  11259. // practice and therefore we are not even trying to protect against interaction with an object
  11260. // explicitly exposed in this way.
  11261. //
  11262. // In general, it is not possible to access a Window object from an angular expression unless a
  11263. // window or some DOM object that has a reference to window is published onto a Scope.
  11264. // Similarly we prevent invocations of function known to be dangerous, as well as assignments to
  11265. // native objects.
  11266. //
  11267. // See https://docs.angularjs.org/guide/security
  11268. function ensureSafeMemberName(name, fullExpression) {
  11269. // From the JavaScript docs:
  11270. // Property names must be strings. This means that non-string objects cannot be used
  11271. // as keys in an object. Any non-string object, including a number, is typecasted
  11272. // into a string via the toString method.
  11273. //
  11274. // So, to ensure that we are checking the same `name` that JavaScript would use,
  11275. // we cast it to a string, if possible
  11276. name = (isObject(name) && name.toString) ? name.toString() : name;
  11277. if (name === "__defineGetter__" || name === "__defineSetter__"
  11278. || name === "__lookupGetter__" || name === "__lookupSetter__"
  11279. || name === "__proto__") {
  11280. throw $parseMinErr('isecfld',
  11281. 'Attempting to access a disallowed field in Angular expressions! '
  11282. + 'Expression: {0}', fullExpression);
  11283. }
  11284. return name;
  11285. }
  11286. function ensureSafeObject(obj, fullExpression) {
  11287. // nifty check if obj is Function that is fast and works across iframes and other contexts
  11288. if (obj) {
  11289. if (obj.constructor === obj) {
  11290. throw $parseMinErr('isecfn',
  11291. 'Referencing Function in Angular expressions is disallowed! Expression: {0}',
  11292. fullExpression);
  11293. } else if (// isWindow(obj)
  11294. obj.window === obj) {
  11295. throw $parseMinErr('isecwindow',
  11296. 'Referencing the Window in Angular expressions is disallowed! Expression: {0}',
  11297. fullExpression);
  11298. } else if (// isElement(obj)
  11299. obj.children && (obj.nodeName || (obj.prop && obj.attr && obj.find))) {
  11300. throw $parseMinErr('isecdom',
  11301. 'Referencing DOM nodes in Angular expressions is disallowed! Expression: {0}',
  11302. fullExpression);
  11303. } else if (// block Object so that we can't get hold of dangerous Object.* methods
  11304. obj === Object) {
  11305. throw $parseMinErr('isecobj',
  11306. 'Referencing Object in Angular expressions is disallowed! Expression: {0}',
  11307. fullExpression);
  11308. }
  11309. }
  11310. return obj;
  11311. }
  11312. var CALL = Function.prototype.call;
  11313. var APPLY = Function.prototype.apply;
  11314. var BIND = Function.prototype.bind;
  11315. function ensureSafeFunction(obj, fullExpression) {
  11316. if (obj) {
  11317. if (obj.constructor === obj) {
  11318. throw $parseMinErr('isecfn',
  11319. 'Referencing Function in Angular expressions is disallowed! Expression: {0}',
  11320. fullExpression);
  11321. } else if (obj === CALL || obj === APPLY || obj === BIND) {
  11322. throw $parseMinErr('isecff',
  11323. 'Referencing call, apply or bind in Angular expressions is disallowed! Expression: {0}',
  11324. fullExpression);
  11325. }
  11326. }
  11327. }
  11328. var OPERATORS = createMap();
  11329. forEach('+ - * / % === !== == != < > <= >= && || ! = |'.split(' '), function(operator) { OPERATORS[operator] = true; });
  11330. var ESCAPE = {"n":"\n", "f":"\f", "r":"\r", "t":"\t", "v":"\v", "'":"'", '"':'"'};
  11331. /////////////////////////////////////////
  11332. /**
  11333. * @constructor
  11334. */
  11335. var Lexer = function(options) {
  11336. this.options = options;
  11337. };
  11338. Lexer.prototype = {
  11339. constructor: Lexer,
  11340. lex: function(text) {
  11341. this.text = text;
  11342. this.index = 0;
  11343. this.tokens = [];
  11344. while (this.index < this.text.length) {
  11345. var ch = this.text.charAt(this.index);
  11346. if (ch === '"' || ch === "'") {
  11347. this.readString(ch);
  11348. } else if (this.isNumber(ch) || ch === '.' && this.isNumber(this.peek())) {
  11349. this.readNumber();
  11350. } else if (this.isIdent(ch)) {
  11351. this.readIdent();
  11352. } else if (this.is(ch, '(){}[].,;:?')) {
  11353. this.tokens.push({index: this.index, text: ch});
  11354. this.index++;
  11355. } else if (this.isWhitespace(ch)) {
  11356. this.index++;
  11357. } else {
  11358. var ch2 = ch + this.peek();
  11359. var ch3 = ch2 + this.peek(2);
  11360. var op1 = OPERATORS[ch];
  11361. var op2 = OPERATORS[ch2];
  11362. var op3 = OPERATORS[ch3];
  11363. if (op1 || op2 || op3) {
  11364. var token = op3 ? ch3 : (op2 ? ch2 : ch);
  11365. this.tokens.push({index: this.index, text: token, operator: true});
  11366. this.index += token.length;
  11367. } else {
  11368. this.throwError('Unexpected next character ', this.index, this.index + 1);
  11369. }
  11370. }
  11371. }
  11372. return this.tokens;
  11373. },
  11374. is: function(ch, chars) {
  11375. return chars.indexOf(ch) !== -1;
  11376. },
  11377. peek: function(i) {
  11378. var num = i || 1;
  11379. return (this.index + num < this.text.length) ? this.text.charAt(this.index + num) : false;
  11380. },
  11381. isNumber: function(ch) {
  11382. return ('0' <= ch && ch <= '9') && typeof ch === "string";
  11383. },
  11384. isWhitespace: function(ch) {
  11385. // IE treats non-breaking space as \u00A0
  11386. return (ch === ' ' || ch === '\r' || ch === '\t' ||
  11387. ch === '\n' || ch === '\v' || ch === '\u00A0');
  11388. },
  11389. isIdent: function(ch) {
  11390. return ('a' <= ch && ch <= 'z' ||
  11391. 'A' <= ch && ch <= 'Z' ||
  11392. '_' === ch || ch === '$');
  11393. },
  11394. isExpOperator: function(ch) {
  11395. return (ch === '-' || ch === '+' || this.isNumber(ch));
  11396. },
  11397. throwError: function(error, start, end) {
  11398. end = end || this.index;
  11399. var colStr = (isDefined(start)
  11400. ? 's ' + start + '-' + this.index + ' [' + this.text.substring(start, end) + ']'
  11401. : ' ' + end);
  11402. throw $parseMinErr('lexerr', 'Lexer Error: {0} at column{1} in expression [{2}].',
  11403. error, colStr, this.text);
  11404. },
  11405. readNumber: function() {
  11406. var number = '';
  11407. var start = this.index;
  11408. while (this.index < this.text.length) {
  11409. var ch = lowercase(this.text.charAt(this.index));
  11410. if (ch == '.' || this.isNumber(ch)) {
  11411. number += ch;
  11412. } else {
  11413. var peekCh = this.peek();
  11414. if (ch == 'e' && this.isExpOperator(peekCh)) {
  11415. number += ch;
  11416. } else if (this.isExpOperator(ch) &&
  11417. peekCh && this.isNumber(peekCh) &&
  11418. number.charAt(number.length - 1) == 'e') {
  11419. number += ch;
  11420. } else if (this.isExpOperator(ch) &&
  11421. (!peekCh || !this.isNumber(peekCh)) &&
  11422. number.charAt(number.length - 1) == 'e') {
  11423. this.throwError('Invalid exponent');
  11424. } else {
  11425. break;
  11426. }
  11427. }
  11428. this.index++;
  11429. }
  11430. this.tokens.push({
  11431. index: start,
  11432. text: number,
  11433. constant: true,
  11434. value: Number(number)
  11435. });
  11436. },
  11437. readIdent: function() {
  11438. var start = this.index;
  11439. while (this.index < this.text.length) {
  11440. var ch = this.text.charAt(this.index);
  11441. if (!(this.isIdent(ch) || this.isNumber(ch))) {
  11442. break;
  11443. }
  11444. this.index++;
  11445. }
  11446. this.tokens.push({
  11447. index: start,
  11448. text: this.text.slice(start, this.index),
  11449. identifier: true
  11450. });
  11451. },
  11452. readString: function(quote) {
  11453. var start = this.index;
  11454. this.index++;
  11455. var string = '';
  11456. var rawString = quote;
  11457. var escape = false;
  11458. while (this.index < this.text.length) {
  11459. var ch = this.text.charAt(this.index);
  11460. rawString += ch;
  11461. if (escape) {
  11462. if (ch === 'u') {
  11463. var hex = this.text.substring(this.index + 1, this.index + 5);
  11464. if (!hex.match(/[\da-f]{4}/i)) {
  11465. this.throwError('Invalid unicode escape [\\u' + hex + ']');
  11466. }
  11467. this.index += 4;
  11468. string += String.fromCharCode(parseInt(hex, 16));
  11469. } else {
  11470. var rep = ESCAPE[ch];
  11471. string = string + (rep || ch);
  11472. }
  11473. escape = false;
  11474. } else if (ch === '\\') {
  11475. escape = true;
  11476. } else if (ch === quote) {
  11477. this.index++;
  11478. this.tokens.push({
  11479. index: start,
  11480. text: rawString,
  11481. constant: true,
  11482. value: string
  11483. });
  11484. return;
  11485. } else {
  11486. string += ch;
  11487. }
  11488. this.index++;
  11489. }
  11490. this.throwError('Unterminated quote', start);
  11491. }
  11492. };
  11493. var AST = function(lexer, options) {
  11494. this.lexer = lexer;
  11495. this.options = options;
  11496. };
  11497. AST.Program = 'Program';
  11498. AST.ExpressionStatement = 'ExpressionStatement';
  11499. AST.AssignmentExpression = 'AssignmentExpression';
  11500. AST.ConditionalExpression = 'ConditionalExpression';
  11501. AST.LogicalExpression = 'LogicalExpression';
  11502. AST.BinaryExpression = 'BinaryExpression';
  11503. AST.UnaryExpression = 'UnaryExpression';
  11504. AST.CallExpression = 'CallExpression';
  11505. AST.MemberExpression = 'MemberExpression';
  11506. AST.Identifier = 'Identifier';
  11507. AST.Literal = 'Literal';
  11508. AST.ArrayExpression = 'ArrayExpression';
  11509. AST.Property = 'Property';
  11510. AST.ObjectExpression = 'ObjectExpression';
  11511. AST.ThisExpression = 'ThisExpression';
  11512. // Internal use only
  11513. AST.NGValueParameter = 'NGValueParameter';
  11514. AST.prototype = {
  11515. ast: function(text) {
  11516. this.text = text;
  11517. this.tokens = this.lexer.lex(text);
  11518. var value = this.program();
  11519. if (this.tokens.length !== 0) {
  11520. this.throwError('is an unexpected token', this.tokens[0]);
  11521. }
  11522. return value;
  11523. },
  11524. program: function() {
  11525. var body = [];
  11526. while (true) {
  11527. if (this.tokens.length > 0 && !this.peek('}', ')', ';', ']'))
  11528. body.push(this.expressionStatement());
  11529. if (!this.expect(';')) {
  11530. return { type: AST.Program, body: body};
  11531. }
  11532. }
  11533. },
  11534. expressionStatement: function() {
  11535. return { type: AST.ExpressionStatement, expression: this.filterChain() };
  11536. },
  11537. filterChain: function() {
  11538. var left = this.expression();
  11539. var token;
  11540. while ((token = this.expect('|'))) {
  11541. left = this.filter(left);
  11542. }
  11543. return left;
  11544. },
  11545. expression: function() {
  11546. return this.assignment();
  11547. },
  11548. assignment: function() {
  11549. var result = this.ternary();
  11550. if (this.expect('=')) {
  11551. result = { type: AST.AssignmentExpression, left: result, right: this.assignment(), operator: '='};
  11552. }
  11553. return result;
  11554. },
  11555. ternary: function() {
  11556. var test = this.logicalOR();
  11557. var alternate;
  11558. var consequent;
  11559. if (this.expect('?')) {
  11560. alternate = this.expression();
  11561. if (this.consume(':')) {
  11562. consequent = this.expression();
  11563. return { type: AST.ConditionalExpression, test: test, alternate: alternate, consequent: consequent};
  11564. }
  11565. }
  11566. return test;
  11567. },
  11568. logicalOR: function() {
  11569. var left = this.logicalAND();
  11570. while (this.expect('||')) {
  11571. left = { type: AST.LogicalExpression, operator: '||', left: left, right: this.logicalAND() };
  11572. }
  11573. return left;
  11574. },
  11575. logicalAND: function() {
  11576. var left = this.equality();
  11577. while (this.expect('&&')) {
  11578. left = { type: AST.LogicalExpression, operator: '&&', left: left, right: this.equality()};
  11579. }
  11580. return left;
  11581. },
  11582. equality: function() {
  11583. var left = this.relational();
  11584. var token;
  11585. while ((token = this.expect('==','!=','===','!=='))) {
  11586. left = { type: AST.BinaryExpression, operator: token.text, left: left, right: this.relational() };
  11587. }
  11588. return left;
  11589. },
  11590. relational: function() {
  11591. var left = this.additive();
  11592. var token;
  11593. while ((token = this.expect('<', '>', '<=', '>='))) {
  11594. left = { type: AST.BinaryExpression, operator: token.text, left: left, right: this.additive() };
  11595. }
  11596. return left;
  11597. },
  11598. additive: function() {
  11599. var left = this.multiplicative();
  11600. var token;
  11601. while ((token = this.expect('+','-'))) {
  11602. left = { type: AST.BinaryExpression, operator: token.text, left: left, right: this.multiplicative() };
  11603. }
  11604. return left;
  11605. },
  11606. multiplicative: function() {
  11607. var left = this.unary();
  11608. var token;
  11609. while ((token = this.expect('*','/','%'))) {
  11610. left = { type: AST.BinaryExpression, operator: token.text, left: left, right: this.unary() };
  11611. }
  11612. return left;
  11613. },
  11614. unary: function() {
  11615. var token;
  11616. if ((token = this.expect('+', '-', '!'))) {
  11617. return { type: AST.UnaryExpression, operator: token.text, prefix: true, argument: this.unary() };
  11618. } else {
  11619. return this.primary();
  11620. }
  11621. },
  11622. primary: function() {
  11623. var primary;
  11624. if (this.expect('(')) {
  11625. primary = this.filterChain();
  11626. this.consume(')');
  11627. } else if (this.expect('[')) {
  11628. primary = this.arrayDeclaration();
  11629. } else if (this.expect('{')) {
  11630. primary = this.object();
  11631. } else if (this.constants.hasOwnProperty(this.peek().text)) {
  11632. primary = copy(this.constants[this.consume().text]);
  11633. } else if (this.peek().identifier) {
  11634. primary = this.identifier();
  11635. } else if (this.peek().constant) {
  11636. primary = this.constant();
  11637. } else {
  11638. this.throwError('not a primary expression', this.peek());
  11639. }
  11640. var next;
  11641. while ((next = this.expect('(', '[', '.'))) {
  11642. if (next.text === '(') {
  11643. primary = {type: AST.CallExpression, callee: primary, arguments: this.parseArguments() };
  11644. this.consume(')');
  11645. } else if (next.text === '[') {
  11646. primary = { type: AST.MemberExpression, object: primary, property: this.expression(), computed: true };
  11647. this.consume(']');
  11648. } else if (next.text === '.') {
  11649. primary = { type: AST.MemberExpression, object: primary, property: this.identifier(), computed: false };
  11650. } else {
  11651. this.throwError('IMPOSSIBLE');
  11652. }
  11653. }
  11654. return primary;
  11655. },
  11656. filter: function(baseExpression) {
  11657. var args = [baseExpression];
  11658. var result = {type: AST.CallExpression, callee: this.identifier(), arguments: args, filter: true};
  11659. while (this.expect(':')) {
  11660. args.push(this.expression());
  11661. }
  11662. return result;
  11663. },
  11664. parseArguments: function() {
  11665. var args = [];
  11666. if (this.peekToken().text !== ')') {
  11667. do {
  11668. args.push(this.expression());
  11669. } while (this.expect(','));
  11670. }
  11671. return args;
  11672. },
  11673. identifier: function() {
  11674. var token = this.consume();
  11675. if (!token.identifier) {
  11676. this.throwError('is not a valid identifier', token);
  11677. }
  11678. return { type: AST.Identifier, name: token.text };
  11679. },
  11680. constant: function() {
  11681. // TODO check that it is a constant
  11682. return { type: AST.Literal, value: this.consume().value };
  11683. },
  11684. arrayDeclaration: function() {
  11685. var elements = [];
  11686. if (this.peekToken().text !== ']') {
  11687. do {
  11688. if (this.peek(']')) {
  11689. // Support trailing commas per ES5.1.
  11690. break;
  11691. }
  11692. elements.push(this.expression());
  11693. } while (this.expect(','));
  11694. }
  11695. this.consume(']');
  11696. return { type: AST.ArrayExpression, elements: elements };
  11697. },
  11698. object: function() {
  11699. var properties = [], property;
  11700. if (this.peekToken().text !== '}') {
  11701. do {
  11702. if (this.peek('}')) {
  11703. // Support trailing commas per ES5.1.
  11704. break;
  11705. }
  11706. property = {type: AST.Property, kind: 'init'};
  11707. if (this.peek().constant) {
  11708. property.key = this.constant();
  11709. } else if (this.peek().identifier) {
  11710. property.key = this.identifier();
  11711. } else {
  11712. this.throwError("invalid key", this.peek());
  11713. }
  11714. this.consume(':');
  11715. property.value = this.expression();
  11716. properties.push(property);
  11717. } while (this.expect(','));
  11718. }
  11719. this.consume('}');
  11720. return {type: AST.ObjectExpression, properties: properties };
  11721. },
  11722. throwError: function(msg, token) {
  11723. throw $parseMinErr('syntax',
  11724. 'Syntax Error: Token \'{0}\' {1} at column {2} of the expression [{3}] starting at [{4}].',
  11725. token.text, msg, (token.index + 1), this.text, this.text.substring(token.index));
  11726. },
  11727. consume: function(e1) {
  11728. if (this.tokens.length === 0) {
  11729. throw $parseMinErr('ueoe', 'Unexpected end of expression: {0}', this.text);
  11730. }
  11731. var token = this.expect(e1);
  11732. if (!token) {
  11733. this.throwError('is unexpected, expecting [' + e1 + ']', this.peek());
  11734. }
  11735. return token;
  11736. },
  11737. peekToken: function() {
  11738. if (this.tokens.length === 0) {
  11739. throw $parseMinErr('ueoe', 'Unexpected end of expression: {0}', this.text);
  11740. }
  11741. return this.tokens[0];
  11742. },
  11743. peek: function(e1, e2, e3, e4) {
  11744. return this.peekAhead(0, e1, e2, e3, e4);
  11745. },
  11746. peekAhead: function(i, e1, e2, e3, e4) {
  11747. if (this.tokens.length > i) {
  11748. var token = this.tokens[i];
  11749. var t = token.text;
  11750. if (t === e1 || t === e2 || t === e3 || t === e4 ||
  11751. (!e1 && !e2 && !e3 && !e4)) {
  11752. return token;
  11753. }
  11754. }
  11755. return false;
  11756. },
  11757. expect: function(e1, e2, e3, e4) {
  11758. var token = this.peek(e1, e2, e3, e4);
  11759. if (token) {
  11760. this.tokens.shift();
  11761. return token;
  11762. }
  11763. return false;
  11764. },
  11765. /* `undefined` is not a constant, it is an identifier,
  11766. * but using it as an identifier is not supported
  11767. */
  11768. constants: {
  11769. 'true': { type: AST.Literal, value: true },
  11770. 'false': { type: AST.Literal, value: false },
  11771. 'null': { type: AST.Literal, value: null },
  11772. 'undefined': {type: AST.Literal, value: undefined },
  11773. 'this': {type: AST.ThisExpression }
  11774. }
  11775. };
  11776. function ifDefined(v, d) {
  11777. return typeof v !== 'undefined' ? v : d;
  11778. }
  11779. function plusFn(l, r) {
  11780. if (typeof l === 'undefined') return r;
  11781. if (typeof r === 'undefined') return l;
  11782. return l + r;
  11783. }
  11784. function isStateless($filter, filterName) {
  11785. var fn = $filter(filterName);
  11786. return !fn.$stateful;
  11787. }
  11788. function findConstantAndWatchExpressions(ast, $filter) {
  11789. var allConstants;
  11790. var argsToWatch;
  11791. switch (ast.type) {
  11792. case AST.Program:
  11793. allConstants = true;
  11794. forEach(ast.body, function(expr) {
  11795. findConstantAndWatchExpressions(expr.expression, $filter);
  11796. allConstants = allConstants && expr.expression.constant;
  11797. });
  11798. ast.constant = allConstants;
  11799. break;
  11800. case AST.Literal:
  11801. ast.constant = true;
  11802. ast.toWatch = [];
  11803. break;
  11804. case AST.UnaryExpression:
  11805. findConstantAndWatchExpressions(ast.argument, $filter);
  11806. ast.constant = ast.argument.constant;
  11807. ast.toWatch = ast.argument.toWatch;
  11808. break;
  11809. case AST.BinaryExpression:
  11810. findConstantAndWatchExpressions(ast.left, $filter);
  11811. findConstantAndWatchExpressions(ast.right, $filter);
  11812. ast.constant = ast.left.constant && ast.right.constant;
  11813. ast.toWatch = ast.left.toWatch.concat(ast.right.toWatch);
  11814. break;
  11815. case AST.LogicalExpression:
  11816. findConstantAndWatchExpressions(ast.left, $filter);
  11817. findConstantAndWatchExpressions(ast.right, $filter);
  11818. ast.constant = ast.left.constant && ast.right.constant;
  11819. ast.toWatch = ast.constant ? [] : [ast];
  11820. break;
  11821. case AST.ConditionalExpression:
  11822. findConstantAndWatchExpressions(ast.test, $filter);
  11823. findConstantAndWatchExpressions(ast.alternate, $filter);
  11824. findConstantAndWatchExpressions(ast.consequent, $filter);
  11825. ast.constant = ast.test.constant && ast.alternate.constant && ast.consequent.constant;
  11826. ast.toWatch = ast.constant ? [] : [ast];
  11827. break;
  11828. case AST.Identifier:
  11829. ast.constant = false;
  11830. ast.toWatch = [ast];
  11831. break;
  11832. case AST.MemberExpression:
  11833. findConstantAndWatchExpressions(ast.object, $filter);
  11834. if (ast.computed) {
  11835. findConstantAndWatchExpressions(ast.property, $filter);
  11836. }
  11837. ast.constant = ast.object.constant && (!ast.computed || ast.property.constant);
  11838. ast.toWatch = [ast];
  11839. break;
  11840. case AST.CallExpression:
  11841. allConstants = ast.filter ? isStateless($filter, ast.callee.name) : false;
  11842. argsToWatch = [];
  11843. forEach(ast.arguments, function(expr) {
  11844. findConstantAndWatchExpressions(expr, $filter);
  11845. allConstants = allConstants && expr.constant;
  11846. if (!expr.constant) {
  11847. argsToWatch.push.apply(argsToWatch, expr.toWatch);
  11848. }
  11849. });
  11850. ast.constant = allConstants;
  11851. ast.toWatch = ast.filter && isStateless($filter, ast.callee.name) ? argsToWatch : [ast];
  11852. break;
  11853. case AST.AssignmentExpression:
  11854. findConstantAndWatchExpressions(ast.left, $filter);
  11855. findConstantAndWatchExpressions(ast.right, $filter);
  11856. ast.constant = ast.left.constant && ast.right.constant;
  11857. ast.toWatch = [ast];
  11858. break;
  11859. case AST.ArrayExpression:
  11860. allConstants = true;
  11861. argsToWatch = [];
  11862. forEach(ast.elements, function(expr) {
  11863. findConstantAndWatchExpressions(expr, $filter);
  11864. allConstants = allConstants && expr.constant;
  11865. if (!expr.constant) {
  11866. argsToWatch.push.apply(argsToWatch, expr.toWatch);
  11867. }
  11868. });
  11869. ast.constant = allConstants;
  11870. ast.toWatch = argsToWatch;
  11871. break;
  11872. case AST.ObjectExpression:
  11873. allConstants = true;
  11874. argsToWatch = [];
  11875. forEach(ast.properties, function(property) {
  11876. findConstantAndWatchExpressions(property.value, $filter);
  11877. allConstants = allConstants && property.value.constant;
  11878. if (!property.value.constant) {
  11879. argsToWatch.push.apply(argsToWatch, property.value.toWatch);
  11880. }
  11881. });
  11882. ast.constant = allConstants;
  11883. ast.toWatch = argsToWatch;
  11884. break;
  11885. case AST.ThisExpression:
  11886. ast.constant = false;
  11887. ast.toWatch = [];
  11888. break;
  11889. }
  11890. }
  11891. function getInputs(body) {
  11892. if (body.length != 1) return;
  11893. var lastExpression = body[0].expression;
  11894. var candidate = lastExpression.toWatch;
  11895. if (candidate.length !== 1) return candidate;
  11896. return candidate[0] !== lastExpression ? candidate : undefined;
  11897. }
  11898. function isAssignable(ast) {
  11899. return ast.type === AST.Identifier || ast.type === AST.MemberExpression;
  11900. }
  11901. function assignableAST(ast) {
  11902. if (ast.body.length === 1 && isAssignable(ast.body[0].expression)) {
  11903. return {type: AST.AssignmentExpression, left: ast.body[0].expression, right: {type: AST.NGValueParameter}, operator: '='};
  11904. }
  11905. }
  11906. function isLiteral(ast) {
  11907. return ast.body.length === 0 ||
  11908. ast.body.length === 1 && (
  11909. ast.body[0].expression.type === AST.Literal ||
  11910. ast.body[0].expression.type === AST.ArrayExpression ||
  11911. ast.body[0].expression.type === AST.ObjectExpression);
  11912. }
  11913. function isConstant(ast) {
  11914. return ast.constant;
  11915. }
  11916. function ASTCompiler(astBuilder, $filter) {
  11917. this.astBuilder = astBuilder;
  11918. this.$filter = $filter;
  11919. }
  11920. ASTCompiler.prototype = {
  11921. compile: function(expression, expensiveChecks) {
  11922. var self = this;
  11923. var ast = this.astBuilder.ast(expression);
  11924. this.state = {
  11925. nextId: 0,
  11926. filters: {},
  11927. expensiveChecks: expensiveChecks,
  11928. fn: {vars: [], body: [], own: {}},
  11929. assign: {vars: [], body: [], own: {}},
  11930. inputs: []
  11931. };
  11932. findConstantAndWatchExpressions(ast, self.$filter);
  11933. var extra = '';
  11934. var assignable;
  11935. this.stage = 'assign';
  11936. if ((assignable = assignableAST(ast))) {
  11937. this.state.computing = 'assign';
  11938. var result = this.nextId();
  11939. this.recurse(assignable, result);
  11940. this.return_(result);
  11941. extra = 'fn.assign=' + this.generateFunction('assign', 's,v,l');
  11942. }
  11943. var toWatch = getInputs(ast.body);
  11944. self.stage = 'inputs';
  11945. forEach(toWatch, function(watch, key) {
  11946. var fnKey = 'fn' + key;
  11947. self.state[fnKey] = {vars: [], body: [], own: {}};
  11948. self.state.computing = fnKey;
  11949. var intoId = self.nextId();
  11950. self.recurse(watch, intoId);
  11951. self.return_(intoId);
  11952. self.state.inputs.push(fnKey);
  11953. watch.watchId = key;
  11954. });
  11955. this.state.computing = 'fn';
  11956. this.stage = 'main';
  11957. this.recurse(ast);
  11958. var fnString =
  11959. // The build and minification steps remove the string "use strict" from the code, but this is done using a regex.
  11960. // This is a workaround for this until we do a better job at only removing the prefix only when we should.
  11961. '"' + this.USE + ' ' + this.STRICT + '";\n' +
  11962. this.filterPrefix() +
  11963. 'var fn=' + this.generateFunction('fn', 's,l,a,i') +
  11964. extra +
  11965. this.watchFns() +
  11966. 'return fn;';
  11967. /* jshint -W054 */
  11968. var fn = (new Function('$filter',
  11969. 'ensureSafeMemberName',
  11970. 'ensureSafeObject',
  11971. 'ensureSafeFunction',
  11972. 'ifDefined',
  11973. 'plus',
  11974. 'text',
  11975. fnString))(
  11976. this.$filter,
  11977. ensureSafeMemberName,
  11978. ensureSafeObject,
  11979. ensureSafeFunction,
  11980. ifDefined,
  11981. plusFn,
  11982. expression);
  11983. /* jshint +W054 */
  11984. this.state = this.stage = undefined;
  11985. fn.literal = isLiteral(ast);
  11986. fn.constant = isConstant(ast);
  11987. return fn;
  11988. },
  11989. USE: 'use',
  11990. STRICT: 'strict',
  11991. watchFns: function() {
  11992. var result = [];
  11993. var fns = this.state.inputs;
  11994. var self = this;
  11995. forEach(fns, function(name) {
  11996. result.push('var ' + name + '=' + self.generateFunction(name, 's'));
  11997. });
  11998. if (fns.length) {
  11999. result.push('fn.inputs=[' + fns.join(',') + '];');
  12000. }
  12001. return result.join('');
  12002. },
  12003. generateFunction: function(name, params) {
  12004. return 'function(' + params + '){' +
  12005. this.varsPrefix(name) +
  12006. this.body(name) +
  12007. '};';
  12008. },
  12009. filterPrefix: function() {
  12010. var parts = [];
  12011. var self = this;
  12012. forEach(this.state.filters, function(id, filter) {
  12013. parts.push(id + '=$filter(' + self.escape(filter) + ')');
  12014. });
  12015. if (parts.length) return 'var ' + parts.join(',') + ';';
  12016. return '';
  12017. },
  12018. varsPrefix: function(section) {
  12019. return this.state[section].vars.length ? 'var ' + this.state[section].vars.join(',') + ';' : '';
  12020. },
  12021. body: function(section) {
  12022. return this.state[section].body.join('');
  12023. },
  12024. recurse: function(ast, intoId, nameId, recursionFn, create, skipWatchIdCheck) {
  12025. var left, right, self = this, args, expression;
  12026. recursionFn = recursionFn || noop;
  12027. if (!skipWatchIdCheck && isDefined(ast.watchId)) {
  12028. intoId = intoId || this.nextId();
  12029. this.if_('i',
  12030. this.lazyAssign(intoId, this.computedMember('i', ast.watchId)),
  12031. this.lazyRecurse(ast, intoId, nameId, recursionFn, create, true)
  12032. );
  12033. return;
  12034. }
  12035. switch (ast.type) {
  12036. case AST.Program:
  12037. forEach(ast.body, function(expression, pos) {
  12038. self.recurse(expression.expression, undefined, undefined, function(expr) { right = expr; });
  12039. if (pos !== ast.body.length - 1) {
  12040. self.current().body.push(right, ';');
  12041. } else {
  12042. self.return_(right);
  12043. }
  12044. });
  12045. break;
  12046. case AST.Literal:
  12047. expression = this.escape(ast.value);
  12048. this.assign(intoId, expression);
  12049. recursionFn(expression);
  12050. break;
  12051. case AST.UnaryExpression:
  12052. this.recurse(ast.argument, undefined, undefined, function(expr) { right = expr; });
  12053. expression = ast.operator + '(' + this.ifDefined(right, 0) + ')';
  12054. this.assign(intoId, expression);
  12055. recursionFn(expression);
  12056. break;
  12057. case AST.BinaryExpression:
  12058. this.recurse(ast.left, undefined, undefined, function(expr) { left = expr; });
  12059. this.recurse(ast.right, undefined, undefined, function(expr) { right = expr; });
  12060. if (ast.operator === '+') {
  12061. expression = this.plus(left, right);
  12062. } else if (ast.operator === '-') {
  12063. expression = this.ifDefined(left, 0) + ast.operator + this.ifDefined(right, 0);
  12064. } else {
  12065. expression = '(' + left + ')' + ast.operator + '(' + right + ')';
  12066. }
  12067. this.assign(intoId, expression);
  12068. recursionFn(expression);
  12069. break;
  12070. case AST.LogicalExpression:
  12071. intoId = intoId || this.nextId();
  12072. self.recurse(ast.left, intoId);
  12073. self.if_(ast.operator === '&&' ? intoId : self.not(intoId), self.lazyRecurse(ast.right, intoId));
  12074. recursionFn(intoId);
  12075. break;
  12076. case AST.ConditionalExpression:
  12077. intoId = intoId || this.nextId();
  12078. self.recurse(ast.test, intoId);
  12079. self.if_(intoId, self.lazyRecurse(ast.alternate, intoId), self.lazyRecurse(ast.consequent, intoId));
  12080. recursionFn(intoId);
  12081. break;
  12082. case AST.Identifier:
  12083. intoId = intoId || this.nextId();
  12084. if (nameId) {
  12085. nameId.context = self.stage === 'inputs' ? 's' : this.assign(this.nextId(), this.getHasOwnProperty('l', ast.name) + '?l:s');
  12086. nameId.computed = false;
  12087. nameId.name = ast.name;
  12088. }
  12089. ensureSafeMemberName(ast.name);
  12090. self.if_(self.stage === 'inputs' || self.not(self.getHasOwnProperty('l', ast.name)),
  12091. function() {
  12092. self.if_(self.stage === 'inputs' || 's', function() {
  12093. if (create && create !== 1) {
  12094. self.if_(
  12095. self.not(self.nonComputedMember('s', ast.name)),
  12096. self.lazyAssign(self.nonComputedMember('s', ast.name), '{}'));
  12097. }
  12098. self.assign(intoId, self.nonComputedMember('s', ast.name));
  12099. });
  12100. }, intoId && self.lazyAssign(intoId, self.nonComputedMember('l', ast.name))
  12101. );
  12102. if (self.state.expensiveChecks || isPossiblyDangerousMemberName(ast.name)) {
  12103. self.addEnsureSafeObject(intoId);
  12104. }
  12105. recursionFn(intoId);
  12106. break;
  12107. case AST.MemberExpression:
  12108. left = nameId && (nameId.context = this.nextId()) || this.nextId();
  12109. intoId = intoId || this.nextId();
  12110. self.recurse(ast.object, left, undefined, function() {
  12111. self.if_(self.notNull(left), function() {
  12112. if (ast.computed) {
  12113. right = self.nextId();
  12114. self.recurse(ast.property, right);
  12115. self.addEnsureSafeMemberName(right);
  12116. if (create && create !== 1) {
  12117. self.if_(self.not(self.computedMember(left, right)), self.lazyAssign(self.computedMember(left, right), '{}'));
  12118. }
  12119. expression = self.ensureSafeObject(self.computedMember(left, right));
  12120. self.assign(intoId, expression);
  12121. if (nameId) {
  12122. nameId.computed = true;
  12123. nameId.name = right;
  12124. }
  12125. } else {
  12126. ensureSafeMemberName(ast.property.name);
  12127. if (create && create !== 1) {
  12128. self.if_(self.not(self.nonComputedMember(left, ast.property.name)), self.lazyAssign(self.nonComputedMember(left, ast.property.name), '{}'));
  12129. }
  12130. expression = self.nonComputedMember(left, ast.property.name);
  12131. if (self.state.expensiveChecks || isPossiblyDangerousMemberName(ast.property.name)) {
  12132. expression = self.ensureSafeObject(expression);
  12133. }
  12134. self.assign(intoId, expression);
  12135. if (nameId) {
  12136. nameId.computed = false;
  12137. nameId.name = ast.property.name;
  12138. }
  12139. }
  12140. }, function() {
  12141. self.assign(intoId, 'undefined');
  12142. });
  12143. recursionFn(intoId);
  12144. }, !!create);
  12145. break;
  12146. case AST.CallExpression:
  12147. intoId = intoId || this.nextId();
  12148. if (ast.filter) {
  12149. right = self.filter(ast.callee.name);
  12150. args = [];
  12151. forEach(ast.arguments, function(expr) {
  12152. var argument = self.nextId();
  12153. self.recurse(expr, argument);
  12154. args.push(argument);
  12155. });
  12156. expression = right + '(' + args.join(',') + ')';
  12157. self.assign(intoId, expression);
  12158. recursionFn(intoId);
  12159. } else {
  12160. right = self.nextId();
  12161. left = {};
  12162. args = [];
  12163. self.recurse(ast.callee, right, left, function() {
  12164. self.if_(self.notNull(right), function() {
  12165. self.addEnsureSafeFunction(right);
  12166. forEach(ast.arguments, function(expr) {
  12167. self.recurse(expr, self.nextId(), undefined, function(argument) {
  12168. args.push(self.ensureSafeObject(argument));
  12169. });
  12170. });
  12171. if (left.name) {
  12172. if (!self.state.expensiveChecks) {
  12173. self.addEnsureSafeObject(left.context);
  12174. }
  12175. expression = self.member(left.context, left.name, left.computed) + '(' + args.join(',') + ')';
  12176. } else {
  12177. expression = right + '(' + args.join(',') + ')';
  12178. }
  12179. expression = self.ensureSafeObject(expression);
  12180. self.assign(intoId, expression);
  12181. }, function() {
  12182. self.assign(intoId, 'undefined');
  12183. });
  12184. recursionFn(intoId);
  12185. });
  12186. }
  12187. break;
  12188. case AST.AssignmentExpression:
  12189. right = this.nextId();
  12190. left = {};
  12191. if (!isAssignable(ast.left)) {
  12192. throw $parseMinErr('lval', 'Trying to assing a value to a non l-value');
  12193. }
  12194. this.recurse(ast.left, undefined, left, function() {
  12195. self.if_(self.notNull(left.context), function() {
  12196. self.recurse(ast.right, right);
  12197. self.addEnsureSafeObject(self.member(left.context, left.name, left.computed));
  12198. expression = self.member(left.context, left.name, left.computed) + ast.operator + right;
  12199. self.assign(intoId, expression);
  12200. recursionFn(intoId || expression);
  12201. });
  12202. }, 1);
  12203. break;
  12204. case AST.ArrayExpression:
  12205. args = [];
  12206. forEach(ast.elements, function(expr) {
  12207. self.recurse(expr, self.nextId(), undefined, function(argument) {
  12208. args.push(argument);
  12209. });
  12210. });
  12211. expression = '[' + args.join(',') + ']';
  12212. this.assign(intoId, expression);
  12213. recursionFn(expression);
  12214. break;
  12215. case AST.ObjectExpression:
  12216. args = [];
  12217. forEach(ast.properties, function(property) {
  12218. self.recurse(property.value, self.nextId(), undefined, function(expr) {
  12219. args.push(self.escape(
  12220. property.key.type === AST.Identifier ? property.key.name :
  12221. ('' + property.key.value)) +
  12222. ':' + expr);
  12223. });
  12224. });
  12225. expression = '{' + args.join(',') + '}';
  12226. this.assign(intoId, expression);
  12227. recursionFn(expression);
  12228. break;
  12229. case AST.ThisExpression:
  12230. this.assign(intoId, 's');
  12231. recursionFn('s');
  12232. break;
  12233. case AST.NGValueParameter:
  12234. this.assign(intoId, 'v');
  12235. recursionFn('v');
  12236. break;
  12237. }
  12238. },
  12239. getHasOwnProperty: function(element, property) {
  12240. var key = element + '.' + property;
  12241. var own = this.current().own;
  12242. if (!own.hasOwnProperty(key)) {
  12243. own[key] = this.nextId(false, element + '&&(' + this.escape(property) + ' in ' + element + ')');
  12244. }
  12245. return own[key];
  12246. },
  12247. assign: function(id, value) {
  12248. if (!id) return;
  12249. this.current().body.push(id, '=', value, ';');
  12250. return id;
  12251. },
  12252. filter: function(filterName) {
  12253. if (!this.state.filters.hasOwnProperty(filterName)) {
  12254. this.state.filters[filterName] = this.nextId(true);
  12255. }
  12256. return this.state.filters[filterName];
  12257. },
  12258. ifDefined: function(id, defaultValue) {
  12259. return 'ifDefined(' + id + ',' + this.escape(defaultValue) + ')';
  12260. },
  12261. plus: function(left, right) {
  12262. return 'plus(' + left + ',' + right + ')';
  12263. },
  12264. return_: function(id) {
  12265. this.current().body.push('return ', id, ';');
  12266. },
  12267. if_: function(test, alternate, consequent) {
  12268. if (test === true) {
  12269. alternate();
  12270. } else {
  12271. var body = this.current().body;
  12272. body.push('if(', test, '){');
  12273. alternate();
  12274. body.push('}');
  12275. if (consequent) {
  12276. body.push('else{');
  12277. consequent();
  12278. body.push('}');
  12279. }
  12280. }
  12281. },
  12282. not: function(expression) {
  12283. return '!(' + expression + ')';
  12284. },
  12285. notNull: function(expression) {
  12286. return expression + '!=null';
  12287. },
  12288. nonComputedMember: function(left, right) {
  12289. return left + '.' + right;
  12290. },
  12291. computedMember: function(left, right) {
  12292. return left + '[' + right + ']';
  12293. },
  12294. member: function(left, right, computed) {
  12295. if (computed) return this.computedMember(left, right);
  12296. return this.nonComputedMember(left, right);
  12297. },
  12298. addEnsureSafeObject: function(item) {
  12299. this.current().body.push(this.ensureSafeObject(item), ';');
  12300. },
  12301. addEnsureSafeMemberName: function(item) {
  12302. this.current().body.push(this.ensureSafeMemberName(item), ';');
  12303. },
  12304. addEnsureSafeFunction: function(item) {
  12305. this.current().body.push(this.ensureSafeFunction(item), ';');
  12306. },
  12307. ensureSafeObject: function(item) {
  12308. return 'ensureSafeObject(' + item + ',text)';
  12309. },
  12310. ensureSafeMemberName: function(item) {
  12311. return 'ensureSafeMemberName(' + item + ',text)';
  12312. },
  12313. ensureSafeFunction: function(item) {
  12314. return 'ensureSafeFunction(' + item + ',text)';
  12315. },
  12316. lazyRecurse: function(ast, intoId, nameId, recursionFn, create, skipWatchIdCheck) {
  12317. var self = this;
  12318. return function() {
  12319. self.recurse(ast, intoId, nameId, recursionFn, create, skipWatchIdCheck);
  12320. };
  12321. },
  12322. lazyAssign: function(id, value) {
  12323. var self = this;
  12324. return function() {
  12325. self.assign(id, value);
  12326. };
  12327. },
  12328. stringEscapeRegex: /[^ a-zA-Z0-9]/g,
  12329. stringEscapeFn: function(c) {
  12330. return '\\u' + ('0000' + c.charCodeAt(0).toString(16)).slice(-4);
  12331. },
  12332. escape: function(value) {
  12333. if (isString(value)) return "'" + value.replace(this.stringEscapeRegex, this.stringEscapeFn) + "'";
  12334. if (isNumber(value)) return value.toString();
  12335. if (value === true) return 'true';
  12336. if (value === false) return 'false';
  12337. if (value === null) return 'null';
  12338. if (typeof value === 'undefined') return 'undefined';
  12339. throw $parseMinErr('esc', 'IMPOSSIBLE');
  12340. },
  12341. nextId: function(skip, init) {
  12342. var id = 'v' + (this.state.nextId++);
  12343. if (!skip) {
  12344. this.current().vars.push(id + (init ? '=' + init : ''));
  12345. }
  12346. return id;
  12347. },
  12348. current: function() {
  12349. return this.state[this.state.computing];
  12350. }
  12351. };
  12352. function ASTInterpreter(astBuilder, $filter) {
  12353. this.astBuilder = astBuilder;
  12354. this.$filter = $filter;
  12355. }
  12356. ASTInterpreter.prototype = {
  12357. compile: function(expression, expensiveChecks) {
  12358. var self = this;
  12359. var ast = this.astBuilder.ast(expression);
  12360. this.expression = expression;
  12361. this.expensiveChecks = expensiveChecks;
  12362. findConstantAndWatchExpressions(ast, self.$filter);
  12363. var assignable;
  12364. var assign;
  12365. if ((assignable = assignableAST(ast))) {
  12366. assign = this.recurse(assignable);
  12367. }
  12368. var toWatch = getInputs(ast.body);
  12369. var inputs;
  12370. if (toWatch) {
  12371. inputs = [];
  12372. forEach(toWatch, function(watch, key) {
  12373. var input = self.recurse(watch);
  12374. watch.input = input;
  12375. inputs.push(input);
  12376. watch.watchId = key;
  12377. });
  12378. }
  12379. var expressions = [];
  12380. forEach(ast.body, function(expression) {
  12381. expressions.push(self.recurse(expression.expression));
  12382. });
  12383. var fn = ast.body.length === 0 ? function() {} :
  12384. ast.body.length === 1 ? expressions[0] :
  12385. function(scope, locals) {
  12386. var lastValue;
  12387. forEach(expressions, function(exp) {
  12388. lastValue = exp(scope, locals);
  12389. });
  12390. return lastValue;
  12391. };
  12392. if (assign) {
  12393. fn.assign = function(scope, value, locals) {
  12394. return assign(scope, locals, value);
  12395. };
  12396. }
  12397. if (inputs) {
  12398. fn.inputs = inputs;
  12399. }
  12400. fn.literal = isLiteral(ast);
  12401. fn.constant = isConstant(ast);
  12402. return fn;
  12403. },
  12404. recurse: function(ast, context, create) {
  12405. var left, right, self = this, args, expression;
  12406. if (ast.input) {
  12407. return this.inputs(ast.input, ast.watchId);
  12408. }
  12409. switch (ast.type) {
  12410. case AST.Literal:
  12411. return this.value(ast.value, context);
  12412. case AST.UnaryExpression:
  12413. right = this.recurse(ast.argument);
  12414. return this['unary' + ast.operator](right, context);
  12415. case AST.BinaryExpression:
  12416. left = this.recurse(ast.left);
  12417. right = this.recurse(ast.right);
  12418. return this['binary' + ast.operator](left, right, context);
  12419. case AST.LogicalExpression:
  12420. left = this.recurse(ast.left);
  12421. right = this.recurse(ast.right);
  12422. return this['binary' + ast.operator](left, right, context);
  12423. case AST.ConditionalExpression:
  12424. return this['ternary?:'](
  12425. this.recurse(ast.test),
  12426. this.recurse(ast.alternate),
  12427. this.recurse(ast.consequent),
  12428. context
  12429. );
  12430. case AST.Identifier:
  12431. ensureSafeMemberName(ast.name, self.expression);
  12432. return self.identifier(ast.name,
  12433. self.expensiveChecks || isPossiblyDangerousMemberName(ast.name),
  12434. context, create, self.expression);
  12435. case AST.MemberExpression:
  12436. left = this.recurse(ast.object, false, !!create);
  12437. if (!ast.computed) {
  12438. ensureSafeMemberName(ast.property.name, self.expression);
  12439. right = ast.property.name;
  12440. }
  12441. if (ast.computed) right = this.recurse(ast.property);
  12442. return ast.computed ?
  12443. this.computedMember(left, right, context, create, self.expression) :
  12444. this.nonComputedMember(left, right, self.expensiveChecks, context, create, self.expression);
  12445. case AST.CallExpression:
  12446. args = [];
  12447. forEach(ast.arguments, function(expr) {
  12448. args.push(self.recurse(expr));
  12449. });
  12450. if (ast.filter) right = this.$filter(ast.callee.name);
  12451. if (!ast.filter) right = this.recurse(ast.callee, true);
  12452. return ast.filter ?
  12453. function(scope, locals, assign, inputs) {
  12454. var values = [];
  12455. for (var i = 0; i < args.length; ++i) {
  12456. values.push(args[i](scope, locals, assign, inputs));
  12457. }
  12458. var value = right.apply(undefined, values, inputs);
  12459. return context ? {context: undefined, name: undefined, value: value} : value;
  12460. } :
  12461. function(scope, locals, assign, inputs) {
  12462. var rhs = right(scope, locals, assign, inputs);
  12463. var value;
  12464. if (rhs.value != null) {
  12465. ensureSafeObject(rhs.context, self.expression);
  12466. ensureSafeFunction(rhs.value, self.expression);
  12467. var values = [];
  12468. for (var i = 0; i < args.length; ++i) {
  12469. values.push(ensureSafeObject(args[i](scope, locals, assign, inputs), self.expression));
  12470. }
  12471. value = ensureSafeObject(rhs.value.apply(rhs.context, values), self.expression);
  12472. }
  12473. return context ? {value: value} : value;
  12474. };
  12475. case AST.AssignmentExpression:
  12476. left = this.recurse(ast.left, true, 1);
  12477. right = this.recurse(ast.right);
  12478. return function(scope, locals, assign, inputs) {
  12479. var lhs = left(scope, locals, assign, inputs);
  12480. var rhs = right(scope, locals, assign, inputs);
  12481. ensureSafeObject(lhs.value, self.expression);
  12482. lhs.context[lhs.name] = rhs;
  12483. return context ? {value: rhs} : rhs;
  12484. };
  12485. case AST.ArrayExpression:
  12486. args = [];
  12487. forEach(ast.elements, function(expr) {
  12488. args.push(self.recurse(expr));
  12489. });
  12490. return function(scope, locals, assign, inputs) {
  12491. var value = [];
  12492. for (var i = 0; i < args.length; ++i) {
  12493. value.push(args[i](scope, locals, assign, inputs));
  12494. }
  12495. return context ? {value: value} : value;
  12496. };
  12497. case AST.ObjectExpression:
  12498. args = [];
  12499. forEach(ast.properties, function(property) {
  12500. args.push({key: property.key.type === AST.Identifier ?
  12501. property.key.name :
  12502. ('' + property.key.value),
  12503. value: self.recurse(property.value)
  12504. });
  12505. });
  12506. return function(scope, locals, assign, inputs) {
  12507. var value = {};
  12508. for (var i = 0; i < args.length; ++i) {
  12509. value[args[i].key] = args[i].value(scope, locals, assign, inputs);
  12510. }
  12511. return context ? {value: value} : value;
  12512. };
  12513. case AST.ThisExpression:
  12514. return function(scope) {
  12515. return context ? {value: scope} : scope;
  12516. };
  12517. case AST.NGValueParameter:
  12518. return function(scope, locals, assign, inputs) {
  12519. return context ? {value: assign} : assign;
  12520. };
  12521. }
  12522. },
  12523. 'unary+': function(argument, context) {
  12524. return function(scope, locals, assign, inputs) {
  12525. var arg = argument(scope, locals, assign, inputs);
  12526. if (isDefined(arg)) {
  12527. arg = +arg;
  12528. } else {
  12529. arg = 0;
  12530. }
  12531. return context ? {value: arg} : arg;
  12532. };
  12533. },
  12534. 'unary-': function(argument, context) {
  12535. return function(scope, locals, assign, inputs) {
  12536. var arg = argument(scope, locals, assign, inputs);
  12537. if (isDefined(arg)) {
  12538. arg = -arg;
  12539. } else {
  12540. arg = 0;
  12541. }
  12542. return context ? {value: arg} : arg;
  12543. };
  12544. },
  12545. 'unary!': function(argument, context) {
  12546. return function(scope, locals, assign, inputs) {
  12547. var arg = !argument(scope, locals, assign, inputs);
  12548. return context ? {value: arg} : arg;
  12549. };
  12550. },
  12551. 'binary+': function(left, right, context) {
  12552. return function(scope, locals, assign, inputs) {
  12553. var lhs = left(scope, locals, assign, inputs);
  12554. var rhs = right(scope, locals, assign, inputs);
  12555. var arg = plusFn(lhs, rhs);
  12556. return context ? {value: arg} : arg;
  12557. };
  12558. },
  12559. 'binary-': function(left, right, context) {
  12560. return function(scope, locals, assign, inputs) {
  12561. var lhs = left(scope, locals, assign, inputs);
  12562. var rhs = right(scope, locals, assign, inputs);
  12563. var arg = (isDefined(lhs) ? lhs : 0) - (isDefined(rhs) ? rhs : 0);
  12564. return context ? {value: arg} : arg;
  12565. };
  12566. },
  12567. 'binary*': function(left, right, context) {
  12568. return function(scope, locals, assign, inputs) {
  12569. var arg = left(scope, locals, assign, inputs) * right(scope, locals, assign, inputs);
  12570. return context ? {value: arg} : arg;
  12571. };
  12572. },
  12573. 'binary/': function(left, right, context) {
  12574. return function(scope, locals, assign, inputs) {
  12575. var arg = left(scope, locals, assign, inputs) / right(scope, locals, assign, inputs);
  12576. return context ? {value: arg} : arg;
  12577. };
  12578. },
  12579. 'binary%': function(left, right, context) {
  12580. return function(scope, locals, assign, inputs) {
  12581. var arg = left(scope, locals, assign, inputs) % right(scope, locals, assign, inputs);
  12582. return context ? {value: arg} : arg;
  12583. };
  12584. },
  12585. 'binary===': function(left, right, context) {
  12586. return function(scope, locals, assign, inputs) {
  12587. var arg = left(scope, locals, assign, inputs) === right(scope, locals, assign, inputs);
  12588. return context ? {value: arg} : arg;
  12589. };
  12590. },
  12591. 'binary!==': function(left, right, context) {
  12592. return function(scope, locals, assign, inputs) {
  12593. var arg = left(scope, locals, assign, inputs) !== right(scope, locals, assign, inputs);
  12594. return context ? {value: arg} : arg;
  12595. };
  12596. },
  12597. 'binary==': function(left, right, context) {
  12598. return function(scope, locals, assign, inputs) {
  12599. var arg = left(scope, locals, assign, inputs) == right(scope, locals, assign, inputs);
  12600. return context ? {value: arg} : arg;
  12601. };
  12602. },
  12603. 'binary!=': function(left, right, context) {
  12604. return function(scope, locals, assign, inputs) {
  12605. var arg = left(scope, locals, assign, inputs) != right(scope, locals, assign, inputs);
  12606. return context ? {value: arg} : arg;
  12607. };
  12608. },
  12609. 'binary<': function(left, right, context) {
  12610. return function(scope, locals, assign, inputs) {
  12611. var arg = left(scope, locals, assign, inputs) < right(scope, locals, assign, inputs);
  12612. return context ? {value: arg} : arg;
  12613. };
  12614. },
  12615. 'binary>': function(left, right, context) {
  12616. return function(scope, locals, assign, inputs) {
  12617. var arg = left(scope, locals, assign, inputs) > right(scope, locals, assign, inputs);
  12618. return context ? {value: arg} : arg;
  12619. };
  12620. },
  12621. 'binary<=': function(left, right, context) {
  12622. return function(scope, locals, assign, inputs) {
  12623. var arg = left(scope, locals, assign, inputs) <= right(scope, locals, assign, inputs);
  12624. return context ? {value: arg} : arg;
  12625. };
  12626. },
  12627. 'binary>=': function(left, right, context) {
  12628. return function(scope, locals, assign, inputs) {
  12629. var arg = left(scope, locals, assign, inputs) >= right(scope, locals, assign, inputs);
  12630. return context ? {value: arg} : arg;
  12631. };
  12632. },
  12633. 'binary&&': function(left, right, context) {
  12634. return function(scope, locals, assign, inputs) {
  12635. var arg = left(scope, locals, assign, inputs) && right(scope, locals, assign, inputs);
  12636. return context ? {value: arg} : arg;
  12637. };
  12638. },
  12639. 'binary||': function(left, right, context) {
  12640. return function(scope, locals, assign, inputs) {
  12641. var arg = left(scope, locals, assign, inputs) || right(scope, locals, assign, inputs);
  12642. return context ? {value: arg} : arg;
  12643. };
  12644. },
  12645. 'ternary?:': function(test, alternate, consequent, context) {
  12646. return function(scope, locals, assign, inputs) {
  12647. var arg = test(scope, locals, assign, inputs) ? alternate(scope, locals, assign, inputs) : consequent(scope, locals, assign, inputs);
  12648. return context ? {value: arg} : arg;
  12649. };
  12650. },
  12651. value: function(value, context) {
  12652. return function() { return context ? {context: undefined, name: undefined, value: value} : value; };
  12653. },
  12654. identifier: function(name, expensiveChecks, context, create, expression) {
  12655. return function(scope, locals, assign, inputs) {
  12656. var base = locals && (name in locals) ? locals : scope;
  12657. if (create && create !== 1 && base && !(base[name])) {
  12658. base[name] = {};
  12659. }
  12660. var value = base ? base[name] : undefined;
  12661. if (expensiveChecks) {
  12662. ensureSafeObject(value, expression);
  12663. }
  12664. if (context) {
  12665. return {context: base, name: name, value: value};
  12666. } else {
  12667. return value;
  12668. }
  12669. };
  12670. },
  12671. computedMember: function(left, right, context, create, expression) {
  12672. return function(scope, locals, assign, inputs) {
  12673. var lhs = left(scope, locals, assign, inputs);
  12674. var rhs;
  12675. var value;
  12676. if (lhs != null) {
  12677. rhs = right(scope, locals, assign, inputs);
  12678. ensureSafeMemberName(rhs, expression);
  12679. if (create && create !== 1 && lhs && !(lhs[rhs])) {
  12680. lhs[rhs] = {};
  12681. }
  12682. value = lhs[rhs];
  12683. ensureSafeObject(value, expression);
  12684. }
  12685. if (context) {
  12686. return {context: lhs, name: rhs, value: value};
  12687. } else {
  12688. return value;
  12689. }
  12690. };
  12691. },
  12692. nonComputedMember: function(left, right, expensiveChecks, context, create, expression) {
  12693. return function(scope, locals, assign, inputs) {
  12694. var lhs = left(scope, locals, assign, inputs);
  12695. if (create && create !== 1 && lhs && !(lhs[right])) {
  12696. lhs[right] = {};
  12697. }
  12698. var value = lhs != null ? lhs[right] : undefined;
  12699. if (expensiveChecks || isPossiblyDangerousMemberName(right)) {
  12700. ensureSafeObject(value, expression);
  12701. }
  12702. if (context) {
  12703. return {context: lhs, name: right, value: value};
  12704. } else {
  12705. return value;
  12706. }
  12707. };
  12708. },
  12709. inputs: function(input, watchId) {
  12710. return function(scope, value, locals, inputs) {
  12711. if (inputs) return inputs[watchId];
  12712. return input(scope, value, locals);
  12713. };
  12714. }
  12715. };
  12716. /**
  12717. * @constructor
  12718. */
  12719. var Parser = function(lexer, $filter, options) {
  12720. this.lexer = lexer;
  12721. this.$filter = $filter;
  12722. this.options = options;
  12723. this.ast = new AST(this.lexer);
  12724. this.astCompiler = options.csp ? new ASTInterpreter(this.ast, $filter) :
  12725. new ASTCompiler(this.ast, $filter);
  12726. };
  12727. Parser.prototype = {
  12728. constructor: Parser,
  12729. parse: function(text) {
  12730. return this.astCompiler.compile(text, this.options.expensiveChecks);
  12731. }
  12732. };
  12733. var getterFnCacheDefault = createMap();
  12734. var getterFnCacheExpensive = createMap();
  12735. function isPossiblyDangerousMemberName(name) {
  12736. return name == 'constructor';
  12737. }
  12738. var objectValueOf = Object.prototype.valueOf;
  12739. function getValueOf(value) {
  12740. return isFunction(value.valueOf) ? value.valueOf() : objectValueOf.call(value);
  12741. }
  12742. ///////////////////////////////////
  12743. /**
  12744. * @ngdoc service
  12745. * @name $parse
  12746. * @kind function
  12747. *
  12748. * @description
  12749. *
  12750. * Converts Angular {@link guide/expression expression} into a function.
  12751. *
  12752. * ```js
  12753. * var getter = $parse('user.name');
  12754. * var setter = getter.assign;
  12755. * var context = {user:{name:'angular'}};
  12756. * var locals = {user:{name:'local'}};
  12757. *
  12758. * expect(getter(context)).toEqual('angular');
  12759. * setter(context, 'newValue');
  12760. * expect(context.user.name).toEqual('newValue');
  12761. * expect(getter(context, locals)).toEqual('local');
  12762. * ```
  12763. *
  12764. *
  12765. * @param {string} expression String expression to compile.
  12766. * @returns {function(context, locals)} a function which represents the compiled expression:
  12767. *
  12768. * * `context` – `{object}` – an object against which any expressions embedded in the strings
  12769. * are evaluated against (typically a scope object).
  12770. * * `locals` – `{object=}` – local variables context object, useful for overriding values in
  12771. * `context`.
  12772. *
  12773. * The returned function also has the following properties:
  12774. * * `literal` – `{boolean}` – whether the expression's top-level node is a JavaScript
  12775. * literal.
  12776. * * `constant` – `{boolean}` – whether the expression is made entirely of JavaScript
  12777. * constant literals.
  12778. * * `assign` – `{?function(context, value)}` – if the expression is assignable, this will be
  12779. * set to a function to change its value on the given context.
  12780. *
  12781. */
  12782. /**
  12783. * @ngdoc provider
  12784. * @name $parseProvider
  12785. *
  12786. * @description
  12787. * `$parseProvider` can be used for configuring the default behavior of the {@link ng.$parse $parse}
  12788. * service.
  12789. */
  12790. function $ParseProvider() {
  12791. var cacheDefault = createMap();
  12792. var cacheExpensive = createMap();
  12793. this.$get = ['$filter', function($filter) {
  12794. var noUnsafeEval = csp().noUnsafeEval;
  12795. var $parseOptions = {
  12796. csp: noUnsafeEval,
  12797. expensiveChecks: false
  12798. },
  12799. $parseOptionsExpensive = {
  12800. csp: noUnsafeEval,
  12801. expensiveChecks: true
  12802. };
  12803. return function $parse(exp, interceptorFn, expensiveChecks) {
  12804. var parsedExpression, oneTime, cacheKey;
  12805. switch (typeof exp) {
  12806. case 'string':
  12807. exp = exp.trim();
  12808. cacheKey = exp;
  12809. var cache = (expensiveChecks ? cacheExpensive : cacheDefault);
  12810. parsedExpression = cache[cacheKey];
  12811. if (!parsedExpression) {
  12812. if (exp.charAt(0) === ':' && exp.charAt(1) === ':') {
  12813. oneTime = true;
  12814. exp = exp.substring(2);
  12815. }
  12816. var parseOptions = expensiveChecks ? $parseOptionsExpensive : $parseOptions;
  12817. var lexer = new Lexer(parseOptions);
  12818. var parser = new Parser(lexer, $filter, parseOptions);
  12819. parsedExpression = parser.parse(exp);
  12820. if (parsedExpression.constant) {
  12821. parsedExpression.$$watchDelegate = constantWatchDelegate;
  12822. } else if (oneTime) {
  12823. parsedExpression.$$watchDelegate = parsedExpression.literal ?
  12824. oneTimeLiteralWatchDelegate : oneTimeWatchDelegate;
  12825. } else if (parsedExpression.inputs) {
  12826. parsedExpression.$$watchDelegate = inputsWatchDelegate;
  12827. }
  12828. cache[cacheKey] = parsedExpression;
  12829. }
  12830. return addInterceptor(parsedExpression, interceptorFn);
  12831. case 'function':
  12832. return addInterceptor(exp, interceptorFn);
  12833. default:
  12834. return noop;
  12835. }
  12836. };
  12837. function expressionInputDirtyCheck(newValue, oldValueOfValue) {
  12838. if (newValue == null || oldValueOfValue == null) { // null/undefined
  12839. return newValue === oldValueOfValue;
  12840. }
  12841. if (typeof newValue === 'object') {
  12842. // attempt to convert the value to a primitive type
  12843. // TODO(docs): add a note to docs that by implementing valueOf even objects and arrays can
  12844. // be cheaply dirty-checked
  12845. newValue = getValueOf(newValue);
  12846. if (typeof newValue === 'object') {
  12847. // objects/arrays are not supported - deep-watching them would be too expensive
  12848. return false;
  12849. }
  12850. // fall-through to the primitive equality check
  12851. }
  12852. //Primitive or NaN
  12853. return newValue === oldValueOfValue || (newValue !== newValue && oldValueOfValue !== oldValueOfValue);
  12854. }
  12855. function inputsWatchDelegate(scope, listener, objectEquality, parsedExpression, prettyPrintExpression) {
  12856. var inputExpressions = parsedExpression.inputs;
  12857. var lastResult;
  12858. if (inputExpressions.length === 1) {
  12859. var oldInputValueOf = expressionInputDirtyCheck; // init to something unique so that equals check fails
  12860. inputExpressions = inputExpressions[0];
  12861. return scope.$watch(function expressionInputWatch(scope) {
  12862. var newInputValue = inputExpressions(scope);
  12863. if (!expressionInputDirtyCheck(newInputValue, oldInputValueOf)) {
  12864. lastResult = parsedExpression(scope, undefined, undefined, [newInputValue]);
  12865. oldInputValueOf = newInputValue && getValueOf(newInputValue);
  12866. }
  12867. return lastResult;
  12868. }, listener, objectEquality, prettyPrintExpression);
  12869. }
  12870. var oldInputValueOfValues = [];
  12871. var oldInputValues = [];
  12872. for (var i = 0, ii = inputExpressions.length; i < ii; i++) {
  12873. oldInputValueOfValues[i] = expressionInputDirtyCheck; // init to something unique so that equals check fails
  12874. oldInputValues[i] = null;
  12875. }
  12876. return scope.$watch(function expressionInputsWatch(scope) {
  12877. var changed = false;
  12878. for (var i = 0, ii = inputExpressions.length; i < ii; i++) {
  12879. var newInputValue = inputExpressions[i](scope);
  12880. if (changed || (changed = !expressionInputDirtyCheck(newInputValue, oldInputValueOfValues[i]))) {
  12881. oldInputValues[i] = newInputValue;
  12882. oldInputValueOfValues[i] = newInputValue && getValueOf(newInputValue);
  12883. }
  12884. }
  12885. if (changed) {
  12886. lastResult = parsedExpression(scope, undefined, undefined, oldInputValues);
  12887. }
  12888. return lastResult;
  12889. }, listener, objectEquality, prettyPrintExpression);
  12890. }
  12891. function oneTimeWatchDelegate(scope, listener, objectEquality, parsedExpression) {
  12892. var unwatch, lastValue;
  12893. return unwatch = scope.$watch(function oneTimeWatch(scope) {
  12894. return parsedExpression(scope);
  12895. }, function oneTimeListener(value, old, scope) {
  12896. lastValue = value;
  12897. if (isFunction(listener)) {
  12898. listener.apply(this, arguments);
  12899. }
  12900. if (isDefined(value)) {
  12901. scope.$$postDigest(function() {
  12902. if (isDefined(lastValue)) {
  12903. unwatch();
  12904. }
  12905. });
  12906. }
  12907. }, objectEquality);
  12908. }
  12909. function oneTimeLiteralWatchDelegate(scope, listener, objectEquality, parsedExpression) {
  12910. var unwatch, lastValue;
  12911. return unwatch = scope.$watch(function oneTimeWatch(scope) {
  12912. return parsedExpression(scope);
  12913. }, function oneTimeListener(value, old, scope) {
  12914. lastValue = value;
  12915. if (isFunction(listener)) {
  12916. listener.call(this, value, old, scope);
  12917. }
  12918. if (isAllDefined(value)) {
  12919. scope.$$postDigest(function() {
  12920. if (isAllDefined(lastValue)) unwatch();
  12921. });
  12922. }
  12923. }, objectEquality);
  12924. function isAllDefined(value) {
  12925. var allDefined = true;
  12926. forEach(value, function(val) {
  12927. if (!isDefined(val)) allDefined = false;
  12928. });
  12929. return allDefined;
  12930. }
  12931. }
  12932. function constantWatchDelegate(scope, listener, objectEquality, parsedExpression) {
  12933. var unwatch;
  12934. return unwatch = scope.$watch(function constantWatch(scope) {
  12935. return parsedExpression(scope);
  12936. }, function constantListener(value, old, scope) {
  12937. if (isFunction(listener)) {
  12938. listener.apply(this, arguments);
  12939. }
  12940. unwatch();
  12941. }, objectEquality);
  12942. }
  12943. function addInterceptor(parsedExpression, interceptorFn) {
  12944. if (!interceptorFn) return parsedExpression;
  12945. var watchDelegate = parsedExpression.$$watchDelegate;
  12946. var regularWatch =
  12947. watchDelegate !== oneTimeLiteralWatchDelegate &&
  12948. watchDelegate !== oneTimeWatchDelegate;
  12949. var fn = regularWatch ? function regularInterceptedExpression(scope, locals, assign, inputs) {
  12950. var value = parsedExpression(scope, locals, assign, inputs);
  12951. return interceptorFn(value, scope, locals);
  12952. } : function oneTimeInterceptedExpression(scope, locals, assign, inputs) {
  12953. var value = parsedExpression(scope, locals, assign, inputs);
  12954. var result = interceptorFn(value, scope, locals);
  12955. // we only return the interceptor's result if the
  12956. // initial value is defined (for bind-once)
  12957. return isDefined(value) ? result : value;
  12958. };
  12959. // Propagate $$watchDelegates other then inputsWatchDelegate
  12960. if (parsedExpression.$$watchDelegate &&
  12961. parsedExpression.$$watchDelegate !== inputsWatchDelegate) {
  12962. fn.$$watchDelegate = parsedExpression.$$watchDelegate;
  12963. } else if (!interceptorFn.$stateful) {
  12964. // If there is an interceptor, but no watchDelegate then treat the interceptor like
  12965. // we treat filters - it is assumed to be a pure function unless flagged with $stateful
  12966. fn.$$watchDelegate = inputsWatchDelegate;
  12967. fn.inputs = parsedExpression.inputs ? parsedExpression.inputs : [parsedExpression];
  12968. }
  12969. return fn;
  12970. }
  12971. }];
  12972. }
  12973. /**
  12974. * @ngdoc service
  12975. * @name $q
  12976. * @requires $rootScope
  12977. *
  12978. * @description
  12979. * A service that helps you run functions asynchronously, and use their return values (or exceptions)
  12980. * when they are done processing.
  12981. *
  12982. * This is an implementation of promises/deferred objects inspired by
  12983. * [Kris Kowal's Q](https://github.com/kriskowal/q).
  12984. *
  12985. * $q can be used in two fashions --- one which is more similar to Kris Kowal's Q or jQuery's Deferred
  12986. * implementations, and the other which resembles ES6 promises to some degree.
  12987. *
  12988. * # $q constructor
  12989. *
  12990. * The streamlined ES6 style promise is essentially just using $q as a constructor which takes a `resolver`
  12991. * function as the first argument. This is similar to the native Promise implementation from ES6 Harmony,
  12992. * see [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise).
  12993. *
  12994. * While the constructor-style use is supported, not all of the supporting methods from ES6 Harmony promises are
  12995. * available yet.
  12996. *
  12997. * It can be used like so:
  12998. *
  12999. * ```js
  13000. * // for the purpose of this example let's assume that variables `$q` and `okToGreet`
  13001. * // are available in the current lexical scope (they could have been injected or passed in).
  13002. *
  13003. * function asyncGreet(name) {
  13004. * // perform some asynchronous operation, resolve or reject the promise when appropriate.
  13005. * return $q(function(resolve, reject) {
  13006. * setTimeout(function() {
  13007. * if (okToGreet(name)) {
  13008. * resolve('Hello, ' + name + '!');
  13009. * } else {
  13010. * reject('Greeting ' + name + ' is not allowed.');
  13011. * }
  13012. * }, 1000);
  13013. * });
  13014. * }
  13015. *
  13016. * var promise = asyncGreet('Robin Hood');
  13017. * promise.then(function(greeting) {
  13018. * alert('Success: ' + greeting);
  13019. * }, function(reason) {
  13020. * alert('Failed: ' + reason);
  13021. * });
  13022. * ```
  13023. *
  13024. * Note: progress/notify callbacks are not currently supported via the ES6-style interface.
  13025. *
  13026. * However, the more traditional CommonJS-style usage is still available, and documented below.
  13027. *
  13028. * [The CommonJS Promise proposal](http://wiki.commonjs.org/wiki/Promises) describes a promise as an
  13029. * interface for interacting with an object that represents the result of an action that is
  13030. * performed asynchronously, and may or may not be finished at any given point in time.
  13031. *
  13032. * From the perspective of dealing with error handling, deferred and promise APIs are to
  13033. * asynchronous programming what `try`, `catch` and `throw` keywords are to synchronous programming.
  13034. *
  13035. * ```js
  13036. * // for the purpose of this example let's assume that variables `$q` and `okToGreet`
  13037. * // are available in the current lexical scope (they could have been injected or passed in).
  13038. *
  13039. * function asyncGreet(name) {
  13040. * var deferred = $q.defer();
  13041. *
  13042. * setTimeout(function() {
  13043. * deferred.notify('About to greet ' + name + '.');
  13044. *
  13045. * if (okToGreet(name)) {
  13046. * deferred.resolve('Hello, ' + name + '!');
  13047. * } else {
  13048. * deferred.reject('Greeting ' + name + ' is not allowed.');
  13049. * }
  13050. * }, 1000);
  13051. *
  13052. * return deferred.promise;
  13053. * }
  13054. *
  13055. * var promise = asyncGreet('Robin Hood');
  13056. * promise.then(function(greeting) {
  13057. * alert('Success: ' + greeting);
  13058. * }, function(reason) {
  13059. * alert('Failed: ' + reason);
  13060. * }, function(update) {
  13061. * alert('Got notification: ' + update);
  13062. * });
  13063. * ```
  13064. *
  13065. * At first it might not be obvious why this extra complexity is worth the trouble. The payoff
  13066. * comes in the way of guarantees that promise and deferred APIs make, see
  13067. * https://github.com/kriskowal/uncommonjs/blob/master/promises/specification.md.
  13068. *
  13069. * Additionally the promise api allows for composition that is very hard to do with the
  13070. * traditional callback ([CPS](http://en.wikipedia.org/wiki/Continuation-passing_style)) approach.
  13071. * For more on this please see the [Q documentation](https://github.com/kriskowal/q) especially the
  13072. * section on serial or parallel joining of promises.
  13073. *
  13074. * # The Deferred API
  13075. *
  13076. * A new instance of deferred is constructed by calling `$q.defer()`.
  13077. *
  13078. * The purpose of the deferred object is to expose the associated Promise instance as well as APIs
  13079. * that can be used for signaling the successful or unsuccessful completion, as well as the status
  13080. * of the task.
  13081. *
  13082. * **Methods**
  13083. *
  13084. * - `resolve(value)` – resolves the derived promise with the `value`. If the value is a rejection
  13085. * constructed via `$q.reject`, the promise will be rejected instead.
  13086. * - `reject(reason)` – rejects the derived promise with the `reason`. This is equivalent to
  13087. * resolving it with a rejection constructed via `$q.reject`.
  13088. * - `notify(value)` - provides updates on the status of the promise's execution. This may be called
  13089. * multiple times before the promise is either resolved or rejected.
  13090. *
  13091. * **Properties**
  13092. *
  13093. * - promise – `{Promise}` – promise object associated with this deferred.
  13094. *
  13095. *
  13096. * # The Promise API
  13097. *
  13098. * A new promise instance is created when a deferred instance is created and can be retrieved by
  13099. * calling `deferred.promise`.
  13100. *
  13101. * The purpose of the promise object is to allow for interested parties to get access to the result
  13102. * of the deferred task when it completes.
  13103. *
  13104. * **Methods**
  13105. *
  13106. * - `then(successCallback, errorCallback, notifyCallback)` – regardless of when the promise was or
  13107. * will be resolved or rejected, `then` calls one of the success or error callbacks asynchronously
  13108. * as soon as the result is available. The callbacks are called with a single argument: the result
  13109. * or rejection reason. Additionally, the notify callback may be called zero or more times to
  13110. * provide a progress indication, before the promise is resolved or rejected.
  13111. *
  13112. * This method *returns a new promise* which is resolved or rejected via the return value of the
  13113. * `successCallback`, `errorCallback` (unless that value is a promise, in which case it is resolved
  13114. * with the value which is resolved in that promise using
  13115. * [promise chaining](http://www.html5rocks.com/en/tutorials/es6/promises/#toc-promises-queues)).
  13116. * It also notifies via the return value of the `notifyCallback` method. The promise cannot be
  13117. * resolved or rejected from the notifyCallback method.
  13118. *
  13119. * - `catch(errorCallback)` – shorthand for `promise.then(null, errorCallback)`
  13120. *
  13121. * - `finally(callback, notifyCallback)` – allows you to observe either the fulfillment or rejection of a promise,
  13122. * but to do so without modifying the final value. This is useful to release resources or do some
  13123. * clean-up that needs to be done whether the promise was rejected or resolved. See the [full
  13124. * specification](https://github.com/kriskowal/q/wiki/API-Reference#promisefinallycallback) for
  13125. * more information.
  13126. *
  13127. * # Chaining promises
  13128. *
  13129. * Because calling the `then` method of a promise returns a new derived promise, it is easily
  13130. * possible to create a chain of promises:
  13131. *
  13132. * ```js
  13133. * promiseB = promiseA.then(function(result) {
  13134. * return result + 1;
  13135. * });
  13136. *
  13137. * // promiseB will be resolved immediately after promiseA is resolved and its value
  13138. * // will be the result of promiseA incremented by 1
  13139. * ```
  13140. *
  13141. * It is possible to create chains of any length and since a promise can be resolved with another
  13142. * promise (which will defer its resolution further), it is possible to pause/defer resolution of
  13143. * the promises at any point in the chain. This makes it possible to implement powerful APIs like
  13144. * $http's response interceptors.
  13145. *
  13146. *
  13147. * # Differences between Kris Kowal's Q and $q
  13148. *
  13149. * There are two main differences:
  13150. *
  13151. * - $q is integrated with the {@link ng.$rootScope.Scope} Scope model observation
  13152. * mechanism in angular, which means faster propagation of resolution or rejection into your
  13153. * models and avoiding unnecessary browser repaints, which would result in flickering UI.
  13154. * - Q has many more features than $q, but that comes at a cost of bytes. $q is tiny, but contains
  13155. * all the important functionality needed for common async tasks.
  13156. *
  13157. * # Testing
  13158. *
  13159. * ```js
  13160. * it('should simulate promise', inject(function($q, $rootScope) {
  13161. * var deferred = $q.defer();
  13162. * var promise = deferred.promise;
  13163. * var resolvedValue;
  13164. *
  13165. * promise.then(function(value) { resolvedValue = value; });
  13166. * expect(resolvedValue).toBeUndefined();
  13167. *
  13168. * // Simulate resolving of promise
  13169. * deferred.resolve(123);
  13170. * // Note that the 'then' function does not get called synchronously.
  13171. * // This is because we want the promise API to always be async, whether or not
  13172. * // it got called synchronously or asynchronously.
  13173. * expect(resolvedValue).toBeUndefined();
  13174. *
  13175. * // Propagate promise resolution to 'then' functions using $apply().
  13176. * $rootScope.$apply();
  13177. * expect(resolvedValue).toEqual(123);
  13178. * }));
  13179. * ```
  13180. *
  13181. * @param {function(function, function)} resolver Function which is responsible for resolving or
  13182. * rejecting the newly created promise. The first parameter is a function which resolves the
  13183. * promise, the second parameter is a function which rejects the promise.
  13184. *
  13185. * @returns {Promise} The newly created promise.
  13186. */
  13187. function $QProvider() {
  13188. this.$get = ['$rootScope', '$exceptionHandler', function($rootScope, $exceptionHandler) {
  13189. return qFactory(function(callback) {
  13190. $rootScope.$evalAsync(callback);
  13191. }, $exceptionHandler);
  13192. }];
  13193. }
  13194. function $$QProvider() {
  13195. this.$get = ['$browser', '$exceptionHandler', function($browser, $exceptionHandler) {
  13196. return qFactory(function(callback) {
  13197. $browser.defer(callback);
  13198. }, $exceptionHandler);
  13199. }];
  13200. }
  13201. /**
  13202. * Constructs a promise manager.
  13203. *
  13204. * @param {function(function)} nextTick Function for executing functions in the next turn.
  13205. * @param {function(...*)} exceptionHandler Function into which unexpected exceptions are passed for
  13206. * debugging purposes.
  13207. * @returns {object} Promise manager.
  13208. */
  13209. function qFactory(nextTick, exceptionHandler) {
  13210. var $qMinErr = minErr('$q', TypeError);
  13211. function callOnce(self, resolveFn, rejectFn) {
  13212. var called = false;
  13213. function wrap(fn) {
  13214. return function(value) {
  13215. if (called) return;
  13216. called = true;
  13217. fn.call(self, value);
  13218. };
  13219. }
  13220. return [wrap(resolveFn), wrap(rejectFn)];
  13221. }
  13222. /**
  13223. * @ngdoc method
  13224. * @name ng.$q#defer
  13225. * @kind function
  13226. *
  13227. * @description
  13228. * Creates a `Deferred` object which represents a task which will finish in the future.
  13229. *
  13230. * @returns {Deferred} Returns a new instance of deferred.
  13231. */
  13232. var defer = function() {
  13233. return new Deferred();
  13234. };
  13235. function Promise() {
  13236. this.$$state = { status: 0 };
  13237. }
  13238. extend(Promise.prototype, {
  13239. then: function(onFulfilled, onRejected, progressBack) {
  13240. if (isUndefined(onFulfilled) && isUndefined(onRejected) && isUndefined(progressBack)) {
  13241. return this;
  13242. }
  13243. var result = new Deferred();
  13244. this.$$state.pending = this.$$state.pending || [];
  13245. this.$$state.pending.push([result, onFulfilled, onRejected, progressBack]);
  13246. if (this.$$state.status > 0) scheduleProcessQueue(this.$$state);
  13247. return result.promise;
  13248. },
  13249. "catch": function(callback) {
  13250. return this.then(null, callback);
  13251. },
  13252. "finally": function(callback, progressBack) {
  13253. return this.then(function(value) {
  13254. return handleCallback(value, true, callback);
  13255. }, function(error) {
  13256. return handleCallback(error, false, callback);
  13257. }, progressBack);
  13258. }
  13259. });
  13260. //Faster, more basic than angular.bind http://jsperf.com/angular-bind-vs-custom-vs-native
  13261. function simpleBind(context, fn) {
  13262. return function(value) {
  13263. fn.call(context, value);
  13264. };
  13265. }
  13266. function processQueue(state) {
  13267. var fn, deferred, pending;
  13268. pending = state.pending;
  13269. state.processScheduled = false;
  13270. state.pending = undefined;
  13271. for (var i = 0, ii = pending.length; i < ii; ++i) {
  13272. deferred = pending[i][0];
  13273. fn = pending[i][state.status];
  13274. try {
  13275. if (isFunction(fn)) {
  13276. deferred.resolve(fn(state.value));
  13277. } else if (state.status === 1) {
  13278. deferred.resolve(state.value);
  13279. } else {
  13280. deferred.reject(state.value);
  13281. }
  13282. } catch (e) {
  13283. deferred.reject(e);
  13284. exceptionHandler(e);
  13285. }
  13286. }
  13287. }
  13288. function scheduleProcessQueue(state) {
  13289. if (state.processScheduled || !state.pending) return;
  13290. state.processScheduled = true;
  13291. nextTick(function() { processQueue(state); });
  13292. }
  13293. function Deferred() {
  13294. this.promise = new Promise();
  13295. //Necessary to support unbound execution :/
  13296. this.resolve = simpleBind(this, this.resolve);
  13297. this.reject = simpleBind(this, this.reject);
  13298. this.notify = simpleBind(this, this.notify);
  13299. }
  13300. extend(Deferred.prototype, {
  13301. resolve: function(val) {
  13302. if (this.promise.$$state.status) return;
  13303. if (val === this.promise) {
  13304. this.$$reject($qMinErr(
  13305. 'qcycle',
  13306. "Expected promise to be resolved with value other than itself '{0}'",
  13307. val));
  13308. } else {
  13309. this.$$resolve(val);
  13310. }
  13311. },
  13312. $$resolve: function(val) {
  13313. var then, fns;
  13314. fns = callOnce(this, this.$$resolve, this.$$reject);
  13315. try {
  13316. if ((isObject(val) || isFunction(val))) then = val && val.then;
  13317. if (isFunction(then)) {
  13318. this.promise.$$state.status = -1;
  13319. then.call(val, fns[0], fns[1], this.notify);
  13320. } else {
  13321. this.promise.$$state.value = val;
  13322. this.promise.$$state.status = 1;
  13323. scheduleProcessQueue(this.promise.$$state);
  13324. }
  13325. } catch (e) {
  13326. fns[1](e);
  13327. exceptionHandler(e);
  13328. }
  13329. },
  13330. reject: function(reason) {
  13331. if (this.promise.$$state.status) return;
  13332. this.$$reject(reason);
  13333. },
  13334. $$reject: function(reason) {
  13335. this.promise.$$state.value = reason;
  13336. this.promise.$$state.status = 2;
  13337. scheduleProcessQueue(this.promise.$$state);
  13338. },
  13339. notify: function(progress) {
  13340. var callbacks = this.promise.$$state.pending;
  13341. if ((this.promise.$$state.status <= 0) && callbacks && callbacks.length) {
  13342. nextTick(function() {
  13343. var callback, result;
  13344. for (var i = 0, ii = callbacks.length; i < ii; i++) {
  13345. result = callbacks[i][0];
  13346. callback = callbacks[i][3];
  13347. try {
  13348. result.notify(isFunction(callback) ? callback(progress) : progress);
  13349. } catch (e) {
  13350. exceptionHandler(e);
  13351. }
  13352. }
  13353. });
  13354. }
  13355. }
  13356. });
  13357. /**
  13358. * @ngdoc method
  13359. * @name $q#reject
  13360. * @kind function
  13361. *
  13362. * @description
  13363. * Creates a promise that is resolved as rejected with the specified `reason`. This api should be
  13364. * used to forward rejection in a chain of promises. If you are dealing with the last promise in
  13365. * a promise chain, you don't need to worry about it.
  13366. *
  13367. * When comparing deferreds/promises to the familiar behavior of try/catch/throw, think of
  13368. * `reject` as the `throw` keyword in JavaScript. This also means that if you "catch" an error via
  13369. * a promise error callback and you want to forward the error to the promise derived from the
  13370. * current promise, you have to "rethrow" the error by returning a rejection constructed via
  13371. * `reject`.
  13372. *
  13373. * ```js
  13374. * promiseB = promiseA.then(function(result) {
  13375. * // success: do something and resolve promiseB
  13376. * // with the old or a new result
  13377. * return result;
  13378. * }, function(reason) {
  13379. * // error: handle the error if possible and
  13380. * // resolve promiseB with newPromiseOrValue,
  13381. * // otherwise forward the rejection to promiseB
  13382. * if (canHandle(reason)) {
  13383. * // handle the error and recover
  13384. * return newPromiseOrValue;
  13385. * }
  13386. * return $q.reject(reason);
  13387. * });
  13388. * ```
  13389. *
  13390. * @param {*} reason Constant, message, exception or an object representing the rejection reason.
  13391. * @returns {Promise} Returns a promise that was already resolved as rejected with the `reason`.
  13392. */
  13393. var reject = function(reason) {
  13394. var result = new Deferred();
  13395. result.reject(reason);
  13396. return result.promise;
  13397. };
  13398. var makePromise = function makePromise(value, resolved) {
  13399. var result = new Deferred();
  13400. if (resolved) {
  13401. result.resolve(value);
  13402. } else {
  13403. result.reject(value);
  13404. }
  13405. return result.promise;
  13406. };
  13407. var handleCallback = function handleCallback(value, isResolved, callback) {
  13408. var callbackOutput = null;
  13409. try {
  13410. if (isFunction(callback)) callbackOutput = callback();
  13411. } catch (e) {
  13412. return makePromise(e, false);
  13413. }
  13414. if (isPromiseLike(callbackOutput)) {
  13415. return callbackOutput.then(function() {
  13416. return makePromise(value, isResolved);
  13417. }, function(error) {
  13418. return makePromise(error, false);
  13419. });
  13420. } else {
  13421. return makePromise(value, isResolved);
  13422. }
  13423. };
  13424. /**
  13425. * @ngdoc method
  13426. * @name $q#when
  13427. * @kind function
  13428. *
  13429. * @description
  13430. * Wraps an object that might be a value or a (3rd party) then-able promise into a $q promise.
  13431. * This is useful when you are dealing with an object that might or might not be a promise, or if
  13432. * the promise comes from a source that can't be trusted.
  13433. *
  13434. * @param {*} value Value or a promise
  13435. * @param {Function=} successCallback
  13436. * @param {Function=} errorCallback
  13437. * @param {Function=} progressCallback
  13438. * @returns {Promise} Returns a promise of the passed value or promise
  13439. */
  13440. var when = function(value, callback, errback, progressBack) {
  13441. var result = new Deferred();
  13442. result.resolve(value);
  13443. return result.promise.then(callback, errback, progressBack);
  13444. };
  13445. /**
  13446. * @ngdoc method
  13447. * @name $q#resolve
  13448. * @kind function
  13449. *
  13450. * @description
  13451. * Alias of {@link ng.$q#when when} to maintain naming consistency with ES6.
  13452. *
  13453. * @param {*} value Value or a promise
  13454. * @param {Function=} successCallback
  13455. * @param {Function=} errorCallback
  13456. * @param {Function=} progressCallback
  13457. * @returns {Promise} Returns a promise of the passed value or promise
  13458. */
  13459. var resolve = when;
  13460. /**
  13461. * @ngdoc method
  13462. * @name $q#all
  13463. * @kind function
  13464. *
  13465. * @description
  13466. * Combines multiple promises into a single promise that is resolved when all of the input
  13467. * promises are resolved.
  13468. *
  13469. * @param {Array.<Promise>|Object.<Promise>} promises An array or hash of promises.
  13470. * @returns {Promise} Returns a single promise that will be resolved with an array/hash of values,
  13471. * each value corresponding to the promise at the same index/key in the `promises` array/hash.
  13472. * If any of the promises is resolved with a rejection, this resulting promise will be rejected
  13473. * with the same rejection value.
  13474. */
  13475. function all(promises) {
  13476. var deferred = new Deferred(),
  13477. counter = 0,
  13478. results = isArray(promises) ? [] : {};
  13479. forEach(promises, function(promise, key) {
  13480. counter++;
  13481. when(promise).then(function(value) {
  13482. if (results.hasOwnProperty(key)) return;
  13483. results[key] = value;
  13484. if (!(--counter)) deferred.resolve(results);
  13485. }, function(reason) {
  13486. if (results.hasOwnProperty(key)) return;
  13487. deferred.reject(reason);
  13488. });
  13489. });
  13490. if (counter === 0) {
  13491. deferred.resolve(results);
  13492. }
  13493. return deferred.promise;
  13494. }
  13495. var $Q = function Q(resolver) {
  13496. if (!isFunction(resolver)) {
  13497. throw $qMinErr('norslvr', "Expected resolverFn, got '{0}'", resolver);
  13498. }
  13499. if (!(this instanceof Q)) {
  13500. // More useful when $Q is the Promise itself.
  13501. return new Q(resolver);
  13502. }
  13503. var deferred = new Deferred();
  13504. function resolveFn(value) {
  13505. deferred.resolve(value);
  13506. }
  13507. function rejectFn(reason) {
  13508. deferred.reject(reason);
  13509. }
  13510. resolver(resolveFn, rejectFn);
  13511. return deferred.promise;
  13512. };
  13513. $Q.defer = defer;
  13514. $Q.reject = reject;
  13515. $Q.when = when;
  13516. $Q.resolve = resolve;
  13517. $Q.all = all;
  13518. return $Q;
  13519. }
  13520. function $$RAFProvider() { //rAF
  13521. this.$get = ['$window', '$timeout', function($window, $timeout) {
  13522. var requestAnimationFrame = $window.requestAnimationFrame ||
  13523. $window.webkitRequestAnimationFrame;
  13524. var cancelAnimationFrame = $window.cancelAnimationFrame ||
  13525. $window.webkitCancelAnimationFrame ||
  13526. $window.webkitCancelRequestAnimationFrame;
  13527. var rafSupported = !!requestAnimationFrame;
  13528. var raf = rafSupported
  13529. ? function(fn) {
  13530. var id = requestAnimationFrame(fn);
  13531. return function() {
  13532. cancelAnimationFrame(id);
  13533. };
  13534. }
  13535. : function(fn) {
  13536. var timer = $timeout(fn, 16.66, false); // 1000 / 60 = 16.666
  13537. return function() {
  13538. $timeout.cancel(timer);
  13539. };
  13540. };
  13541. raf.supported = rafSupported;
  13542. return raf;
  13543. }];
  13544. }
  13545. /**
  13546. * DESIGN NOTES
  13547. *
  13548. * The design decisions behind the scope are heavily favored for speed and memory consumption.
  13549. *
  13550. * The typical use of scope is to watch the expressions, which most of the time return the same
  13551. * value as last time so we optimize the operation.
  13552. *
  13553. * Closures construction is expensive in terms of speed as well as memory:
  13554. * - No closures, instead use prototypical inheritance for API
  13555. * - Internal state needs to be stored on scope directly, which means that private state is
  13556. * exposed as $$____ properties
  13557. *
  13558. * Loop operations are optimized by using while(count--) { ... }
  13559. * - this means that in order to keep the same order of execution as addition we have to add
  13560. * items to the array at the beginning (unshift) instead of at the end (push)
  13561. *
  13562. * Child scopes are created and removed often
  13563. * - Using an array would be slow since inserts in middle are expensive so we use linked list
  13564. *
  13565. * There are few watches then a lot of observers. This is why you don't want the observer to be
  13566. * implemented in the same way as watch. Watch requires return of initialization function which
  13567. * are expensive to construct.
  13568. */
  13569. /**
  13570. * @ngdoc provider
  13571. * @name $rootScopeProvider
  13572. * @description
  13573. *
  13574. * Provider for the $rootScope service.
  13575. */
  13576. /**
  13577. * @ngdoc method
  13578. * @name $rootScopeProvider#digestTtl
  13579. * @description
  13580. *
  13581. * Sets the number of `$digest` iterations the scope should attempt to execute before giving up and
  13582. * assuming that the model is unstable.
  13583. *
  13584. * The current default is 10 iterations.
  13585. *
  13586. * In complex applications it's possible that the dependencies between `$watch`s will result in
  13587. * several digest iterations. However if an application needs more than the default 10 digest
  13588. * iterations for its model to stabilize then you should investigate what is causing the model to
  13589. * continuously change during the digest.
  13590. *
  13591. * Increasing the TTL could have performance implications, so you should not change it without
  13592. * proper justification.
  13593. *
  13594. * @param {number} limit The number of digest iterations.
  13595. */
  13596. /**
  13597. * @ngdoc service
  13598. * @name $rootScope
  13599. * @description
  13600. *
  13601. * Every application has a single root {@link ng.$rootScope.Scope scope}.
  13602. * All other scopes are descendant scopes of the root scope. Scopes provide separation
  13603. * between the model and the view, via a mechanism for watching the model for changes.
  13604. * They also provide an event emission/broadcast and subscription facility. See the
  13605. * {@link guide/scope developer guide on scopes}.
  13606. */
  13607. function $RootScopeProvider() {
  13608. var TTL = 10;
  13609. var $rootScopeMinErr = minErr('$rootScope');
  13610. var lastDirtyWatch = null;
  13611. var applyAsyncId = null;
  13612. this.digestTtl = function(value) {
  13613. if (arguments.length) {
  13614. TTL = value;
  13615. }
  13616. return TTL;
  13617. };
  13618. function createChildScopeClass(parent) {
  13619. function ChildScope() {
  13620. this.$$watchers = this.$$nextSibling =
  13621. this.$$childHead = this.$$childTail = null;
  13622. this.$$listeners = {};
  13623. this.$$listenerCount = {};
  13624. this.$$watchersCount = 0;
  13625. this.$id = nextUid();
  13626. this.$$ChildScope = null;
  13627. }
  13628. ChildScope.prototype = parent;
  13629. return ChildScope;
  13630. }
  13631. this.$get = ['$injector', '$exceptionHandler', '$parse', '$browser',
  13632. function($injector, $exceptionHandler, $parse, $browser) {
  13633. function destroyChildScope($event) {
  13634. $event.currentScope.$$destroyed = true;
  13635. }
  13636. /**
  13637. * @ngdoc type
  13638. * @name $rootScope.Scope
  13639. *
  13640. * @description
  13641. * A root scope can be retrieved using the {@link ng.$rootScope $rootScope} key from the
  13642. * {@link auto.$injector $injector}. Child scopes are created using the
  13643. * {@link ng.$rootScope.Scope#$new $new()} method. (Most scopes are created automatically when
  13644. * compiled HTML template is executed.) See also the {@link guide/scope Scopes guide} for
  13645. * an in-depth introduction and usage examples.
  13646. *
  13647. *
  13648. * # Inheritance
  13649. * A scope can inherit from a parent scope, as in this example:
  13650. * ```js
  13651. var parent = $rootScope;
  13652. var child = parent.$new();
  13653. parent.salutation = "Hello";
  13654. expect(child.salutation).toEqual('Hello');
  13655. child.salutation = "Welcome";
  13656. expect(child.salutation).toEqual('Welcome');
  13657. expect(parent.salutation).toEqual('Hello');
  13658. * ```
  13659. *
  13660. * When interacting with `Scope` in tests, additional helper methods are available on the
  13661. * instances of `Scope` type. See {@link ngMock.$rootScope.Scope ngMock Scope} for additional
  13662. * details.
  13663. *
  13664. *
  13665. * @param {Object.<string, function()>=} providers Map of service factory which need to be
  13666. * provided for the current scope. Defaults to {@link ng}.
  13667. * @param {Object.<string, *>=} instanceCache Provides pre-instantiated services which should
  13668. * append/override services provided by `providers`. This is handy
  13669. * when unit-testing and having the need to override a default
  13670. * service.
  13671. * @returns {Object} Newly created scope.
  13672. *
  13673. */
  13674. function Scope() {
  13675. this.$id = nextUid();
  13676. this.$$phase = this.$parent = this.$$watchers =
  13677. this.$$nextSibling = this.$$prevSibling =
  13678. this.$$childHead = this.$$childTail = null;
  13679. this.$root = this;
  13680. this.$$destroyed = false;
  13681. this.$$listeners = {};
  13682. this.$$listenerCount = {};
  13683. this.$$watchersCount = 0;
  13684. this.$$isolateBindings = null;
  13685. }
  13686. /**
  13687. * @ngdoc property
  13688. * @name $rootScope.Scope#$id
  13689. *
  13690. * @description
  13691. * Unique scope ID (monotonically increasing) useful for debugging.
  13692. */
  13693. /**
  13694. * @ngdoc property
  13695. * @name $rootScope.Scope#$parent
  13696. *
  13697. * @description
  13698. * Reference to the parent scope.
  13699. */
  13700. /**
  13701. * @ngdoc property
  13702. * @name $rootScope.Scope#$root
  13703. *
  13704. * @description
  13705. * Reference to the root scope.
  13706. */
  13707. Scope.prototype = {
  13708. constructor: Scope,
  13709. /**
  13710. * @ngdoc method
  13711. * @name $rootScope.Scope#$new
  13712. * @kind function
  13713. *
  13714. * @description
  13715. * Creates a new child {@link ng.$rootScope.Scope scope}.
  13716. *
  13717. * The parent scope will propagate the {@link ng.$rootScope.Scope#$digest $digest()} event.
  13718. * The scope can be removed from the scope hierarchy using {@link ng.$rootScope.Scope#$destroy $destroy()}.
  13719. *
  13720. * {@link ng.$rootScope.Scope#$destroy $destroy()} must be called on a scope when it is
  13721. * desired for the scope and its child scopes to be permanently detached from the parent and
  13722. * thus stop participating in model change detection and listener notification by invoking.
  13723. *
  13724. * @param {boolean} isolate If true, then the scope does not prototypically inherit from the
  13725. * parent scope. The scope is isolated, as it can not see parent scope properties.
  13726. * When creating widgets, it is useful for the widget to not accidentally read parent
  13727. * state.
  13728. *
  13729. * @param {Scope} [parent=this] The {@link ng.$rootScope.Scope `Scope`} that will be the `$parent`
  13730. * of the newly created scope. Defaults to `this` scope if not provided.
  13731. * This is used when creating a transclude scope to correctly place it
  13732. * in the scope hierarchy while maintaining the correct prototypical
  13733. * inheritance.
  13734. *
  13735. * @returns {Object} The newly created child scope.
  13736. *
  13737. */
  13738. $new: function(isolate, parent) {
  13739. var child;
  13740. parent = parent || this;
  13741. if (isolate) {
  13742. child = new Scope();
  13743. child.$root = this.$root;
  13744. } else {
  13745. // Only create a child scope class if somebody asks for one,
  13746. // but cache it to allow the VM to optimize lookups.
  13747. if (!this.$$ChildScope) {
  13748. this.$$ChildScope = createChildScopeClass(this);
  13749. }
  13750. child = new this.$$ChildScope();
  13751. }
  13752. child.$parent = parent;
  13753. child.$$prevSibling = parent.$$childTail;
  13754. if (parent.$$childHead) {
  13755. parent.$$childTail.$$nextSibling = child;
  13756. parent.$$childTail = child;
  13757. } else {
  13758. parent.$$childHead = parent.$$childTail = child;
  13759. }
  13760. // When the new scope is not isolated or we inherit from `this`, and
  13761. // the parent scope is destroyed, the property `$$destroyed` is inherited
  13762. // prototypically. In all other cases, this property needs to be set
  13763. // when the parent scope is destroyed.
  13764. // The listener needs to be added after the parent is set
  13765. if (isolate || parent != this) child.$on('$destroy', destroyChildScope);
  13766. return child;
  13767. },
  13768. /**
  13769. * @ngdoc method
  13770. * @name $rootScope.Scope#$watch
  13771. * @kind function
  13772. *
  13773. * @description
  13774. * Registers a `listener` callback to be executed whenever the `watchExpression` changes.
  13775. *
  13776. * - The `watchExpression` is called on every call to {@link ng.$rootScope.Scope#$digest
  13777. * $digest()} and should return the value that will be watched. (`watchExpression` should not change
  13778. * its value when executed multiple times with the same input because it may be executed multiple
  13779. * times by {@link ng.$rootScope.Scope#$digest $digest()}. That is, `watchExpression` should be
  13780. * [idempotent](http://en.wikipedia.org/wiki/Idempotence).
  13781. * - The `listener` is called only when the value from the current `watchExpression` and the
  13782. * previous call to `watchExpression` are not equal (with the exception of the initial run,
  13783. * see below). Inequality is determined according to reference inequality,
  13784. * [strict comparison](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Comparison_Operators)
  13785. * via the `!==` Javascript operator, unless `objectEquality == true`
  13786. * (see next point)
  13787. * - When `objectEquality == true`, inequality of the `watchExpression` is determined
  13788. * according to the {@link angular.equals} function. To save the value of the object for
  13789. * later comparison, the {@link angular.copy} function is used. This therefore means that
  13790. * watching complex objects will have adverse memory and performance implications.
  13791. * - The watch `listener` may change the model, which may trigger other `listener`s to fire.
  13792. * This is achieved by rerunning the watchers until no changes are detected. The rerun
  13793. * iteration limit is 10 to prevent an infinite loop deadlock.
  13794. *
  13795. *
  13796. * If you want to be notified whenever {@link ng.$rootScope.Scope#$digest $digest} is called,
  13797. * you can register a `watchExpression` function with no `listener`. (Be prepared for
  13798. * multiple calls to your `watchExpression` because it will execute multiple times in a
  13799. * single {@link ng.$rootScope.Scope#$digest $digest} cycle if a change is detected.)
  13800. *
  13801. * After a watcher is registered with the scope, the `listener` fn is called asynchronously
  13802. * (via {@link ng.$rootScope.Scope#$evalAsync $evalAsync}) to initialize the
  13803. * watcher. In rare cases, this is undesirable because the listener is called when the result
  13804. * of `watchExpression` didn't change. To detect this scenario within the `listener` fn, you
  13805. * can compare the `newVal` and `oldVal`. If these two values are identical (`===`) then the
  13806. * listener was called due to initialization.
  13807. *
  13808. *
  13809. *
  13810. * # Example
  13811. * ```js
  13812. // let's assume that scope was dependency injected as the $rootScope
  13813. var scope = $rootScope;
  13814. scope.name = 'misko';
  13815. scope.counter = 0;
  13816. expect(scope.counter).toEqual(0);
  13817. scope.$watch('name', function(newValue, oldValue) {
  13818. scope.counter = scope.counter + 1;
  13819. });
  13820. expect(scope.counter).toEqual(0);
  13821. scope.$digest();
  13822. // the listener is always called during the first $digest loop after it was registered
  13823. expect(scope.counter).toEqual(1);
  13824. scope.$digest();
  13825. // but now it will not be called unless the value changes
  13826. expect(scope.counter).toEqual(1);
  13827. scope.name = 'adam';
  13828. scope.$digest();
  13829. expect(scope.counter).toEqual(2);
  13830. // Using a function as a watchExpression
  13831. var food;
  13832. scope.foodCounter = 0;
  13833. expect(scope.foodCounter).toEqual(0);
  13834. scope.$watch(
  13835. // This function returns the value being watched. It is called for each turn of the $digest loop
  13836. function() { return food; },
  13837. // This is the change listener, called when the value returned from the above function changes
  13838. function(newValue, oldValue) {
  13839. if ( newValue !== oldValue ) {
  13840. // Only increment the counter if the value changed
  13841. scope.foodCounter = scope.foodCounter + 1;
  13842. }
  13843. }
  13844. );
  13845. // No digest has been run so the counter will be zero
  13846. expect(scope.foodCounter).toEqual(0);
  13847. // Run the digest but since food has not changed count will still be zero
  13848. scope.$digest();
  13849. expect(scope.foodCounter).toEqual(0);
  13850. // Update food and run digest. Now the counter will increment
  13851. food = 'cheeseburger';
  13852. scope.$digest();
  13853. expect(scope.foodCounter).toEqual(1);
  13854. * ```
  13855. *
  13856. *
  13857. *
  13858. * @param {(function()|string)} watchExpression Expression that is evaluated on each
  13859. * {@link ng.$rootScope.Scope#$digest $digest} cycle. A change in the return value triggers
  13860. * a call to the `listener`.
  13861. *
  13862. * - `string`: Evaluated as {@link guide/expression expression}
  13863. * - `function(scope)`: called with current `scope` as a parameter.
  13864. * @param {function(newVal, oldVal, scope)} listener Callback called whenever the value
  13865. * of `watchExpression` changes.
  13866. *
  13867. * - `newVal` contains the current value of the `watchExpression`
  13868. * - `oldVal` contains the previous value of the `watchExpression`
  13869. * - `scope` refers to the current scope
  13870. * @param {boolean=} objectEquality Compare for object equality using {@link angular.equals} instead of
  13871. * comparing for reference equality.
  13872. * @returns {function()} Returns a deregistration function for this listener.
  13873. */
  13874. $watch: function(watchExp, listener, objectEquality, prettyPrintExpression) {
  13875. var get = $parse(watchExp);
  13876. if (get.$$watchDelegate) {
  13877. return get.$$watchDelegate(this, listener, objectEquality, get, watchExp);
  13878. }
  13879. var scope = this,
  13880. array = scope.$$watchers,
  13881. watcher = {
  13882. fn: listener,
  13883. last: initWatchVal,
  13884. get: get,
  13885. exp: prettyPrintExpression || watchExp,
  13886. eq: !!objectEquality
  13887. };
  13888. lastDirtyWatch = null;
  13889. if (!isFunction(listener)) {
  13890. watcher.fn = noop;
  13891. }
  13892. if (!array) {
  13893. array = scope.$$watchers = [];
  13894. }
  13895. // we use unshift since we use a while loop in $digest for speed.
  13896. // the while loop reads in reverse order.
  13897. array.unshift(watcher);
  13898. incrementWatchersCount(this, 1);
  13899. return function deregisterWatch() {
  13900. if (arrayRemove(array, watcher) >= 0) {
  13901. incrementWatchersCount(scope, -1);
  13902. }
  13903. lastDirtyWatch = null;
  13904. };
  13905. },
  13906. /**
  13907. * @ngdoc method
  13908. * @name $rootScope.Scope#$watchGroup
  13909. * @kind function
  13910. *
  13911. * @description
  13912. * A variant of {@link ng.$rootScope.Scope#$watch $watch()} where it watches an array of `watchExpressions`.
  13913. * If any one expression in the collection changes the `listener` is executed.
  13914. *
  13915. * - The items in the `watchExpressions` array are observed via standard $watch operation and are examined on every
  13916. * call to $digest() to see if any items changes.
  13917. * - The `listener` is called whenever any expression in the `watchExpressions` array changes.
  13918. *
  13919. * @param {Array.<string|Function(scope)>} watchExpressions Array of expressions that will be individually
  13920. * watched using {@link ng.$rootScope.Scope#$watch $watch()}
  13921. *
  13922. * @param {function(newValues, oldValues, scope)} listener Callback called whenever the return value of any
  13923. * expression in `watchExpressions` changes
  13924. * The `newValues` array contains the current values of the `watchExpressions`, with the indexes matching
  13925. * those of `watchExpression`
  13926. * and the `oldValues` array contains the previous values of the `watchExpressions`, with the indexes matching
  13927. * those of `watchExpression`
  13928. * The `scope` refers to the current scope.
  13929. * @returns {function()} Returns a de-registration function for all listeners.
  13930. */
  13931. $watchGroup: function(watchExpressions, listener) {
  13932. var oldValues = new Array(watchExpressions.length);
  13933. var newValues = new Array(watchExpressions.length);
  13934. var deregisterFns = [];
  13935. var self = this;
  13936. var changeReactionScheduled = false;
  13937. var firstRun = true;
  13938. if (!watchExpressions.length) {
  13939. // No expressions means we call the listener ASAP
  13940. var shouldCall = true;
  13941. self.$evalAsync(function() {
  13942. if (shouldCall) listener(newValues, newValues, self);
  13943. });
  13944. return function deregisterWatchGroup() {
  13945. shouldCall = false;
  13946. };
  13947. }
  13948. if (watchExpressions.length === 1) {
  13949. // Special case size of one
  13950. return this.$watch(watchExpressions[0], function watchGroupAction(value, oldValue, scope) {
  13951. newValues[0] = value;
  13952. oldValues[0] = oldValue;
  13953. listener(newValues, (value === oldValue) ? newValues : oldValues, scope);
  13954. });
  13955. }
  13956. forEach(watchExpressions, function(expr, i) {
  13957. var unwatchFn = self.$watch(expr, function watchGroupSubAction(value, oldValue) {
  13958. newValues[i] = value;
  13959. oldValues[i] = oldValue;
  13960. if (!changeReactionScheduled) {
  13961. changeReactionScheduled = true;
  13962. self.$evalAsync(watchGroupAction);
  13963. }
  13964. });
  13965. deregisterFns.push(unwatchFn);
  13966. });
  13967. function watchGroupAction() {
  13968. changeReactionScheduled = false;
  13969. if (firstRun) {
  13970. firstRun = false;
  13971. listener(newValues, newValues, self);
  13972. } else {
  13973. listener(newValues, oldValues, self);
  13974. }
  13975. }
  13976. return function deregisterWatchGroup() {
  13977. while (deregisterFns.length) {
  13978. deregisterFns.shift()();
  13979. }
  13980. };
  13981. },
  13982. /**
  13983. * @ngdoc method
  13984. * @name $rootScope.Scope#$watchCollection
  13985. * @kind function
  13986. *
  13987. * @description
  13988. * Shallow watches the properties of an object and fires whenever any of the properties change
  13989. * (for arrays, this implies watching the array items; for object maps, this implies watching
  13990. * the properties). If a change is detected, the `listener` callback is fired.
  13991. *
  13992. * - The `obj` collection is observed via standard $watch operation and is examined on every
  13993. * call to $digest() to see if any items have been added, removed, or moved.
  13994. * - The `listener` is called whenever anything within the `obj` has changed. Examples include
  13995. * adding, removing, and moving items belonging to an object or array.
  13996. *
  13997. *
  13998. * # Example
  13999. * ```js
  14000. $scope.names = ['igor', 'matias', 'misko', 'james'];
  14001. $scope.dataCount = 4;
  14002. $scope.$watchCollection('names', function(newNames, oldNames) {
  14003. $scope.dataCount = newNames.length;
  14004. });
  14005. expect($scope.dataCount).toEqual(4);
  14006. $scope.$digest();
  14007. //still at 4 ... no changes
  14008. expect($scope.dataCount).toEqual(4);
  14009. $scope.names.pop();
  14010. $scope.$digest();
  14011. //now there's been a change
  14012. expect($scope.dataCount).toEqual(3);
  14013. * ```
  14014. *
  14015. *
  14016. * @param {string|function(scope)} obj Evaluated as {@link guide/expression expression}. The
  14017. * expression value should evaluate to an object or an array which is observed on each
  14018. * {@link ng.$rootScope.Scope#$digest $digest} cycle. Any shallow change within the
  14019. * collection will trigger a call to the `listener`.
  14020. *
  14021. * @param {function(newCollection, oldCollection, scope)} listener a callback function called
  14022. * when a change is detected.
  14023. * - The `newCollection` object is the newly modified data obtained from the `obj` expression
  14024. * - The `oldCollection` object is a copy of the former collection data.
  14025. * Due to performance considerations, the`oldCollection` value is computed only if the
  14026. * `listener` function declares two or more arguments.
  14027. * - The `scope` argument refers to the current scope.
  14028. *
  14029. * @returns {function()} Returns a de-registration function for this listener. When the
  14030. * de-registration function is executed, the internal watch operation is terminated.
  14031. */
  14032. $watchCollection: function(obj, listener) {
  14033. $watchCollectionInterceptor.$stateful = true;
  14034. var self = this;
  14035. // the current value, updated on each dirty-check run
  14036. var newValue;
  14037. // a shallow copy of the newValue from the last dirty-check run,
  14038. // updated to match newValue during dirty-check run
  14039. var oldValue;
  14040. // a shallow copy of the newValue from when the last change happened
  14041. var veryOldValue;
  14042. // only track veryOldValue if the listener is asking for it
  14043. var trackVeryOldValue = (listener.length > 1);
  14044. var changeDetected = 0;
  14045. var changeDetector = $parse(obj, $watchCollectionInterceptor);
  14046. var internalArray = [];
  14047. var internalObject = {};
  14048. var initRun = true;
  14049. var oldLength = 0;
  14050. function $watchCollectionInterceptor(_value) {
  14051. newValue = _value;
  14052. var newLength, key, bothNaN, newItem, oldItem;
  14053. // If the new value is undefined, then return undefined as the watch may be a one-time watch
  14054. if (isUndefined(newValue)) return;
  14055. if (!isObject(newValue)) { // if primitive
  14056. if (oldValue !== newValue) {
  14057. oldValue = newValue;
  14058. changeDetected++;
  14059. }
  14060. } else if (isArrayLike(newValue)) {
  14061. if (oldValue !== internalArray) {
  14062. // we are transitioning from something which was not an array into array.
  14063. oldValue = internalArray;
  14064. oldLength = oldValue.length = 0;
  14065. changeDetected++;
  14066. }
  14067. newLength = newValue.length;
  14068. if (oldLength !== newLength) {
  14069. // if lengths do not match we need to trigger change notification
  14070. changeDetected++;
  14071. oldValue.length = oldLength = newLength;
  14072. }
  14073. // copy the items to oldValue and look for changes.
  14074. for (var i = 0; i < newLength; i++) {
  14075. oldItem = oldValue[i];
  14076. newItem = newValue[i];
  14077. bothNaN = (oldItem !== oldItem) && (newItem !== newItem);
  14078. if (!bothNaN && (oldItem !== newItem)) {
  14079. changeDetected++;
  14080. oldValue[i] = newItem;
  14081. }
  14082. }
  14083. } else {
  14084. if (oldValue !== internalObject) {
  14085. // we are transitioning from something which was not an object into object.
  14086. oldValue = internalObject = {};
  14087. oldLength = 0;
  14088. changeDetected++;
  14089. }
  14090. // copy the items to oldValue and look for changes.
  14091. newLength = 0;
  14092. for (key in newValue) {
  14093. if (hasOwnProperty.call(newValue, key)) {
  14094. newLength++;
  14095. newItem = newValue[key];
  14096. oldItem = oldValue[key];
  14097. if (key in oldValue) {
  14098. bothNaN = (oldItem !== oldItem) && (newItem !== newItem);
  14099. if (!bothNaN && (oldItem !== newItem)) {
  14100. changeDetected++;
  14101. oldValue[key] = newItem;
  14102. }
  14103. } else {
  14104. oldLength++;
  14105. oldValue[key] = newItem;
  14106. changeDetected++;
  14107. }
  14108. }
  14109. }
  14110. if (oldLength > newLength) {
  14111. // we used to have more keys, need to find them and destroy them.
  14112. changeDetected++;
  14113. for (key in oldValue) {
  14114. if (!hasOwnProperty.call(newValue, key)) {
  14115. oldLength--;
  14116. delete oldValue[key];
  14117. }
  14118. }
  14119. }
  14120. }
  14121. return changeDetected;
  14122. }
  14123. function $watchCollectionAction() {
  14124. if (initRun) {
  14125. initRun = false;
  14126. listener(newValue, newValue, self);
  14127. } else {
  14128. listener(newValue, veryOldValue, self);
  14129. }
  14130. // make a copy for the next time a collection is changed
  14131. if (trackVeryOldValue) {
  14132. if (!isObject(newValue)) {
  14133. //primitive
  14134. veryOldValue = newValue;
  14135. } else if (isArrayLike(newValue)) {
  14136. veryOldValue = new Array(newValue.length);
  14137. for (var i = 0; i < newValue.length; i++) {
  14138. veryOldValue[i] = newValue[i];
  14139. }
  14140. } else { // if object
  14141. veryOldValue = {};
  14142. for (var key in newValue) {
  14143. if (hasOwnProperty.call(newValue, key)) {
  14144. veryOldValue[key] = newValue[key];
  14145. }
  14146. }
  14147. }
  14148. }
  14149. }
  14150. return this.$watch(changeDetector, $watchCollectionAction);
  14151. },
  14152. /**
  14153. * @ngdoc method
  14154. * @name $rootScope.Scope#$digest
  14155. * @kind function
  14156. *
  14157. * @description
  14158. * Processes all of the {@link ng.$rootScope.Scope#$watch watchers} of the current scope and
  14159. * its children. Because a {@link ng.$rootScope.Scope#$watch watcher}'s listener can change
  14160. * the model, the `$digest()` keeps calling the {@link ng.$rootScope.Scope#$watch watchers}
  14161. * until no more listeners are firing. This means that it is possible to get into an infinite
  14162. * loop. This function will throw `'Maximum iteration limit exceeded.'` if the number of
  14163. * iterations exceeds 10.
  14164. *
  14165. * Usually, you don't call `$digest()` directly in
  14166. * {@link ng.directive:ngController controllers} or in
  14167. * {@link ng.$compileProvider#directive directives}.
  14168. * Instead, you should call {@link ng.$rootScope.Scope#$apply $apply()} (typically from within
  14169. * a {@link ng.$compileProvider#directive directive}), which will force a `$digest()`.
  14170. *
  14171. * If you want to be notified whenever `$digest()` is called,
  14172. * you can register a `watchExpression` function with
  14173. * {@link ng.$rootScope.Scope#$watch $watch()} with no `listener`.
  14174. *
  14175. * In unit tests, you may need to call `$digest()` to simulate the scope life cycle.
  14176. *
  14177. * # Example
  14178. * ```js
  14179. var scope = ...;
  14180. scope.name = 'misko';
  14181. scope.counter = 0;
  14182. expect(scope.counter).toEqual(0);
  14183. scope.$watch('name', function(newValue, oldValue) {
  14184. scope.counter = scope.counter + 1;
  14185. });
  14186. expect(scope.counter).toEqual(0);
  14187. scope.$digest();
  14188. // the listener is always called during the first $digest loop after it was registered
  14189. expect(scope.counter).toEqual(1);
  14190. scope.$digest();
  14191. // but now it will not be called unless the value changes
  14192. expect(scope.counter).toEqual(1);
  14193. scope.name = 'adam';
  14194. scope.$digest();
  14195. expect(scope.counter).toEqual(2);
  14196. * ```
  14197. *
  14198. */
  14199. $digest: function() {
  14200. var watch, value, last,
  14201. watchers,
  14202. length,
  14203. dirty, ttl = TTL,
  14204. next, current, target = this,
  14205. watchLog = [],
  14206. logIdx, logMsg, asyncTask;
  14207. beginPhase('$digest');
  14208. // Check for changes to browser url that happened in sync before the call to $digest
  14209. $browser.$$checkUrlChange();
  14210. if (this === $rootScope && applyAsyncId !== null) {
  14211. // If this is the root scope, and $applyAsync has scheduled a deferred $apply(), then
  14212. // cancel the scheduled $apply and flush the queue of expressions to be evaluated.
  14213. $browser.defer.cancel(applyAsyncId);
  14214. flushApplyAsync();
  14215. }
  14216. lastDirtyWatch = null;
  14217. do { // "while dirty" loop
  14218. dirty = false;
  14219. current = target;
  14220. while (asyncQueue.length) {
  14221. try {
  14222. asyncTask = asyncQueue.shift();
  14223. asyncTask.scope.$eval(asyncTask.expression, asyncTask.locals);
  14224. } catch (e) {
  14225. $exceptionHandler(e);
  14226. }
  14227. lastDirtyWatch = null;
  14228. }
  14229. traverseScopesLoop:
  14230. do { // "traverse the scopes" loop
  14231. if ((watchers = current.$$watchers)) {
  14232. // process our watches
  14233. length = watchers.length;
  14234. while (length--) {
  14235. try {
  14236. watch = watchers[length];
  14237. // Most common watches are on primitives, in which case we can short
  14238. // circuit it with === operator, only when === fails do we use .equals
  14239. if (watch) {
  14240. if ((value = watch.get(current)) !== (last = watch.last) &&
  14241. !(watch.eq
  14242. ? equals(value, last)
  14243. : (typeof value === 'number' && typeof last === 'number'
  14244. && isNaN(value) && isNaN(last)))) {
  14245. dirty = true;
  14246. lastDirtyWatch = watch;
  14247. watch.last = watch.eq ? copy(value, null) : value;
  14248. watch.fn(value, ((last === initWatchVal) ? value : last), current);
  14249. if (ttl < 5) {
  14250. logIdx = 4 - ttl;
  14251. if (!watchLog[logIdx]) watchLog[logIdx] = [];
  14252. watchLog[logIdx].push({
  14253. msg: isFunction(watch.exp) ? 'fn: ' + (watch.exp.name || watch.exp.toString()) : watch.exp,
  14254. newVal: value,
  14255. oldVal: last
  14256. });
  14257. }
  14258. } else if (watch === lastDirtyWatch) {
  14259. // If the most recently dirty watcher is now clean, short circuit since the remaining watchers
  14260. // have already been tested.
  14261. dirty = false;
  14262. break traverseScopesLoop;
  14263. }
  14264. }
  14265. } catch (e) {
  14266. $exceptionHandler(e);
  14267. }
  14268. }
  14269. }
  14270. // Insanity Warning: scope depth-first traversal
  14271. // yes, this code is a bit crazy, but it works and we have tests to prove it!
  14272. // this piece should be kept in sync with the traversal in $broadcast
  14273. if (!(next = ((current.$$watchersCount && current.$$childHead) ||
  14274. (current !== target && current.$$nextSibling)))) {
  14275. while (current !== target && !(next = current.$$nextSibling)) {
  14276. current = current.$parent;
  14277. }
  14278. }
  14279. } while ((current = next));
  14280. // `break traverseScopesLoop;` takes us to here
  14281. if ((dirty || asyncQueue.length) && !(ttl--)) {
  14282. clearPhase();
  14283. throw $rootScopeMinErr('infdig',
  14284. '{0} $digest() iterations reached. Aborting!\n' +
  14285. 'Watchers fired in the last 5 iterations: {1}',
  14286. TTL, watchLog);
  14287. }
  14288. } while (dirty || asyncQueue.length);
  14289. clearPhase();
  14290. while (postDigestQueue.length) {
  14291. try {
  14292. postDigestQueue.shift()();
  14293. } catch (e) {
  14294. $exceptionHandler(e);
  14295. }
  14296. }
  14297. },
  14298. /**
  14299. * @ngdoc event
  14300. * @name $rootScope.Scope#$destroy
  14301. * @eventType broadcast on scope being destroyed
  14302. *
  14303. * @description
  14304. * Broadcasted when a scope and its children are being destroyed.
  14305. *
  14306. * Note that, in AngularJS, there is also a `$destroy` jQuery event, which can be used to
  14307. * clean up DOM bindings before an element is removed from the DOM.
  14308. */
  14309. /**
  14310. * @ngdoc method
  14311. * @name $rootScope.Scope#$destroy
  14312. * @kind function
  14313. *
  14314. * @description
  14315. * Removes the current scope (and all of its children) from the parent scope. Removal implies
  14316. * that calls to {@link ng.$rootScope.Scope#$digest $digest()} will no longer
  14317. * propagate to the current scope and its children. Removal also implies that the current
  14318. * scope is eligible for garbage collection.
  14319. *
  14320. * The `$destroy()` is usually used by directives such as
  14321. * {@link ng.directive:ngRepeat ngRepeat} for managing the
  14322. * unrolling of the loop.
  14323. *
  14324. * Just before a scope is destroyed, a `$destroy` event is broadcasted on this scope.
  14325. * Application code can register a `$destroy` event handler that will give it a chance to
  14326. * perform any necessary cleanup.
  14327. *
  14328. * Note that, in AngularJS, there is also a `$destroy` jQuery event, which can be used to
  14329. * clean up DOM bindings before an element is removed from the DOM.
  14330. */
  14331. $destroy: function() {
  14332. // We can't destroy a scope that has been already destroyed.
  14333. if (this.$$destroyed) return;
  14334. var parent = this.$parent;
  14335. this.$broadcast('$destroy');
  14336. this.$$destroyed = true;
  14337. if (this === $rootScope) {
  14338. //Remove handlers attached to window when $rootScope is removed
  14339. $browser.$$applicationDestroyed();
  14340. }
  14341. incrementWatchersCount(this, -this.$$watchersCount);
  14342. for (var eventName in this.$$listenerCount) {
  14343. decrementListenerCount(this, this.$$listenerCount[eventName], eventName);
  14344. }
  14345. // sever all the references to parent scopes (after this cleanup, the current scope should
  14346. // not be retained by any of our references and should be eligible for garbage collection)
  14347. if (parent && parent.$$childHead == this) parent.$$childHead = this.$$nextSibling;
  14348. if (parent && parent.$$childTail == this) parent.$$childTail = this.$$prevSibling;
  14349. if (this.$$prevSibling) this.$$prevSibling.$$nextSibling = this.$$nextSibling;
  14350. if (this.$$nextSibling) this.$$nextSibling.$$prevSibling = this.$$prevSibling;
  14351. // Disable listeners, watchers and apply/digest methods
  14352. this.$destroy = this.$digest = this.$apply = this.$evalAsync = this.$applyAsync = noop;
  14353. this.$on = this.$watch = this.$watchGroup = function() { return noop; };
  14354. this.$$listeners = {};
  14355. // All of the code below is bogus code that works around V8's memory leak via optimized code
  14356. // and inline caches.
  14357. //
  14358. // see:
  14359. // - https://code.google.com/p/v8/issues/detail?id=2073#c26
  14360. // - https://github.com/angular/angular.js/issues/6794#issuecomment-38648909
  14361. // - https://github.com/angular/angular.js/issues/1313#issuecomment-10378451
  14362. this.$parent = this.$$nextSibling = this.$$prevSibling = this.$$childHead =
  14363. this.$$childTail = this.$root = this.$$watchers = null;
  14364. },
  14365. /**
  14366. * @ngdoc method
  14367. * @name $rootScope.Scope#$eval
  14368. * @kind function
  14369. *
  14370. * @description
  14371. * Executes the `expression` on the current scope and returns the result. Any exceptions in
  14372. * the expression are propagated (uncaught). This is useful when evaluating Angular
  14373. * expressions.
  14374. *
  14375. * # Example
  14376. * ```js
  14377. var scope = ng.$rootScope.Scope();
  14378. scope.a = 1;
  14379. scope.b = 2;
  14380. expect(scope.$eval('a+b')).toEqual(3);
  14381. expect(scope.$eval(function(scope){ return scope.a + scope.b; })).toEqual(3);
  14382. * ```
  14383. *
  14384. * @param {(string|function())=} expression An angular expression to be executed.
  14385. *
  14386. * - `string`: execute using the rules as defined in {@link guide/expression expression}.
  14387. * - `function(scope)`: execute the function with the current `scope` parameter.
  14388. *
  14389. * @param {(object)=} locals Local variables object, useful for overriding values in scope.
  14390. * @returns {*} The result of evaluating the expression.
  14391. */
  14392. $eval: function(expr, locals) {
  14393. return $parse(expr)(this, locals);
  14394. },
  14395. /**
  14396. * @ngdoc method
  14397. * @name $rootScope.Scope#$evalAsync
  14398. * @kind function
  14399. *
  14400. * @description
  14401. * Executes the expression on the current scope at a later point in time.
  14402. *
  14403. * The `$evalAsync` makes no guarantees as to when the `expression` will be executed, only
  14404. * that:
  14405. *
  14406. * - it will execute after the function that scheduled the evaluation (preferably before DOM
  14407. * rendering).
  14408. * - at least one {@link ng.$rootScope.Scope#$digest $digest cycle} will be performed after
  14409. * `expression` execution.
  14410. *
  14411. * Any exceptions from the execution of the expression are forwarded to the
  14412. * {@link ng.$exceptionHandler $exceptionHandler} service.
  14413. *
  14414. * __Note:__ if this function is called outside of a `$digest` cycle, a new `$digest` cycle
  14415. * will be scheduled. However, it is encouraged to always call code that changes the model
  14416. * from within an `$apply` call. That includes code evaluated via `$evalAsync`.
  14417. *
  14418. * @param {(string|function())=} expression An angular expression to be executed.
  14419. *
  14420. * - `string`: execute using the rules as defined in {@link guide/expression expression}.
  14421. * - `function(scope)`: execute the function with the current `scope` parameter.
  14422. *
  14423. * @param {(object)=} locals Local variables object, useful for overriding values in scope.
  14424. */
  14425. $evalAsync: function(expr, locals) {
  14426. // if we are outside of an $digest loop and this is the first time we are scheduling async
  14427. // task also schedule async auto-flush
  14428. if (!$rootScope.$$phase && !asyncQueue.length) {
  14429. $browser.defer(function() {
  14430. if (asyncQueue.length) {
  14431. $rootScope.$digest();
  14432. }
  14433. });
  14434. }
  14435. asyncQueue.push({scope: this, expression: expr, locals: locals});
  14436. },
  14437. $$postDigest: function(fn) {
  14438. postDigestQueue.push(fn);
  14439. },
  14440. /**
  14441. * @ngdoc method
  14442. * @name $rootScope.Scope#$apply
  14443. * @kind function
  14444. *
  14445. * @description
  14446. * `$apply()` is used to execute an expression in angular from outside of the angular
  14447. * framework. (For example from browser DOM events, setTimeout, XHR or third party libraries).
  14448. * Because we are calling into the angular framework we need to perform proper scope life
  14449. * cycle of {@link ng.$exceptionHandler exception handling},
  14450. * {@link ng.$rootScope.Scope#$digest executing watches}.
  14451. *
  14452. * ## Life cycle
  14453. *
  14454. * # Pseudo-Code of `$apply()`
  14455. * ```js
  14456. function $apply(expr) {
  14457. try {
  14458. return $eval(expr);
  14459. } catch (e) {
  14460. $exceptionHandler(e);
  14461. } finally {
  14462. $root.$digest();
  14463. }
  14464. }
  14465. * ```
  14466. *
  14467. *
  14468. * Scope's `$apply()` method transitions through the following stages:
  14469. *
  14470. * 1. The {@link guide/expression expression} is executed using the
  14471. * {@link ng.$rootScope.Scope#$eval $eval()} method.
  14472. * 2. Any exceptions from the execution of the expression are forwarded to the
  14473. * {@link ng.$exceptionHandler $exceptionHandler} service.
  14474. * 3. The {@link ng.$rootScope.Scope#$watch watch} listeners are fired immediately after the
  14475. * expression was executed using the {@link ng.$rootScope.Scope#$digest $digest()} method.
  14476. *
  14477. *
  14478. * @param {(string|function())=} exp An angular expression to be executed.
  14479. *
  14480. * - `string`: execute using the rules as defined in {@link guide/expression expression}.
  14481. * - `function(scope)`: execute the function with current `scope` parameter.
  14482. *
  14483. * @returns {*} The result of evaluating the expression.
  14484. */
  14485. $apply: function(expr) {
  14486. try {
  14487. beginPhase('$apply');
  14488. try {
  14489. return this.$eval(expr);
  14490. } finally {
  14491. clearPhase();
  14492. }
  14493. } catch (e) {
  14494. $exceptionHandler(e);
  14495. } finally {
  14496. try {
  14497. $rootScope.$digest();
  14498. } catch (e) {
  14499. $exceptionHandler(e);
  14500. throw e;
  14501. }
  14502. }
  14503. },
  14504. /**
  14505. * @ngdoc method
  14506. * @name $rootScope.Scope#$applyAsync
  14507. * @kind function
  14508. *
  14509. * @description
  14510. * Schedule the invocation of $apply to occur at a later time. The actual time difference
  14511. * varies across browsers, but is typically around ~10 milliseconds.
  14512. *
  14513. * This can be used to queue up multiple expressions which need to be evaluated in the same
  14514. * digest.
  14515. *
  14516. * @param {(string|function())=} exp An angular expression to be executed.
  14517. *
  14518. * - `string`: execute using the rules as defined in {@link guide/expression expression}.
  14519. * - `function(scope)`: execute the function with current `scope` parameter.
  14520. */
  14521. $applyAsync: function(expr) {
  14522. var scope = this;
  14523. expr && applyAsyncQueue.push($applyAsyncExpression);
  14524. scheduleApplyAsync();
  14525. function $applyAsyncExpression() {
  14526. scope.$eval(expr);
  14527. }
  14528. },
  14529. /**
  14530. * @ngdoc method
  14531. * @name $rootScope.Scope#$on
  14532. * @kind function
  14533. *
  14534. * @description
  14535. * Listens on events of a given type. See {@link ng.$rootScope.Scope#$emit $emit} for
  14536. * discussion of event life cycle.
  14537. *
  14538. * The event listener function format is: `function(event, args...)`. The `event` object
  14539. * passed into the listener has the following attributes:
  14540. *
  14541. * - `targetScope` - `{Scope}`: the scope on which the event was `$emit`-ed or
  14542. * `$broadcast`-ed.
  14543. * - `currentScope` - `{Scope}`: the scope that is currently handling the event. Once the
  14544. * event propagates through the scope hierarchy, this property is set to null.
  14545. * - `name` - `{string}`: name of the event.
  14546. * - `stopPropagation` - `{function=}`: calling `stopPropagation` function will cancel
  14547. * further event propagation (available only for events that were `$emit`-ed).
  14548. * - `preventDefault` - `{function}`: calling `preventDefault` sets `defaultPrevented` flag
  14549. * to true.
  14550. * - `defaultPrevented` - `{boolean}`: true if `preventDefault` was called.
  14551. *
  14552. * @param {string} name Event name to listen on.
  14553. * @param {function(event, ...args)} listener Function to call when the event is emitted.
  14554. * @returns {function()} Returns a deregistration function for this listener.
  14555. */
  14556. $on: function(name, listener) {
  14557. var namedListeners = this.$$listeners[name];
  14558. if (!namedListeners) {
  14559. this.$$listeners[name] = namedListeners = [];
  14560. }
  14561. namedListeners.push(listener);
  14562. var current = this;
  14563. do {
  14564. if (!current.$$listenerCount[name]) {
  14565. current.$$listenerCount[name] = 0;
  14566. }
  14567. current.$$listenerCount[name]++;
  14568. } while ((current = current.$parent));
  14569. var self = this;
  14570. return function() {
  14571. var indexOfListener = namedListeners.indexOf(listener);
  14572. if (indexOfListener !== -1) {
  14573. namedListeners[indexOfListener] = null;
  14574. decrementListenerCount(self, 1, name);
  14575. }
  14576. };
  14577. },
  14578. /**
  14579. * @ngdoc method
  14580. * @name $rootScope.Scope#$emit
  14581. * @kind function
  14582. *
  14583. * @description
  14584. * Dispatches an event `name` upwards through the scope hierarchy notifying the
  14585. * registered {@link ng.$rootScope.Scope#$on} listeners.
  14586. *
  14587. * The event life cycle starts at the scope on which `$emit` was called. All
  14588. * {@link ng.$rootScope.Scope#$on listeners} listening for `name` event on this scope get
  14589. * notified. Afterwards, the event traverses upwards toward the root scope and calls all
  14590. * registered listeners along the way. The event will stop propagating if one of the listeners
  14591. * cancels it.
  14592. *
  14593. * Any exception emitted from the {@link ng.$rootScope.Scope#$on listeners} will be passed
  14594. * onto the {@link ng.$exceptionHandler $exceptionHandler} service.
  14595. *
  14596. * @param {string} name Event name to emit.
  14597. * @param {...*} args Optional one or more arguments which will be passed onto the event listeners.
  14598. * @return {Object} Event object (see {@link ng.$rootScope.Scope#$on}).
  14599. */
  14600. $emit: function(name, args) {
  14601. var empty = [],
  14602. namedListeners,
  14603. scope = this,
  14604. stopPropagation = false,
  14605. event = {
  14606. name: name,
  14607. targetScope: scope,
  14608. stopPropagation: function() {stopPropagation = true;},
  14609. preventDefault: function() {
  14610. event.defaultPrevented = true;
  14611. },
  14612. defaultPrevented: false
  14613. },
  14614. listenerArgs = concat([event], arguments, 1),
  14615. i, length;
  14616. do {
  14617. namedListeners = scope.$$listeners[name] || empty;
  14618. event.currentScope = scope;
  14619. for (i = 0, length = namedListeners.length; i < length; i++) {
  14620. // if listeners were deregistered, defragment the array
  14621. if (!namedListeners[i]) {
  14622. namedListeners.splice(i, 1);
  14623. i--;
  14624. length--;
  14625. continue;
  14626. }
  14627. try {
  14628. //allow all listeners attached to the current scope to run
  14629. namedListeners[i].apply(null, listenerArgs);
  14630. } catch (e) {
  14631. $exceptionHandler(e);
  14632. }
  14633. }
  14634. //if any listener on the current scope stops propagation, prevent bubbling
  14635. if (stopPropagation) {
  14636. event.currentScope = null;
  14637. return event;
  14638. }
  14639. //traverse upwards
  14640. scope = scope.$parent;
  14641. } while (scope);
  14642. event.currentScope = null;
  14643. return event;
  14644. },
  14645. /**
  14646. * @ngdoc method
  14647. * @name $rootScope.Scope#$broadcast
  14648. * @kind function
  14649. *
  14650. * @description
  14651. * Dispatches an event `name` downwards to all child scopes (and their children) notifying the
  14652. * registered {@link ng.$rootScope.Scope#$on} listeners.
  14653. *
  14654. * The event life cycle starts at the scope on which `$broadcast` was called. All
  14655. * {@link ng.$rootScope.Scope#$on listeners} listening for `name` event on this scope get
  14656. * notified. Afterwards, the event propagates to all direct and indirect scopes of the current
  14657. * scope and calls all registered listeners along the way. The event cannot be canceled.
  14658. *
  14659. * Any exception emitted from the {@link ng.$rootScope.Scope#$on listeners} will be passed
  14660. * onto the {@link ng.$exceptionHandler $exceptionHandler} service.
  14661. *
  14662. * @param {string} name Event name to broadcast.
  14663. * @param {...*} args Optional one or more arguments which will be passed onto the event listeners.
  14664. * @return {Object} Event object, see {@link ng.$rootScope.Scope#$on}
  14665. */
  14666. $broadcast: function(name, args) {
  14667. var target = this,
  14668. current = target,
  14669. next = target,
  14670. event = {
  14671. name: name,
  14672. targetScope: target,
  14673. preventDefault: function() {
  14674. event.defaultPrevented = true;
  14675. },
  14676. defaultPrevented: false
  14677. };
  14678. if (!target.$$listenerCount[name]) return event;
  14679. var listenerArgs = concat([event], arguments, 1),
  14680. listeners, i, length;
  14681. //down while you can, then up and next sibling or up and next sibling until back at root
  14682. while ((current = next)) {
  14683. event.currentScope = current;
  14684. listeners = current.$$listeners[name] || [];
  14685. for (i = 0, length = listeners.length; i < length; i++) {
  14686. // if listeners were deregistered, defragment the array
  14687. if (!listeners[i]) {
  14688. listeners.splice(i, 1);
  14689. i--;
  14690. length--;
  14691. continue;
  14692. }
  14693. try {
  14694. listeners[i].apply(null, listenerArgs);
  14695. } catch (e) {
  14696. $exceptionHandler(e);
  14697. }
  14698. }
  14699. // Insanity Warning: scope depth-first traversal
  14700. // yes, this code is a bit crazy, but it works and we have tests to prove it!
  14701. // this piece should be kept in sync with the traversal in $digest
  14702. // (though it differs due to having the extra check for $$listenerCount)
  14703. if (!(next = ((current.$$listenerCount[name] && current.$$childHead) ||
  14704. (current !== target && current.$$nextSibling)))) {
  14705. while (current !== target && !(next = current.$$nextSibling)) {
  14706. current = current.$parent;
  14707. }
  14708. }
  14709. }
  14710. event.currentScope = null;
  14711. return event;
  14712. }
  14713. };
  14714. var $rootScope = new Scope();
  14715. //The internal queues. Expose them on the $rootScope for debugging/testing purposes.
  14716. var asyncQueue = $rootScope.$$asyncQueue = [];
  14717. var postDigestQueue = $rootScope.$$postDigestQueue = [];
  14718. var applyAsyncQueue = $rootScope.$$applyAsyncQueue = [];
  14719. return $rootScope;
  14720. function beginPhase(phase) {
  14721. if ($rootScope.$$phase) {
  14722. throw $rootScopeMinErr('inprog', '{0} already in progress', $rootScope.$$phase);
  14723. }
  14724. $rootScope.$$phase = phase;
  14725. }
  14726. function clearPhase() {
  14727. $rootScope.$$phase = null;
  14728. }
  14729. function incrementWatchersCount(current, count) {
  14730. do {
  14731. current.$$watchersCount += count;
  14732. } while ((current = current.$parent));
  14733. }
  14734. function decrementListenerCount(current, count, name) {
  14735. do {
  14736. current.$$listenerCount[name] -= count;
  14737. if (current.$$listenerCount[name] === 0) {
  14738. delete current.$$listenerCount[name];
  14739. }
  14740. } while ((current = current.$parent));
  14741. }
  14742. /**
  14743. * function used as an initial value for watchers.
  14744. * because it's unique we can easily tell it apart from other values
  14745. */
  14746. function initWatchVal() {}
  14747. function flushApplyAsync() {
  14748. while (applyAsyncQueue.length) {
  14749. try {
  14750. applyAsyncQueue.shift()();
  14751. } catch (e) {
  14752. $exceptionHandler(e);
  14753. }
  14754. }
  14755. applyAsyncId = null;
  14756. }
  14757. function scheduleApplyAsync() {
  14758. if (applyAsyncId === null) {
  14759. applyAsyncId = $browser.defer(function() {
  14760. $rootScope.$apply(flushApplyAsync);
  14761. });
  14762. }
  14763. }
  14764. }];
  14765. }
  14766. /**
  14767. * @description
  14768. * Private service to sanitize uris for links and images. Used by $compile and $sanitize.
  14769. */
  14770. function $$SanitizeUriProvider() {
  14771. var aHrefSanitizationWhitelist = /^\s*(https?|ftp|mailto|tel|file):/,
  14772. imgSrcSanitizationWhitelist = /^\s*((https?|ftp|file|blob):|data:image\/)/;
  14773. /**
  14774. * @description
  14775. * Retrieves or overrides the default regular expression that is used for whitelisting of safe
  14776. * urls during a[href] sanitization.
  14777. *
  14778. * The sanitization is a security measure aimed at prevent XSS attacks via html links.
  14779. *
  14780. * Any url about to be assigned to a[href] via data-binding is first normalized and turned into
  14781. * an absolute url. Afterwards, the url is matched against the `aHrefSanitizationWhitelist`
  14782. * regular expression. If a match is found, the original url is written into the dom. Otherwise,
  14783. * the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM.
  14784. *
  14785. * @param {RegExp=} regexp New regexp to whitelist urls with.
  14786. * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for
  14787. * chaining otherwise.
  14788. */
  14789. this.aHrefSanitizationWhitelist = function(regexp) {
  14790. if (isDefined(regexp)) {
  14791. aHrefSanitizationWhitelist = regexp;
  14792. return this;
  14793. }
  14794. return aHrefSanitizationWhitelist;
  14795. };
  14796. /**
  14797. * @description
  14798. * Retrieves or overrides the default regular expression that is used for whitelisting of safe
  14799. * urls during img[src] sanitization.
  14800. *
  14801. * The sanitization is a security measure aimed at prevent XSS attacks via html links.
  14802. *
  14803. * Any url about to be assigned to img[src] via data-binding is first normalized and turned into
  14804. * an absolute url. Afterwards, the url is matched against the `imgSrcSanitizationWhitelist`
  14805. * regular expression. If a match is found, the original url is written into the dom. Otherwise,
  14806. * the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM.
  14807. *
  14808. * @param {RegExp=} regexp New regexp to whitelist urls with.
  14809. * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for
  14810. * chaining otherwise.
  14811. */
  14812. this.imgSrcSanitizationWhitelist = function(regexp) {
  14813. if (isDefined(regexp)) {
  14814. imgSrcSanitizationWhitelist = regexp;
  14815. return this;
  14816. }
  14817. return imgSrcSanitizationWhitelist;
  14818. };
  14819. this.$get = function() {
  14820. return function sanitizeUri(uri, isImage) {
  14821. var regex = isImage ? imgSrcSanitizationWhitelist : aHrefSanitizationWhitelist;
  14822. var normalizedVal;
  14823. normalizedVal = urlResolve(uri).href;
  14824. if (normalizedVal !== '' && !normalizedVal.match(regex)) {
  14825. return 'unsafe:' + normalizedVal;
  14826. }
  14827. return uri;
  14828. };
  14829. };
  14830. }
  14831. /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
  14832. * Any commits to this file should be reviewed with security in mind. *
  14833. * Changes to this file can potentially create security vulnerabilities. *
  14834. * An approval from 2 Core members with history of modifying *
  14835. * this file is required. *
  14836. * *
  14837. * Does the change somehow allow for arbitrary javascript to be executed? *
  14838. * Or allows for someone to change the prototype of built-in objects? *
  14839. * Or gives undesired access to variables likes document or window? *
  14840. * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
  14841. var $sceMinErr = minErr('$sce');
  14842. var SCE_CONTEXTS = {
  14843. HTML: 'html',
  14844. CSS: 'css',
  14845. URL: 'url',
  14846. // RESOURCE_URL is a subtype of URL used in contexts where a privileged resource is sourced from a
  14847. // url. (e.g. ng-include, script src, templateUrl)
  14848. RESOURCE_URL: 'resourceUrl',
  14849. JS: 'js'
  14850. };
  14851. // Helper functions follow.
  14852. function adjustMatcher(matcher) {
  14853. if (matcher === 'self') {
  14854. return matcher;
  14855. } else if (isString(matcher)) {
  14856. // Strings match exactly except for 2 wildcards - '*' and '**'.
  14857. // '*' matches any character except those from the set ':/.?&'.
  14858. // '**' matches any character (like .* in a RegExp).
  14859. // More than 2 *'s raises an error as it's ill defined.
  14860. if (matcher.indexOf('***') > -1) {
  14861. throw $sceMinErr('iwcard',
  14862. 'Illegal sequence *** in string matcher. String: {0}', matcher);
  14863. }
  14864. matcher = escapeForRegexp(matcher).
  14865. replace('\\*\\*', '.*').
  14866. replace('\\*', '[^:/.?&;]*');
  14867. return new RegExp('^' + matcher + '$');
  14868. } else if (isRegExp(matcher)) {
  14869. // The only other type of matcher allowed is a Regexp.
  14870. // Match entire URL / disallow partial matches.
  14871. // Flags are reset (i.e. no global, ignoreCase or multiline)
  14872. return new RegExp('^' + matcher.source + '$');
  14873. } else {
  14874. throw $sceMinErr('imatcher',
  14875. 'Matchers may only be "self", string patterns or RegExp objects');
  14876. }
  14877. }
  14878. function adjustMatchers(matchers) {
  14879. var adjustedMatchers = [];
  14880. if (isDefined(matchers)) {
  14881. forEach(matchers, function(matcher) {
  14882. adjustedMatchers.push(adjustMatcher(matcher));
  14883. });
  14884. }
  14885. return adjustedMatchers;
  14886. }
  14887. /**
  14888. * @ngdoc service
  14889. * @name $sceDelegate
  14890. * @kind function
  14891. *
  14892. * @description
  14893. *
  14894. * `$sceDelegate` is a service that is used by the `$sce` service to provide {@link ng.$sce Strict
  14895. * Contextual Escaping (SCE)} services to AngularJS.
  14896. *
  14897. * Typically, you would configure or override the {@link ng.$sceDelegate $sceDelegate} instead of
  14898. * the `$sce` service to customize the way Strict Contextual Escaping works in AngularJS. This is
  14899. * because, while the `$sce` provides numerous shorthand methods, etc., you really only need to
  14900. * override 3 core functions (`trustAs`, `getTrusted` and `valueOf`) to replace the way things
  14901. * work because `$sce` delegates to `$sceDelegate` for these operations.
  14902. *
  14903. * Refer {@link ng.$sceDelegateProvider $sceDelegateProvider} to configure this service.
  14904. *
  14905. * The default instance of `$sceDelegate` should work out of the box with little pain. While you
  14906. * can override it completely to change the behavior of `$sce`, the common case would
  14907. * involve configuring the {@link ng.$sceDelegateProvider $sceDelegateProvider} instead by setting
  14908. * your own whitelists and blacklists for trusting URLs used for loading AngularJS resources such as
  14909. * templates. Refer {@link ng.$sceDelegateProvider#resourceUrlWhitelist
  14910. * $sceDelegateProvider.resourceUrlWhitelist} and {@link
  14911. * ng.$sceDelegateProvider#resourceUrlBlacklist $sceDelegateProvider.resourceUrlBlacklist}
  14912. */
  14913. /**
  14914. * @ngdoc provider
  14915. * @name $sceDelegateProvider
  14916. * @description
  14917. *
  14918. * The `$sceDelegateProvider` provider allows developers to configure the {@link ng.$sceDelegate
  14919. * $sceDelegate} service. This allows one to get/set the whitelists and blacklists used to ensure
  14920. * that the URLs used for sourcing Angular templates are safe. Refer {@link
  14921. * ng.$sceDelegateProvider#resourceUrlWhitelist $sceDelegateProvider.resourceUrlWhitelist} and
  14922. * {@link ng.$sceDelegateProvider#resourceUrlBlacklist $sceDelegateProvider.resourceUrlBlacklist}
  14923. *
  14924. * For the general details about this service in Angular, read the main page for {@link ng.$sce
  14925. * Strict Contextual Escaping (SCE)}.
  14926. *
  14927. * **Example**: Consider the following case. <a name="example"></a>
  14928. *
  14929. * - your app is hosted at url `http://myapp.example.com/`
  14930. * - but some of your templates are hosted on other domains you control such as
  14931. * `http://srv01.assets.example.com/`,  `http://srv02.assets.example.com/`, etc.
  14932. * - and you have an open redirect at `http://myapp.example.com/clickThru?...`.
  14933. *
  14934. * Here is what a secure configuration for this scenario might look like:
  14935. *
  14936. * ```
  14937. * angular.module('myApp', []).config(function($sceDelegateProvider) {
  14938. * $sceDelegateProvider.resourceUrlWhitelist([
  14939. * // Allow same origin resource loads.
  14940. * 'self',
  14941. * // Allow loading from our assets domain. Notice the difference between * and **.
  14942. * 'http://srv*.assets.example.com/**'
  14943. * ]);
  14944. *
  14945. * // The blacklist overrides the whitelist so the open redirect here is blocked.
  14946. * $sceDelegateProvider.resourceUrlBlacklist([
  14947. * 'http://myapp.example.com/clickThru**'
  14948. * ]);
  14949. * });
  14950. * ```
  14951. */
  14952. function $SceDelegateProvider() {
  14953. this.SCE_CONTEXTS = SCE_CONTEXTS;
  14954. // Resource URLs can also be trusted by policy.
  14955. var resourceUrlWhitelist = ['self'],
  14956. resourceUrlBlacklist = [];
  14957. /**
  14958. * @ngdoc method
  14959. * @name $sceDelegateProvider#resourceUrlWhitelist
  14960. * @kind function
  14961. *
  14962. * @param {Array=} whitelist When provided, replaces the resourceUrlWhitelist with the value
  14963. * provided. This must be an array or null. A snapshot of this array is used so further
  14964. * changes to the array are ignored.
  14965. *
  14966. * Follow {@link ng.$sce#resourceUrlPatternItem this link} for a description of the items
  14967. * allowed in this array.
  14968. *
  14969. * Note: **an empty whitelist array will block all URLs**!
  14970. *
  14971. * @return {Array} the currently set whitelist array.
  14972. *
  14973. * The **default value** when no whitelist has been explicitly set is `['self']` allowing only
  14974. * same origin resource requests.
  14975. *
  14976. * @description
  14977. * Sets/Gets the whitelist of trusted resource URLs.
  14978. */
  14979. this.resourceUrlWhitelist = function(value) {
  14980. if (arguments.length) {
  14981. resourceUrlWhitelist = adjustMatchers(value);
  14982. }
  14983. return resourceUrlWhitelist;
  14984. };
  14985. /**
  14986. * @ngdoc method
  14987. * @name $sceDelegateProvider#resourceUrlBlacklist
  14988. * @kind function
  14989. *
  14990. * @param {Array=} blacklist When provided, replaces the resourceUrlBlacklist with the value
  14991. * provided. This must be an array or null. A snapshot of this array is used so further
  14992. * changes to the array are ignored.
  14993. *
  14994. * Follow {@link ng.$sce#resourceUrlPatternItem this link} for a description of the items
  14995. * allowed in this array.
  14996. *
  14997. * The typical usage for the blacklist is to **block
  14998. * [open redirects](http://cwe.mitre.org/data/definitions/601.html)** served by your domain as
  14999. * these would otherwise be trusted but actually return content from the redirected domain.
  15000. *
  15001. * Finally, **the blacklist overrides the whitelist** and has the final say.
  15002. *
  15003. * @return {Array} the currently set blacklist array.
  15004. *
  15005. * The **default value** when no whitelist has been explicitly set is the empty array (i.e. there
  15006. * is no blacklist.)
  15007. *
  15008. * @description
  15009. * Sets/Gets the blacklist of trusted resource URLs.
  15010. */
  15011. this.resourceUrlBlacklist = function(value) {
  15012. if (arguments.length) {
  15013. resourceUrlBlacklist = adjustMatchers(value);
  15014. }
  15015. return resourceUrlBlacklist;
  15016. };
  15017. this.$get = ['$injector', function($injector) {
  15018. var htmlSanitizer = function htmlSanitizer(html) {
  15019. throw $sceMinErr('unsafe', 'Attempting to use an unsafe value in a safe context.');
  15020. };
  15021. if ($injector.has('$sanitize')) {
  15022. htmlSanitizer = $injector.get('$sanitize');
  15023. }
  15024. function matchUrl(matcher, parsedUrl) {
  15025. if (matcher === 'self') {
  15026. return urlIsSameOrigin(parsedUrl);
  15027. } else {
  15028. // definitely a regex. See adjustMatchers()
  15029. return !!matcher.exec(parsedUrl.href);
  15030. }
  15031. }
  15032. function isResourceUrlAllowedByPolicy(url) {
  15033. var parsedUrl = urlResolve(url.toString());
  15034. var i, n, allowed = false;
  15035. // Ensure that at least one item from the whitelist allows this url.
  15036. for (i = 0, n = resourceUrlWhitelist.length; i < n; i++) {
  15037. if (matchUrl(resourceUrlWhitelist[i], parsedUrl)) {
  15038. allowed = true;
  15039. break;
  15040. }
  15041. }
  15042. if (allowed) {
  15043. // Ensure that no item from the blacklist blocked this url.
  15044. for (i = 0, n = resourceUrlBlacklist.length; i < n; i++) {
  15045. if (matchUrl(resourceUrlBlacklist[i], parsedUrl)) {
  15046. allowed = false;
  15047. break;
  15048. }
  15049. }
  15050. }
  15051. return allowed;
  15052. }
  15053. function generateHolderType(Base) {
  15054. var holderType = function TrustedValueHolderType(trustedValue) {
  15055. this.$$unwrapTrustedValue = function() {
  15056. return trustedValue;
  15057. };
  15058. };
  15059. if (Base) {
  15060. holderType.prototype = new Base();
  15061. }
  15062. holderType.prototype.valueOf = function sceValueOf() {
  15063. return this.$$unwrapTrustedValue();
  15064. };
  15065. holderType.prototype.toString = function sceToString() {
  15066. return this.$$unwrapTrustedValue().toString();
  15067. };
  15068. return holderType;
  15069. }
  15070. var trustedValueHolderBase = generateHolderType(),
  15071. byType = {};
  15072. byType[SCE_CONTEXTS.HTML] = generateHolderType(trustedValueHolderBase);
  15073. byType[SCE_CONTEXTS.CSS] = generateHolderType(trustedValueHolderBase);
  15074. byType[SCE_CONTEXTS.URL] = generateHolderType(trustedValueHolderBase);
  15075. byType[SCE_CONTEXTS.JS] = generateHolderType(trustedValueHolderBase);
  15076. byType[SCE_CONTEXTS.RESOURCE_URL] = generateHolderType(byType[SCE_CONTEXTS.URL]);
  15077. /**
  15078. * @ngdoc method
  15079. * @name $sceDelegate#trustAs
  15080. *
  15081. * @description
  15082. * Returns an object that is trusted by angular for use in specified strict
  15083. * contextual escaping contexts (such as ng-bind-html, ng-include, any src
  15084. * attribute interpolation, any dom event binding attribute interpolation
  15085. * such as for onclick, etc.) that uses the provided value.
  15086. * See {@link ng.$sce $sce} for enabling strict contextual escaping.
  15087. *
  15088. * @param {string} type The kind of context in which this value is safe for use. e.g. url,
  15089. * resourceUrl, html, js and css.
  15090. * @param {*} value The value that that should be considered trusted/safe.
  15091. * @returns {*} A value that can be used to stand in for the provided `value` in places
  15092. * where Angular expects a $sce.trustAs() return value.
  15093. */
  15094. function trustAs(type, trustedValue) {
  15095. var Constructor = (byType.hasOwnProperty(type) ? byType[type] : null);
  15096. if (!Constructor) {
  15097. throw $sceMinErr('icontext',
  15098. 'Attempted to trust a value in invalid context. Context: {0}; Value: {1}',
  15099. type, trustedValue);
  15100. }
  15101. if (trustedValue === null || isUndefined(trustedValue) || trustedValue === '') {
  15102. return trustedValue;
  15103. }
  15104. // All the current contexts in SCE_CONTEXTS happen to be strings. In order to avoid trusting
  15105. // mutable objects, we ensure here that the value passed in is actually a string.
  15106. if (typeof trustedValue !== 'string') {
  15107. throw $sceMinErr('itype',
  15108. 'Attempted to trust a non-string value in a content requiring a string: Context: {0}',
  15109. type);
  15110. }
  15111. return new Constructor(trustedValue);
  15112. }
  15113. /**
  15114. * @ngdoc method
  15115. * @name $sceDelegate#valueOf
  15116. *
  15117. * @description
  15118. * If the passed parameter had been returned by a prior call to {@link ng.$sceDelegate#trustAs
  15119. * `$sceDelegate.trustAs`}, returns the value that had been passed to {@link
  15120. * ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}.
  15121. *
  15122. * If the passed parameter is not a value that had been returned by {@link
  15123. * ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}, returns it as-is.
  15124. *
  15125. * @param {*} value The result of a prior {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}
  15126. * call or anything else.
  15127. * @returns {*} The `value` that was originally provided to {@link ng.$sceDelegate#trustAs
  15128. * `$sceDelegate.trustAs`} if `value` is the result of such a call. Otherwise, returns
  15129. * `value` unchanged.
  15130. */
  15131. function valueOf(maybeTrusted) {
  15132. if (maybeTrusted instanceof trustedValueHolderBase) {
  15133. return maybeTrusted.$$unwrapTrustedValue();
  15134. } else {
  15135. return maybeTrusted;
  15136. }
  15137. }
  15138. /**
  15139. * @ngdoc method
  15140. * @name $sceDelegate#getTrusted
  15141. *
  15142. * @description
  15143. * Takes the result of a {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs`} call and
  15144. * returns the originally supplied value if the queried context type is a supertype of the
  15145. * created type. If this condition isn't satisfied, throws an exception.
  15146. *
  15147. * @param {string} type The kind of context in which this value is to be used.
  15148. * @param {*} maybeTrusted The result of a prior {@link ng.$sceDelegate#trustAs
  15149. * `$sceDelegate.trustAs`} call.
  15150. * @returns {*} The value the was originally provided to {@link ng.$sceDelegate#trustAs
  15151. * `$sceDelegate.trustAs`} if valid in this context. Otherwise, throws an exception.
  15152. */
  15153. function getTrusted(type, maybeTrusted) {
  15154. if (maybeTrusted === null || isUndefined(maybeTrusted) || maybeTrusted === '') {
  15155. return maybeTrusted;
  15156. }
  15157. var constructor = (byType.hasOwnProperty(type) ? byType[type] : null);
  15158. if (constructor && maybeTrusted instanceof constructor) {
  15159. return maybeTrusted.$$unwrapTrustedValue();
  15160. }
  15161. // If we get here, then we may only take one of two actions.
  15162. // 1. sanitize the value for the requested type, or
  15163. // 2. throw an exception.
  15164. if (type === SCE_CONTEXTS.RESOURCE_URL) {
  15165. if (isResourceUrlAllowedByPolicy(maybeTrusted)) {
  15166. return maybeTrusted;
  15167. } else {
  15168. throw $sceMinErr('insecurl',
  15169. 'Blocked loading resource from url not allowed by $sceDelegate policy. URL: {0}',
  15170. maybeTrusted.toString());
  15171. }
  15172. } else if (type === SCE_CONTEXTS.HTML) {
  15173. return htmlSanitizer(maybeTrusted);
  15174. }
  15175. throw $sceMinErr('unsafe', 'Attempting to use an unsafe value in a safe context.');
  15176. }
  15177. return { trustAs: trustAs,
  15178. getTrusted: getTrusted,
  15179. valueOf: valueOf };
  15180. }];
  15181. }
  15182. /**
  15183. * @ngdoc provider
  15184. * @name $sceProvider
  15185. * @description
  15186. *
  15187. * The $sceProvider provider allows developers to configure the {@link ng.$sce $sce} service.
  15188. * - enable/disable Strict Contextual Escaping (SCE) in a module
  15189. * - override the default implementation with a custom delegate
  15190. *
  15191. * Read more about {@link ng.$sce Strict Contextual Escaping (SCE)}.
  15192. */
  15193. /* jshint maxlen: false*/
  15194. /**
  15195. * @ngdoc service
  15196. * @name $sce
  15197. * @kind function
  15198. *
  15199. * @description
  15200. *
  15201. * `$sce` is a service that provides Strict Contextual Escaping services to AngularJS.
  15202. *
  15203. * # Strict Contextual Escaping
  15204. *
  15205. * Strict Contextual Escaping (SCE) is a mode in which AngularJS requires bindings in certain
  15206. * contexts to result in a value that is marked as safe to use for that context. One example of
  15207. * such a context is binding arbitrary html controlled by the user via `ng-bind-html`. We refer
  15208. * to these contexts as privileged or SCE contexts.
  15209. *
  15210. * As of version 1.2, Angular ships with SCE enabled by default.
  15211. *
  15212. * Note: When enabled (the default), IE<11 in quirks mode is not supported. In this mode, IE<11 allow
  15213. * one to execute arbitrary javascript by the use of the expression() syntax. Refer
  15214. * <http://blogs.msdn.com/b/ie/archive/2008/10/16/ending-expressions.aspx> to learn more about them.
  15215. * You can ensure your document is in standards mode and not quirks mode by adding `<!doctype html>`
  15216. * to the top of your HTML document.
  15217. *
  15218. * SCE assists in writing code in way that (a) is secure by default and (b) makes auditing for
  15219. * security vulnerabilities such as XSS, clickjacking, etc. a lot easier.
  15220. *
  15221. * Here's an example of a binding in a privileged context:
  15222. *
  15223. * ```
  15224. * <input ng-model="userHtml" aria-label="User input">
  15225. * <div ng-bind-html="userHtml"></div>
  15226. * ```
  15227. *
  15228. * Notice that `ng-bind-html` is bound to `userHtml` controlled by the user. With SCE
  15229. * disabled, this application allows the user to render arbitrary HTML into the DIV.
  15230. * In a more realistic example, one may be rendering user comments, blog articles, etc. via
  15231. * bindings. (HTML is just one example of a context where rendering user controlled input creates
  15232. * security vulnerabilities.)
  15233. *
  15234. * For the case of HTML, you might use a library, either on the client side, or on the server side,
  15235. * to sanitize unsafe HTML before binding to the value and rendering it in the document.
  15236. *
  15237. * How would you ensure that every place that used these types of bindings was bound to a value that
  15238. * was sanitized by your library (or returned as safe for rendering by your server?) How can you
  15239. * ensure that you didn't accidentally delete the line that sanitized the value, or renamed some
  15240. * properties/fields and forgot to update the binding to the sanitized value?
  15241. *
  15242. * To be secure by default, you want to ensure that any such bindings are disallowed unless you can
  15243. * determine that something explicitly says it's safe to use a value for binding in that
  15244. * context. You can then audit your code (a simple grep would do) to ensure that this is only done
  15245. * for those values that you can easily tell are safe - because they were received from your server,
  15246. * sanitized by your library, etc. You can organize your codebase to help with this - perhaps
  15247. * allowing only the files in a specific directory to do this. Ensuring that the internal API
  15248. * exposed by that code doesn't markup arbitrary values as safe then becomes a more manageable task.
  15249. *
  15250. * In the case of AngularJS' SCE service, one uses {@link ng.$sce#trustAs $sce.trustAs}
  15251. * (and shorthand methods such as {@link ng.$sce#trustAsHtml $sce.trustAsHtml}, etc.) to
  15252. * obtain values that will be accepted by SCE / privileged contexts.
  15253. *
  15254. *
  15255. * ## How does it work?
  15256. *
  15257. * In privileged contexts, directives and code will bind to the result of {@link ng.$sce#getTrusted
  15258. * $sce.getTrusted(context, value)} rather than to the value directly. Directives use {@link
  15259. * ng.$sce#parseAs $sce.parseAs} rather than `$parse` to watch attribute bindings, which performs the
  15260. * {@link ng.$sce#getTrusted $sce.getTrusted} behind the scenes on non-constant literals.
  15261. *
  15262. * As an example, {@link ng.directive:ngBindHtml ngBindHtml} uses {@link
  15263. * ng.$sce#parseAsHtml $sce.parseAsHtml(binding expression)}. Here's the actual code (slightly
  15264. * simplified):
  15265. *
  15266. * ```
  15267. * var ngBindHtmlDirective = ['$sce', function($sce) {
  15268. * return function(scope, element, attr) {
  15269. * scope.$watch($sce.parseAsHtml(attr.ngBindHtml), function(value) {
  15270. * element.html(value || '');
  15271. * });
  15272. * };
  15273. * }];
  15274. * ```
  15275. *
  15276. * ## Impact on loading templates
  15277. *
  15278. * This applies both to the {@link ng.directive:ngInclude `ng-include`} directive as well as
  15279. * `templateUrl`'s specified by {@link guide/directive directives}.
  15280. *
  15281. * By default, Angular only loads templates from the same domain and protocol as the application
  15282. * document. This is done by calling {@link ng.$sce#getTrustedResourceUrl
  15283. * $sce.getTrustedResourceUrl} on the template URL. To load templates from other domains and/or
  15284. * protocols, you may either either {@link ng.$sceDelegateProvider#resourceUrlWhitelist whitelist
  15285. * them} or {@link ng.$sce#trustAsResourceUrl wrap it} into a trusted value.
  15286. *
  15287. * *Please note*:
  15288. * The browser's
  15289. * [Same Origin Policy](https://code.google.com/p/browsersec/wiki/Part2#Same-origin_policy_for_XMLHttpRequest)
  15290. * and [Cross-Origin Resource Sharing (CORS)](http://www.w3.org/TR/cors/)
  15291. * policy apply in addition to this and may further restrict whether the template is successfully
  15292. * loaded. This means that without the right CORS policy, loading templates from a different domain
  15293. * won't work on all browsers. Also, loading templates from `file://` URL does not work on some
  15294. * browsers.
  15295. *
  15296. * ## This feels like too much overhead
  15297. *
  15298. * It's important to remember that SCE only applies to interpolation expressions.
  15299. *
  15300. * If your expressions are constant literals, they're automatically trusted and you don't need to
  15301. * call `$sce.trustAs` on them (remember to include the `ngSanitize` module) (e.g.
  15302. * `<div ng-bind-html="'<b>implicitly trusted</b>'"></div>`) just works.
  15303. *
  15304. * Additionally, `a[href]` and `img[src]` automatically sanitize their URLs and do not pass them
  15305. * through {@link ng.$sce#getTrusted $sce.getTrusted}. SCE doesn't play a role here.
  15306. *
  15307. * The included {@link ng.$sceDelegate $sceDelegate} comes with sane defaults to allow you to load
  15308. * templates in `ng-include` from your application's domain without having to even know about SCE.
  15309. * It blocks loading templates from other domains or loading templates over http from an https
  15310. * served document. You can change these by setting your own custom {@link
  15311. * ng.$sceDelegateProvider#resourceUrlWhitelist whitelists} and {@link
  15312. * ng.$sceDelegateProvider#resourceUrlBlacklist blacklists} for matching such URLs.
  15313. *
  15314. * This significantly reduces the overhead. It is far easier to pay the small overhead and have an
  15315. * application that's secure and can be audited to verify that with much more ease than bolting
  15316. * security onto an application later.
  15317. *
  15318. * <a name="contexts"></a>
  15319. * ## What trusted context types are supported?
  15320. *
  15321. * | Context | Notes |
  15322. * |---------------------|----------------|
  15323. * | `$sce.HTML` | For HTML that's safe to source into the application. The {@link ng.directive:ngBindHtml ngBindHtml} directive uses this context for bindings. If an unsafe value is encountered and the {@link ngSanitize $sanitize} module is present this will sanitize the value instead of throwing an error. |
  15324. * | `$sce.CSS` | For CSS that's safe to source into the application. Currently unused. Feel free to use it in your own directives. |
  15325. * | `$sce.URL` | For URLs that are safe to follow as links. Currently unused (`<a href=` and `<img src=` sanitize their urls and don't constitute an SCE context. |
  15326. * | `$sce.RESOURCE_URL` | For URLs that are not only safe to follow as links, but whose contents are also safe to include in your application. Examples include `ng-include`, `src` / `ngSrc` bindings for tags other than `IMG` (e.g. `IFRAME`, `OBJECT`, etc.) <br><br>Note that `$sce.RESOURCE_URL` makes a stronger statement about the URL than `$sce.URL` does and therefore contexts requiring values trusted for `$sce.RESOURCE_URL` can be used anywhere that values trusted for `$sce.URL` are required. |
  15327. * | `$sce.JS` | For JavaScript that is safe to execute in your application's context. Currently unused. Feel free to use it in your own directives. |
  15328. *
  15329. * ## Format of items in {@link ng.$sceDelegateProvider#resourceUrlWhitelist resourceUrlWhitelist}/{@link ng.$sceDelegateProvider#resourceUrlBlacklist Blacklist} <a name="resourceUrlPatternItem"></a>
  15330. *
  15331. * Each element in these arrays must be one of the following:
  15332. *
  15333. * - **'self'**
  15334. * - The special **string**, `'self'`, can be used to match against all URLs of the **same
  15335. * domain** as the application document using the **same protocol**.
  15336. * - **String** (except the special value `'self'`)
  15337. * - The string is matched against the full *normalized / absolute URL* of the resource
  15338. * being tested (substring matches are not good enough.)
  15339. * - There are exactly **two wildcard sequences** - `*` and `**`. All other characters
  15340. * match themselves.
  15341. * - `*`: matches zero or more occurrences of any character other than one of the following 6
  15342. * characters: '`:`', '`/`', '`.`', '`?`', '`&`' and '`;`'. It's a useful wildcard for use
  15343. * in a whitelist.
  15344. * - `**`: matches zero or more occurrences of *any* character. As such, it's not
  15345. * appropriate for use in a scheme, domain, etc. as it would match too much. (e.g.
  15346. * http://**.example.com/ would match http://evil.com/?ignore=.example.com/ and that might
  15347. * not have been the intention.) Its usage at the very end of the path is ok. (e.g.
  15348. * http://foo.example.com/templates/**).
  15349. * - **RegExp** (*see caveat below*)
  15350. * - *Caveat*: While regular expressions are powerful and offer great flexibility, their syntax
  15351. * (and all the inevitable escaping) makes them *harder to maintain*. It's easy to
  15352. * accidentally introduce a bug when one updates a complex expression (imho, all regexes should
  15353. * have good test coverage). For instance, the use of `.` in the regex is correct only in a
  15354. * small number of cases. A `.` character in the regex used when matching the scheme or a
  15355. * subdomain could be matched against a `:` or literal `.` that was likely not intended. It
  15356. * is highly recommended to use the string patterns and only fall back to regular expressions
  15357. * as a last resort.
  15358. * - The regular expression must be an instance of RegExp (i.e. not a string.) It is
  15359. * matched against the **entire** *normalized / absolute URL* of the resource being tested
  15360. * (even when the RegExp did not have the `^` and `$` codes.) In addition, any flags
  15361. * present on the RegExp (such as multiline, global, ignoreCase) are ignored.
  15362. * - If you are generating your JavaScript from some other templating engine (not
  15363. * recommended, e.g. in issue [#4006](https://github.com/angular/angular.js/issues/4006)),
  15364. * remember to escape your regular expression (and be aware that you might need more than
  15365. * one level of escaping depending on your templating engine and the way you interpolated
  15366. * the value.) Do make use of your platform's escaping mechanism as it might be good
  15367. * enough before coding your own. E.g. Ruby has
  15368. * [Regexp.escape(str)](http://www.ruby-doc.org/core-2.0.0/Regexp.html#method-c-escape)
  15369. * and Python has [re.escape](http://docs.python.org/library/re.html#re.escape).
  15370. * Javascript lacks a similar built in function for escaping. Take a look at Google
  15371. * Closure library's [goog.string.regExpEscape(s)](
  15372. * http://docs.closure-library.googlecode.com/git/closure_goog_string_string.js.source.html#line962).
  15373. *
  15374. * Refer {@link ng.$sceDelegateProvider $sceDelegateProvider} for an example.
  15375. *
  15376. * ## Show me an example using SCE.
  15377. *
  15378. * <example module="mySceApp" deps="angular-sanitize.js">
  15379. * <file name="index.html">
  15380. * <div ng-controller="AppController as myCtrl">
  15381. * <i ng-bind-html="myCtrl.explicitlyTrustedHtml" id="explicitlyTrustedHtml"></i><br><br>
  15382. * <b>User comments</b><br>
  15383. * By default, HTML that isn't explicitly trusted (e.g. Alice's comment) is sanitized when
  15384. * $sanitize is available. If $sanitize isn't available, this results in an error instead of an
  15385. * exploit.
  15386. * <div class="well">
  15387. * <div ng-repeat="userComment in myCtrl.userComments">
  15388. * <b>{{userComment.name}}</b>:
  15389. * <span ng-bind-html="userComment.htmlComment" class="htmlComment"></span>
  15390. * <br>
  15391. * </div>
  15392. * </div>
  15393. * </div>
  15394. * </file>
  15395. *
  15396. * <file name="script.js">
  15397. * angular.module('mySceApp', ['ngSanitize'])
  15398. * .controller('AppController', ['$http', '$templateCache', '$sce',
  15399. * function($http, $templateCache, $sce) {
  15400. * var self = this;
  15401. * $http.get("test_data.json", {cache: $templateCache}).success(function(userComments) {
  15402. * self.userComments = userComments;
  15403. * });
  15404. * self.explicitlyTrustedHtml = $sce.trustAsHtml(
  15405. * '<span onmouseover="this.textContent=&quot;Explicitly trusted HTML bypasses ' +
  15406. * 'sanitization.&quot;">Hover over this text.</span>');
  15407. * }]);
  15408. * </file>
  15409. *
  15410. * <file name="test_data.json">
  15411. * [
  15412. * { "name": "Alice",
  15413. * "htmlComment":
  15414. * "<span onmouseover='this.textContent=\"PWN3D!\"'>Is <i>anyone</i> reading this?</span>"
  15415. * },
  15416. * { "name": "Bob",
  15417. * "htmlComment": "<i>Yes!</i> Am I the only other one?"
  15418. * }
  15419. * ]
  15420. * </file>
  15421. *
  15422. * <file name="protractor.js" type="protractor">
  15423. * describe('SCE doc demo', function() {
  15424. * it('should sanitize untrusted values', function() {
  15425. * expect(element.all(by.css('.htmlComment')).first().getInnerHtml())
  15426. * .toBe('<span>Is <i>anyone</i> reading this?</span>');
  15427. * });
  15428. *
  15429. * it('should NOT sanitize explicitly trusted values', function() {
  15430. * expect(element(by.id('explicitlyTrustedHtml')).getInnerHtml()).toBe(
  15431. * '<span onmouseover="this.textContent=&quot;Explicitly trusted HTML bypasses ' +
  15432. * 'sanitization.&quot;">Hover over this text.</span>');
  15433. * });
  15434. * });
  15435. * </file>
  15436. * </example>
  15437. *
  15438. *
  15439. *
  15440. * ## Can I disable SCE completely?
  15441. *
  15442. * Yes, you can. However, this is strongly discouraged. SCE gives you a lot of security benefits
  15443. * for little coding overhead. It will be much harder to take an SCE disabled application and
  15444. * either secure it on your own or enable SCE at a later stage. It might make sense to disable SCE
  15445. * for cases where you have a lot of existing code that was written before SCE was introduced and
  15446. * you're migrating them a module at a time.
  15447. *
  15448. * That said, here's how you can completely disable SCE:
  15449. *
  15450. * ```
  15451. * angular.module('myAppWithSceDisabledmyApp', []).config(function($sceProvider) {
  15452. * // Completely disable SCE. For demonstration purposes only!
  15453. * // Do not use in new projects.
  15454. * $sceProvider.enabled(false);
  15455. * });
  15456. * ```
  15457. *
  15458. */
  15459. /* jshint maxlen: 100 */
  15460. function $SceProvider() {
  15461. var enabled = true;
  15462. /**
  15463. * @ngdoc method
  15464. * @name $sceProvider#enabled
  15465. * @kind function
  15466. *
  15467. * @param {boolean=} value If provided, then enables/disables SCE.
  15468. * @return {boolean} true if SCE is enabled, false otherwise.
  15469. *
  15470. * @description
  15471. * Enables/disables SCE and returns the current value.
  15472. */
  15473. this.enabled = function(value) {
  15474. if (arguments.length) {
  15475. enabled = !!value;
  15476. }
  15477. return enabled;
  15478. };
  15479. /* Design notes on the default implementation for SCE.
  15480. *
  15481. * The API contract for the SCE delegate
  15482. * -------------------------------------
  15483. * The SCE delegate object must provide the following 3 methods:
  15484. *
  15485. * - trustAs(contextEnum, value)
  15486. * This method is used to tell the SCE service that the provided value is OK to use in the
  15487. * contexts specified by contextEnum. It must return an object that will be accepted by
  15488. * getTrusted() for a compatible contextEnum and return this value.
  15489. *
  15490. * - valueOf(value)
  15491. * For values that were not produced by trustAs(), return them as is. For values that were
  15492. * produced by trustAs(), return the corresponding input value to trustAs. Basically, if
  15493. * trustAs is wrapping the given values into some type, this operation unwraps it when given
  15494. * such a value.
  15495. *
  15496. * - getTrusted(contextEnum, value)
  15497. * This function should return the a value that is safe to use in the context specified by
  15498. * contextEnum or throw and exception otherwise.
  15499. *
  15500. * NOTE: This contract deliberately does NOT state that values returned by trustAs() must be
  15501. * opaque or wrapped in some holder object. That happens to be an implementation detail. For
  15502. * instance, an implementation could maintain a registry of all trusted objects by context. In
  15503. * such a case, trustAs() would return the same object that was passed in. getTrusted() would
  15504. * return the same object passed in if it was found in the registry under a compatible context or
  15505. * throw an exception otherwise. An implementation might only wrap values some of the time based
  15506. * on some criteria. getTrusted() might return a value and not throw an exception for special
  15507. * constants or objects even if not wrapped. All such implementations fulfill this contract.
  15508. *
  15509. *
  15510. * A note on the inheritance model for SCE contexts
  15511. * ------------------------------------------------
  15512. * I've used inheritance and made RESOURCE_URL wrapped types a subtype of URL wrapped types. This
  15513. * is purely an implementation details.
  15514. *
  15515. * The contract is simply this:
  15516. *
  15517. * getTrusted($sce.RESOURCE_URL, value) succeeding implies that getTrusted($sce.URL, value)
  15518. * will also succeed.
  15519. *
  15520. * Inheritance happens to capture this in a natural way. In some future, we
  15521. * may not use inheritance anymore. That is OK because no code outside of
  15522. * sce.js and sceSpecs.js would need to be aware of this detail.
  15523. */
  15524. this.$get = ['$parse', '$sceDelegate', function(
  15525. $parse, $sceDelegate) {
  15526. // Prereq: Ensure that we're not running in IE<11 quirks mode. In that mode, IE < 11 allow
  15527. // the "expression(javascript expression)" syntax which is insecure.
  15528. if (enabled && msie < 8) {
  15529. throw $sceMinErr('iequirks',
  15530. 'Strict Contextual Escaping does not support Internet Explorer version < 11 in quirks ' +
  15531. 'mode. You can fix this by adding the text <!doctype html> to the top of your HTML ' +
  15532. 'document. See http://docs.angularjs.org/api/ng.$sce for more information.');
  15533. }
  15534. var sce = shallowCopy(SCE_CONTEXTS);
  15535. /**
  15536. * @ngdoc method
  15537. * @name $sce#isEnabled
  15538. * @kind function
  15539. *
  15540. * @return {Boolean} true if SCE is enabled, false otherwise. If you want to set the value, you
  15541. * have to do it at module config time on {@link ng.$sceProvider $sceProvider}.
  15542. *
  15543. * @description
  15544. * Returns a boolean indicating if SCE is enabled.
  15545. */
  15546. sce.isEnabled = function() {
  15547. return enabled;
  15548. };
  15549. sce.trustAs = $sceDelegate.trustAs;
  15550. sce.getTrusted = $sceDelegate.getTrusted;
  15551. sce.valueOf = $sceDelegate.valueOf;
  15552. if (!enabled) {
  15553. sce.trustAs = sce.getTrusted = function(type, value) { return value; };
  15554. sce.valueOf = identity;
  15555. }
  15556. /**
  15557. * @ngdoc method
  15558. * @name $sce#parseAs
  15559. *
  15560. * @description
  15561. * Converts Angular {@link guide/expression expression} into a function. This is like {@link
  15562. * ng.$parse $parse} and is identical when the expression is a literal constant. Otherwise, it
  15563. * wraps the expression in a call to {@link ng.$sce#getTrusted $sce.getTrusted(*type*,
  15564. * *result*)}
  15565. *
  15566. * @param {string} type The kind of SCE context in which this result will be used.
  15567. * @param {string} expression String expression to compile.
  15568. * @returns {function(context, locals)} a function which represents the compiled expression:
  15569. *
  15570. * * `context` – `{object}` – an object against which any expressions embedded in the strings
  15571. * are evaluated against (typically a scope object).
  15572. * * `locals` – `{object=}` – local variables context object, useful for overriding values in
  15573. * `context`.
  15574. */
  15575. sce.parseAs = function sceParseAs(type, expr) {
  15576. var parsed = $parse(expr);
  15577. if (parsed.literal && parsed.constant) {
  15578. return parsed;
  15579. } else {
  15580. return $parse(expr, function(value) {
  15581. return sce.getTrusted(type, value);
  15582. });
  15583. }
  15584. };
  15585. /**
  15586. * @ngdoc method
  15587. * @name $sce#trustAs
  15588. *
  15589. * @description
  15590. * Delegates to {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}. As such,
  15591. * returns an object that is trusted by angular for use in specified strict contextual
  15592. * escaping contexts (such as ng-bind-html, ng-include, any src attribute
  15593. * interpolation, any dom event binding attribute interpolation such as for onclick, etc.)
  15594. * that uses the provided value. See * {@link ng.$sce $sce} for enabling strict contextual
  15595. * escaping.
  15596. *
  15597. * @param {string} type The kind of context in which this value is safe for use. e.g. url,
  15598. * resourceUrl, html, js and css.
  15599. * @param {*} value The value that that should be considered trusted/safe.
  15600. * @returns {*} A value that can be used to stand in for the provided `value` in places
  15601. * where Angular expects a $sce.trustAs() return value.
  15602. */
  15603. /**
  15604. * @ngdoc method
  15605. * @name $sce#trustAsHtml
  15606. *
  15607. * @description
  15608. * Shorthand method. `$sce.trustAsHtml(value)` →
  15609. * {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.HTML, value)`}
  15610. *
  15611. * @param {*} value The value to trustAs.
  15612. * @returns {*} An object that can be passed to {@link ng.$sce#getTrustedHtml
  15613. * $sce.getTrustedHtml(value)} to obtain the original value. (privileged directives
  15614. * only accept expressions that are either literal constants or are the
  15615. * return value of {@link ng.$sce#trustAs $sce.trustAs}.)
  15616. */
  15617. /**
  15618. * @ngdoc method
  15619. * @name $sce#trustAsUrl
  15620. *
  15621. * @description
  15622. * Shorthand method. `$sce.trustAsUrl(value)` →
  15623. * {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.URL, value)`}
  15624. *
  15625. * @param {*} value The value to trustAs.
  15626. * @returns {*} An object that can be passed to {@link ng.$sce#getTrustedUrl
  15627. * $sce.getTrustedUrl(value)} to obtain the original value. (privileged directives
  15628. * only accept expressions that are either literal constants or are the
  15629. * return value of {@link ng.$sce#trustAs $sce.trustAs}.)
  15630. */
  15631. /**
  15632. * @ngdoc method
  15633. * @name $sce#trustAsResourceUrl
  15634. *
  15635. * @description
  15636. * Shorthand method. `$sce.trustAsResourceUrl(value)` →
  15637. * {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.RESOURCE_URL, value)`}
  15638. *
  15639. * @param {*} value The value to trustAs.
  15640. * @returns {*} An object that can be passed to {@link ng.$sce#getTrustedResourceUrl
  15641. * $sce.getTrustedResourceUrl(value)} to obtain the original value. (privileged directives
  15642. * only accept expressions that are either literal constants or are the return
  15643. * value of {@link ng.$sce#trustAs $sce.trustAs}.)
  15644. */
  15645. /**
  15646. * @ngdoc method
  15647. * @name $sce#trustAsJs
  15648. *
  15649. * @description
  15650. * Shorthand method. `$sce.trustAsJs(value)` →
  15651. * {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.JS, value)`}
  15652. *
  15653. * @param {*} value The value to trustAs.
  15654. * @returns {*} An object that can be passed to {@link ng.$sce#getTrustedJs
  15655. * $sce.getTrustedJs(value)} to obtain the original value. (privileged directives
  15656. * only accept expressions that are either literal constants or are the
  15657. * return value of {@link ng.$sce#trustAs $sce.trustAs}.)
  15658. */
  15659. /**
  15660. * @ngdoc method
  15661. * @name $sce#getTrusted
  15662. *
  15663. * @description
  15664. * Delegates to {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted`}. As such,
  15665. * takes the result of a {@link ng.$sce#trustAs `$sce.trustAs`}() call and returns the
  15666. * originally supplied value if the queried context type is a supertype of the created type.
  15667. * If this condition isn't satisfied, throws an exception.
  15668. *
  15669. * @param {string} type The kind of context in which this value is to be used.
  15670. * @param {*} maybeTrusted The result of a prior {@link ng.$sce#trustAs `$sce.trustAs`}
  15671. * call.
  15672. * @returns {*} The value the was originally provided to
  15673. * {@link ng.$sce#trustAs `$sce.trustAs`} if valid in this context.
  15674. * Otherwise, throws an exception.
  15675. */
  15676. /**
  15677. * @ngdoc method
  15678. * @name $sce#getTrustedHtml
  15679. *
  15680. * @description
  15681. * Shorthand method. `$sce.getTrustedHtml(value)` →
  15682. * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.HTML, value)`}
  15683. *
  15684. * @param {*} value The value to pass to `$sce.getTrusted`.
  15685. * @returns {*} The return value of `$sce.getTrusted($sce.HTML, value)`
  15686. */
  15687. /**
  15688. * @ngdoc method
  15689. * @name $sce#getTrustedCss
  15690. *
  15691. * @description
  15692. * Shorthand method. `$sce.getTrustedCss(value)` →
  15693. * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.CSS, value)`}
  15694. *
  15695. * @param {*} value The value to pass to `$sce.getTrusted`.
  15696. * @returns {*} The return value of `$sce.getTrusted($sce.CSS, value)`
  15697. */
  15698. /**
  15699. * @ngdoc method
  15700. * @name $sce#getTrustedUrl
  15701. *
  15702. * @description
  15703. * Shorthand method. `$sce.getTrustedUrl(value)` →
  15704. * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.URL, value)`}
  15705. *
  15706. * @param {*} value The value to pass to `$sce.getTrusted`.
  15707. * @returns {*} The return value of `$sce.getTrusted($sce.URL, value)`
  15708. */
  15709. /**
  15710. * @ngdoc method
  15711. * @name $sce#getTrustedResourceUrl
  15712. *
  15713. * @description
  15714. * Shorthand method. `$sce.getTrustedResourceUrl(value)` →
  15715. * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.RESOURCE_URL, value)`}
  15716. *
  15717. * @param {*} value The value to pass to `$sceDelegate.getTrusted`.
  15718. * @returns {*} The return value of `$sce.getTrusted($sce.RESOURCE_URL, value)`
  15719. */
  15720. /**
  15721. * @ngdoc method
  15722. * @name $sce#getTrustedJs
  15723. *
  15724. * @description
  15725. * Shorthand method. `$sce.getTrustedJs(value)` →
  15726. * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.JS, value)`}
  15727. *
  15728. * @param {*} value The value to pass to `$sce.getTrusted`.
  15729. * @returns {*} The return value of `$sce.getTrusted($sce.JS, value)`
  15730. */
  15731. /**
  15732. * @ngdoc method
  15733. * @name $sce#parseAsHtml
  15734. *
  15735. * @description
  15736. * Shorthand method. `$sce.parseAsHtml(expression string)` →
  15737. * {@link ng.$sce#parseAs `$sce.parseAs($sce.HTML, value)`}
  15738. *
  15739. * @param {string} expression String expression to compile.
  15740. * @returns {function(context, locals)} a function which represents the compiled expression:
  15741. *
  15742. * * `context` – `{object}` – an object against which any expressions embedded in the strings
  15743. * are evaluated against (typically a scope object).
  15744. * * `locals` – `{object=}` – local variables context object, useful for overriding values in
  15745. * `context`.
  15746. */
  15747. /**
  15748. * @ngdoc method
  15749. * @name $sce#parseAsCss
  15750. *
  15751. * @description
  15752. * Shorthand method. `$sce.parseAsCss(value)` →
  15753. * {@link ng.$sce#parseAs `$sce.parseAs($sce.CSS, value)`}
  15754. *
  15755. * @param {string} expression String expression to compile.
  15756. * @returns {function(context, locals)} a function which represents the compiled expression:
  15757. *
  15758. * * `context` – `{object}` – an object against which any expressions embedded in the strings
  15759. * are evaluated against (typically a scope object).
  15760. * * `locals` – `{object=}` – local variables context object, useful for overriding values in
  15761. * `context`.
  15762. */
  15763. /**
  15764. * @ngdoc method
  15765. * @name $sce#parseAsUrl
  15766. *
  15767. * @description
  15768. * Shorthand method. `$sce.parseAsUrl(value)` →
  15769. * {@link ng.$sce#parseAs `$sce.parseAs($sce.URL, value)`}
  15770. *
  15771. * @param {string} expression String expression to compile.
  15772. * @returns {function(context, locals)} a function which represents the compiled expression:
  15773. *
  15774. * * `context` – `{object}` – an object against which any expressions embedded in the strings
  15775. * are evaluated against (typically a scope object).
  15776. * * `locals` – `{object=}` – local variables context object, useful for overriding values in
  15777. * `context`.
  15778. */
  15779. /**
  15780. * @ngdoc method
  15781. * @name $sce#parseAsResourceUrl
  15782. *
  15783. * @description
  15784. * Shorthand method. `$sce.parseAsResourceUrl(value)` →
  15785. * {@link ng.$sce#parseAs `$sce.parseAs($sce.RESOURCE_URL, value)`}
  15786. *
  15787. * @param {string} expression String expression to compile.
  15788. * @returns {function(context, locals)} a function which represents the compiled expression:
  15789. *
  15790. * * `context` – `{object}` – an object against which any expressions embedded in the strings
  15791. * are evaluated against (typically a scope object).
  15792. * * `locals` – `{object=}` – local variables context object, useful for overriding values in
  15793. * `context`.
  15794. */
  15795. /**
  15796. * @ngdoc method
  15797. * @name $sce#parseAsJs
  15798. *
  15799. * @description
  15800. * Shorthand method. `$sce.parseAsJs(value)` →
  15801. * {@link ng.$sce#parseAs `$sce.parseAs($sce.JS, value)`}
  15802. *
  15803. * @param {string} expression String expression to compile.
  15804. * @returns {function(context, locals)} a function which represents the compiled expression:
  15805. *
  15806. * * `context` – `{object}` – an object against which any expressions embedded in the strings
  15807. * are evaluated against (typically a scope object).
  15808. * * `locals` – `{object=}` – local variables context object, useful for overriding values in
  15809. * `context`.
  15810. */
  15811. // Shorthand delegations.
  15812. var parse = sce.parseAs,
  15813. getTrusted = sce.getTrusted,
  15814. trustAs = sce.trustAs;
  15815. forEach(SCE_CONTEXTS, function(enumValue, name) {
  15816. var lName = lowercase(name);
  15817. sce[camelCase("parse_as_" + lName)] = function(expr) {
  15818. return parse(enumValue, expr);
  15819. };
  15820. sce[camelCase("get_trusted_" + lName)] = function(value) {
  15821. return getTrusted(enumValue, value);
  15822. };
  15823. sce[camelCase("trust_as_" + lName)] = function(value) {
  15824. return trustAs(enumValue, value);
  15825. };
  15826. });
  15827. return sce;
  15828. }];
  15829. }
  15830. /**
  15831. * !!! This is an undocumented "private" service !!!
  15832. *
  15833. * @name $sniffer
  15834. * @requires $window
  15835. * @requires $document
  15836. *
  15837. * @property {boolean} history Does the browser support html5 history api ?
  15838. * @property {boolean} transitions Does the browser support CSS transition events ?
  15839. * @property {boolean} animations Does the browser support CSS animation events ?
  15840. *
  15841. * @description
  15842. * This is very simple implementation of testing browser's features.
  15843. */
  15844. function $SnifferProvider() {
  15845. this.$get = ['$window', '$document', function($window, $document) {
  15846. var eventSupport = {},
  15847. android =
  15848. toInt((/android (\d+)/.exec(lowercase(($window.navigator || {}).userAgent)) || [])[1]),
  15849. boxee = /Boxee/i.test(($window.navigator || {}).userAgent),
  15850. document = $document[0] || {},
  15851. vendorPrefix,
  15852. vendorRegex = /^(Moz|webkit|ms)(?=[A-Z])/,
  15853. bodyStyle = document.body && document.body.style,
  15854. transitions = false,
  15855. animations = false,
  15856. match;
  15857. if (bodyStyle) {
  15858. for (var prop in bodyStyle) {
  15859. if (match = vendorRegex.exec(prop)) {
  15860. vendorPrefix = match[0];
  15861. vendorPrefix = vendorPrefix.substr(0, 1).toUpperCase() + vendorPrefix.substr(1);
  15862. break;
  15863. }
  15864. }
  15865. if (!vendorPrefix) {
  15866. vendorPrefix = ('WebkitOpacity' in bodyStyle) && 'webkit';
  15867. }
  15868. transitions = !!(('transition' in bodyStyle) || (vendorPrefix + 'Transition' in bodyStyle));
  15869. animations = !!(('animation' in bodyStyle) || (vendorPrefix + 'Animation' in bodyStyle));
  15870. if (android && (!transitions || !animations)) {
  15871. transitions = isString(bodyStyle.webkitTransition);
  15872. animations = isString(bodyStyle.webkitAnimation);
  15873. }
  15874. }
  15875. return {
  15876. // Android has history.pushState, but it does not update location correctly
  15877. // so let's not use the history API at all.
  15878. // http://code.google.com/p/android/issues/detail?id=17471
  15879. // https://github.com/angular/angular.js/issues/904
  15880. // older webkit browser (533.9) on Boxee box has exactly the same problem as Android has
  15881. // so let's not use the history API also
  15882. // We are purposefully using `!(android < 4)` to cover the case when `android` is undefined
  15883. // jshint -W018
  15884. history: !!($window.history && $window.history.pushState && !(android < 4) && !boxee),
  15885. // jshint +W018
  15886. hasEvent: function(event) {
  15887. // IE9 implements 'input' event it's so fubared that we rather pretend that it doesn't have
  15888. // it. In particular the event is not fired when backspace or delete key are pressed or
  15889. // when cut operation is performed.
  15890. // IE10+ implements 'input' event but it erroneously fires under various situations,
  15891. // e.g. when placeholder changes, or a form is focused.
  15892. if (event === 'input' && msie <= 11) return false;
  15893. if (isUndefined(eventSupport[event])) {
  15894. var divElm = document.createElement('div');
  15895. eventSupport[event] = 'on' + event in divElm;
  15896. }
  15897. return eventSupport[event];
  15898. },
  15899. csp: csp(),
  15900. vendorPrefix: vendorPrefix,
  15901. transitions: transitions,
  15902. animations: animations,
  15903. android: android
  15904. };
  15905. }];
  15906. }
  15907. var $compileMinErr = minErr('$compile');
  15908. /**
  15909. * @ngdoc service
  15910. * @name $templateRequest
  15911. *
  15912. * @description
  15913. * The `$templateRequest` service runs security checks then downloads the provided template using
  15914. * `$http` and, upon success, stores the contents inside of `$templateCache`. If the HTTP request
  15915. * fails or the response data of the HTTP request is empty, a `$compile` error will be thrown (the
  15916. * exception can be thwarted by setting the 2nd parameter of the function to true). Note that the
  15917. * contents of `$templateCache` are trusted, so the call to `$sce.getTrustedUrl(tpl)` is omitted
  15918. * when `tpl` is of type string and `$templateCache` has the matching entry.
  15919. *
  15920. * @param {string|TrustedResourceUrl} tpl The HTTP request template URL
  15921. * @param {boolean=} ignoreRequestError Whether or not to ignore the exception when the request fails or the template is empty
  15922. *
  15923. * @return {Promise} a promise for the HTTP response data of the given URL.
  15924. *
  15925. * @property {number} totalPendingRequests total amount of pending template requests being downloaded.
  15926. */
  15927. function $TemplateRequestProvider() {
  15928. this.$get = ['$templateCache', '$http', '$q', '$sce', function($templateCache, $http, $q, $sce) {
  15929. function handleRequestFn(tpl, ignoreRequestError) {
  15930. handleRequestFn.totalPendingRequests++;
  15931. // We consider the template cache holds only trusted templates, so
  15932. // there's no need to go through whitelisting again for keys that already
  15933. // are included in there. This also makes Angular accept any script
  15934. // directive, no matter its name. However, we still need to unwrap trusted
  15935. // types.
  15936. if (!isString(tpl) || !$templateCache.get(tpl)) {
  15937. tpl = $sce.getTrustedResourceUrl(tpl);
  15938. }
  15939. var transformResponse = $http.defaults && $http.defaults.transformResponse;
  15940. if (isArray(transformResponse)) {
  15941. transformResponse = transformResponse.filter(function(transformer) {
  15942. return transformer !== defaultHttpResponseTransform;
  15943. });
  15944. } else if (transformResponse === defaultHttpResponseTransform) {
  15945. transformResponse = null;
  15946. }
  15947. var httpOptions = {
  15948. cache: $templateCache,
  15949. transformResponse: transformResponse
  15950. };
  15951. return $http.get(tpl, httpOptions)
  15952. ['finally'](function() {
  15953. handleRequestFn.totalPendingRequests--;
  15954. })
  15955. .then(function(response) {
  15956. $templateCache.put(tpl, response.data);
  15957. return response.data;
  15958. }, handleError);
  15959. function handleError(resp) {
  15960. if (!ignoreRequestError) {
  15961. throw $compileMinErr('tpload', 'Failed to load template: {0} (HTTP status: {1} {2})',
  15962. tpl, resp.status, resp.statusText);
  15963. }
  15964. return $q.reject(resp);
  15965. }
  15966. }
  15967. handleRequestFn.totalPendingRequests = 0;
  15968. return handleRequestFn;
  15969. }];
  15970. }
  15971. function $$TestabilityProvider() {
  15972. this.$get = ['$rootScope', '$browser', '$location',
  15973. function($rootScope, $browser, $location) {
  15974. /**
  15975. * @name $testability
  15976. *
  15977. * @description
  15978. * The private $$testability service provides a collection of methods for use when debugging
  15979. * or by automated test and debugging tools.
  15980. */
  15981. var testability = {};
  15982. /**
  15983. * @name $$testability#findBindings
  15984. *
  15985. * @description
  15986. * Returns an array of elements that are bound (via ng-bind or {{}})
  15987. * to expressions matching the input.
  15988. *
  15989. * @param {Element} element The element root to search from.
  15990. * @param {string} expression The binding expression to match.
  15991. * @param {boolean} opt_exactMatch If true, only returns exact matches
  15992. * for the expression. Filters and whitespace are ignored.
  15993. */
  15994. testability.findBindings = function(element, expression, opt_exactMatch) {
  15995. var bindings = element.getElementsByClassName('ng-binding');
  15996. var matches = [];
  15997. forEach(bindings, function(binding) {
  15998. var dataBinding = angular.element(binding).data('$binding');
  15999. if (dataBinding) {
  16000. forEach(dataBinding, function(bindingName) {
  16001. if (opt_exactMatch) {
  16002. var matcher = new RegExp('(^|\\s)' + escapeForRegexp(expression) + '(\\s|\\||$)');
  16003. if (matcher.test(bindingName)) {
  16004. matches.push(binding);
  16005. }
  16006. } else {
  16007. if (bindingName.indexOf(expression) != -1) {
  16008. matches.push(binding);
  16009. }
  16010. }
  16011. });
  16012. }
  16013. });
  16014. return matches;
  16015. };
  16016. /**
  16017. * @name $$testability#findModels
  16018. *
  16019. * @description
  16020. * Returns an array of elements that are two-way found via ng-model to
  16021. * expressions matching the input.
  16022. *
  16023. * @param {Element} element The element root to search from.
  16024. * @param {string} expression The model expression to match.
  16025. * @param {boolean} opt_exactMatch If true, only returns exact matches
  16026. * for the expression.
  16027. */
  16028. testability.findModels = function(element, expression, opt_exactMatch) {
  16029. var prefixes = ['ng-', 'data-ng-', 'ng\\:'];
  16030. for (var p = 0; p < prefixes.length; ++p) {
  16031. var attributeEquals = opt_exactMatch ? '=' : '*=';
  16032. var selector = '[' + prefixes[p] + 'model' + attributeEquals + '"' + expression + '"]';
  16033. var elements = element.querySelectorAll(selector);
  16034. if (elements.length) {
  16035. return elements;
  16036. }
  16037. }
  16038. };
  16039. /**
  16040. * @name $$testability#getLocation
  16041. *
  16042. * @description
  16043. * Shortcut for getting the location in a browser agnostic way. Returns
  16044. * the path, search, and hash. (e.g. /path?a=b#hash)
  16045. */
  16046. testability.getLocation = function() {
  16047. return $location.url();
  16048. };
  16049. /**
  16050. * @name $$testability#setLocation
  16051. *
  16052. * @description
  16053. * Shortcut for navigating to a location without doing a full page reload.
  16054. *
  16055. * @param {string} url The location url (path, search and hash,
  16056. * e.g. /path?a=b#hash) to go to.
  16057. */
  16058. testability.setLocation = function(url) {
  16059. if (url !== $location.url()) {
  16060. $location.url(url);
  16061. $rootScope.$digest();
  16062. }
  16063. };
  16064. /**
  16065. * @name $$testability#whenStable
  16066. *
  16067. * @description
  16068. * Calls the callback when $timeout and $http requests are completed.
  16069. *
  16070. * @param {function} callback
  16071. */
  16072. testability.whenStable = function(callback) {
  16073. $browser.notifyWhenNoOutstandingRequests(callback);
  16074. };
  16075. return testability;
  16076. }];
  16077. }
  16078. function $TimeoutProvider() {
  16079. this.$get = ['$rootScope', '$browser', '$q', '$$q', '$exceptionHandler',
  16080. function($rootScope, $browser, $q, $$q, $exceptionHandler) {
  16081. var deferreds = {};
  16082. /**
  16083. * @ngdoc service
  16084. * @name $timeout
  16085. *
  16086. * @description
  16087. * Angular's wrapper for `window.setTimeout`. The `fn` function is wrapped into a try/catch
  16088. * block and delegates any exceptions to
  16089. * {@link ng.$exceptionHandler $exceptionHandler} service.
  16090. *
  16091. * The return value of calling `$timeout` is a promise, which will be resolved when
  16092. * the delay has passed and the timeout function, if provided, is executed.
  16093. *
  16094. * To cancel a timeout request, call `$timeout.cancel(promise)`.
  16095. *
  16096. * In tests you can use {@link ngMock.$timeout `$timeout.flush()`} to
  16097. * synchronously flush the queue of deferred functions.
  16098. *
  16099. * If you only want a promise that will be resolved after some specified delay
  16100. * then you can call `$timeout` without the `fn` function.
  16101. *
  16102. * @param {function()=} fn A function, whose execution should be delayed.
  16103. * @param {number=} [delay=0] Delay in milliseconds.
  16104. * @param {boolean=} [invokeApply=true] If set to `false` skips model dirty checking, otherwise
  16105. * will invoke `fn` within the {@link ng.$rootScope.Scope#$apply $apply} block.
  16106. * @param {...*=} Pass additional parameters to the executed function.
  16107. * @returns {Promise} Promise that will be resolved when the timeout is reached. The value this
  16108. * promise will be resolved with is the return value of the `fn` function.
  16109. *
  16110. */
  16111. function timeout(fn, delay, invokeApply) {
  16112. if (!isFunction(fn)) {
  16113. invokeApply = delay;
  16114. delay = fn;
  16115. fn = noop;
  16116. }
  16117. var args = sliceArgs(arguments, 3),
  16118. skipApply = (isDefined(invokeApply) && !invokeApply),
  16119. deferred = (skipApply ? $$q : $q).defer(),
  16120. promise = deferred.promise,
  16121. timeoutId;
  16122. timeoutId = $browser.defer(function() {
  16123. try {
  16124. deferred.resolve(fn.apply(null, args));
  16125. } catch (e) {
  16126. deferred.reject(e);
  16127. $exceptionHandler(e);
  16128. }
  16129. finally {
  16130. delete deferreds[promise.$$timeoutId];
  16131. }
  16132. if (!skipApply) $rootScope.$apply();
  16133. }, delay);
  16134. promise.$$timeoutId = timeoutId;
  16135. deferreds[timeoutId] = deferred;
  16136. return promise;
  16137. }
  16138. /**
  16139. * @ngdoc method
  16140. * @name $timeout#cancel
  16141. *
  16142. * @description
  16143. * Cancels a task associated with the `promise`. As a result of this, the promise will be
  16144. * resolved with a rejection.
  16145. *
  16146. * @param {Promise=} promise Promise returned by the `$timeout` function.
  16147. * @returns {boolean} Returns `true` if the task hasn't executed yet and was successfully
  16148. * canceled.
  16149. */
  16150. timeout.cancel = function(promise) {
  16151. if (promise && promise.$$timeoutId in deferreds) {
  16152. deferreds[promise.$$timeoutId].reject('canceled');
  16153. delete deferreds[promise.$$timeoutId];
  16154. return $browser.defer.cancel(promise.$$timeoutId);
  16155. }
  16156. return false;
  16157. };
  16158. return timeout;
  16159. }];
  16160. }
  16161. // NOTE: The usage of window and document instead of $window and $document here is
  16162. // deliberate. This service depends on the specific behavior of anchor nodes created by the
  16163. // browser (resolving and parsing URLs) that is unlikely to be provided by mock objects and
  16164. // cause us to break tests. In addition, when the browser resolves a URL for XHR, it
  16165. // doesn't know about mocked locations and resolves URLs to the real document - which is
  16166. // exactly the behavior needed here. There is little value is mocking these out for this
  16167. // service.
  16168. var urlParsingNode = document.createElement("a");
  16169. var originUrl = urlResolve(window.location.href);
  16170. /**
  16171. *
  16172. * Implementation Notes for non-IE browsers
  16173. * ----------------------------------------
  16174. * Assigning a URL to the href property of an anchor DOM node, even one attached to the DOM,
  16175. * results both in the normalizing and parsing of the URL. Normalizing means that a relative
  16176. * URL will be resolved into an absolute URL in the context of the application document.
  16177. * Parsing means that the anchor node's host, hostname, protocol, port, pathname and related
  16178. * properties are all populated to reflect the normalized URL. This approach has wide
  16179. * compatibility - Safari 1+, Mozilla 1+, Opera 7+,e etc. See
  16180. * http://www.aptana.com/reference/html/api/HTMLAnchorElement.html
  16181. *
  16182. * Implementation Notes for IE
  16183. * ---------------------------
  16184. * IE <= 10 normalizes the URL when assigned to the anchor node similar to the other
  16185. * browsers. However, the parsed components will not be set if the URL assigned did not specify
  16186. * them. (e.g. if you assign a.href = "foo", then a.protocol, a.host, etc. will be empty.) We
  16187. * work around that by performing the parsing in a 2nd step by taking a previously normalized
  16188. * URL (e.g. by assigning to a.href) and assigning it a.href again. This correctly populates the
  16189. * properties such as protocol, hostname, port, etc.
  16190. *
  16191. * References:
  16192. * http://developer.mozilla.org/en-US/docs/Web/API/HTMLAnchorElement
  16193. * http://www.aptana.com/reference/html/api/HTMLAnchorElement.html
  16194. * http://url.spec.whatwg.org/#urlutils
  16195. * https://github.com/angular/angular.js/pull/2902
  16196. * http://james.padolsey.com/javascript/parsing-urls-with-the-dom/
  16197. *
  16198. * @kind function
  16199. * @param {string} url The URL to be parsed.
  16200. * @description Normalizes and parses a URL.
  16201. * @returns {object} Returns the normalized URL as a dictionary.
  16202. *
  16203. * | member name | Description |
  16204. * |---------------|----------------|
  16205. * | href | A normalized version of the provided URL if it was not an absolute URL |
  16206. * | protocol | The protocol including the trailing colon |
  16207. * | host | The host and port (if the port is non-default) of the normalizedUrl |
  16208. * | search | The search params, minus the question mark |
  16209. * | hash | The hash string, minus the hash symbol
  16210. * | hostname | The hostname
  16211. * | port | The port, without ":"
  16212. * | pathname | The pathname, beginning with "/"
  16213. *
  16214. */
  16215. function urlResolve(url) {
  16216. var href = url;
  16217. if (msie) {
  16218. // Normalize before parse. Refer Implementation Notes on why this is
  16219. // done in two steps on IE.
  16220. urlParsingNode.setAttribute("href", href);
  16221. href = urlParsingNode.href;
  16222. }
  16223. urlParsingNode.setAttribute('href', href);
  16224. // urlParsingNode provides the UrlUtils interface - http://url.spec.whatwg.org/#urlutils
  16225. return {
  16226. href: urlParsingNode.href,
  16227. protocol: urlParsingNode.protocol ? urlParsingNode.protocol.replace(/:$/, '') : '',
  16228. host: urlParsingNode.host,
  16229. search: urlParsingNode.search ? urlParsingNode.search.replace(/^\?/, '') : '',
  16230. hash: urlParsingNode.hash ? urlParsingNode.hash.replace(/^#/, '') : '',
  16231. hostname: urlParsingNode.hostname,
  16232. port: urlParsingNode.port,
  16233. pathname: (urlParsingNode.pathname.charAt(0) === '/')
  16234. ? urlParsingNode.pathname
  16235. : '/' + urlParsingNode.pathname
  16236. };
  16237. }
  16238. /**
  16239. * Parse a request URL and determine whether this is a same-origin request as the application document.
  16240. *
  16241. * @param {string|object} requestUrl The url of the request as a string that will be resolved
  16242. * or a parsed URL object.
  16243. * @returns {boolean} Whether the request is for the same origin as the application document.
  16244. */
  16245. function urlIsSameOrigin(requestUrl) {
  16246. var parsed = (isString(requestUrl)) ? urlResolve(requestUrl) : requestUrl;
  16247. return (parsed.protocol === originUrl.protocol &&
  16248. parsed.host === originUrl.host);
  16249. }
  16250. /**
  16251. * @ngdoc service
  16252. * @name $window
  16253. *
  16254. * @description
  16255. * A reference to the browser's `window` object. While `window`
  16256. * is globally available in JavaScript, it causes testability problems, because
  16257. * it is a global variable. In angular we always refer to it through the
  16258. * `$window` service, so it may be overridden, removed or mocked for testing.
  16259. *
  16260. * Expressions, like the one defined for the `ngClick` directive in the example
  16261. * below, are evaluated with respect to the current scope. Therefore, there is
  16262. * no risk of inadvertently coding in a dependency on a global value in such an
  16263. * expression.
  16264. *
  16265. * @example
  16266. <example module="windowExample">
  16267. <file name="index.html">
  16268. <script>
  16269. angular.module('windowExample', [])
  16270. .controller('ExampleController', ['$scope', '$window', function($scope, $window) {
  16271. $scope.greeting = 'Hello, World!';
  16272. $scope.doGreeting = function(greeting) {
  16273. $window.alert(greeting);
  16274. };
  16275. }]);
  16276. </script>
  16277. <div ng-controller="ExampleController">
  16278. <input type="text" ng-model="greeting" aria-label="greeting" />
  16279. <button ng-click="doGreeting(greeting)">ALERT</button>
  16280. </div>
  16281. </file>
  16282. <file name="protractor.js" type="protractor">
  16283. it('should display the greeting in the input box', function() {
  16284. element(by.model('greeting')).sendKeys('Hello, E2E Tests');
  16285. // If we click the button it will block the test runner
  16286. // element(':button').click();
  16287. });
  16288. </file>
  16289. </example>
  16290. */
  16291. function $WindowProvider() {
  16292. this.$get = valueFn(window);
  16293. }
  16294. /**
  16295. * @name $$cookieReader
  16296. * @requires $document
  16297. *
  16298. * @description
  16299. * This is a private service for reading cookies used by $http and ngCookies
  16300. *
  16301. * @return {Object} a key/value map of the current cookies
  16302. */
  16303. function $$CookieReader($document) {
  16304. var rawDocument = $document[0] || {};
  16305. var lastCookies = {};
  16306. var lastCookieString = '';
  16307. function safeDecodeURIComponent(str) {
  16308. try {
  16309. return decodeURIComponent(str);
  16310. } catch (e) {
  16311. return str;
  16312. }
  16313. }
  16314. return function() {
  16315. var cookieArray, cookie, i, index, name;
  16316. var currentCookieString = rawDocument.cookie || '';
  16317. if (currentCookieString !== lastCookieString) {
  16318. lastCookieString = currentCookieString;
  16319. cookieArray = lastCookieString.split('; ');
  16320. lastCookies = {};
  16321. for (i = 0; i < cookieArray.length; i++) {
  16322. cookie = cookieArray[i];
  16323. index = cookie.indexOf('=');
  16324. if (index > 0) { //ignore nameless cookies
  16325. name = safeDecodeURIComponent(cookie.substring(0, index));
  16326. // the first value that is seen for a cookie is the most
  16327. // specific one. values for the same cookie name that
  16328. // follow are for less specific paths.
  16329. if (isUndefined(lastCookies[name])) {
  16330. lastCookies[name] = safeDecodeURIComponent(cookie.substring(index + 1));
  16331. }
  16332. }
  16333. }
  16334. }
  16335. return lastCookies;
  16336. };
  16337. }
  16338. $$CookieReader.$inject = ['$document'];
  16339. function $$CookieReaderProvider() {
  16340. this.$get = $$CookieReader;
  16341. }
  16342. /* global currencyFilter: true,
  16343. dateFilter: true,
  16344. filterFilter: true,
  16345. jsonFilter: true,
  16346. limitToFilter: true,
  16347. lowercaseFilter: true,
  16348. numberFilter: true,
  16349. orderByFilter: true,
  16350. uppercaseFilter: true,
  16351. */
  16352. /**
  16353. * @ngdoc provider
  16354. * @name $filterProvider
  16355. * @description
  16356. *
  16357. * Filters are just functions which transform input to an output. However filters need to be
  16358. * Dependency Injected. To achieve this a filter definition consists of a factory function which is
  16359. * annotated with dependencies and is responsible for creating a filter function.
  16360. *
  16361. * <div class="alert alert-warning">
  16362. * **Note:** Filter names must be valid angular {@link expression} identifiers, such as `uppercase` or `orderBy`.
  16363. * Names with special characters, such as hyphens and dots, are not allowed. If you wish to namespace
  16364. * your filters, then you can use capitalization (`myappSubsectionFilterx`) or underscores
  16365. * (`myapp_subsection_filterx`).
  16366. * </div>
  16367. *
  16368. * ```js
  16369. * // Filter registration
  16370. * function MyModule($provide, $filterProvider) {
  16371. * // create a service to demonstrate injection (not always needed)
  16372. * $provide.value('greet', function(name){
  16373. * return 'Hello ' + name + '!';
  16374. * });
  16375. *
  16376. * // register a filter factory which uses the
  16377. * // greet service to demonstrate DI.
  16378. * $filterProvider.register('greet', function(greet){
  16379. * // return the filter function which uses the greet service
  16380. * // to generate salutation
  16381. * return function(text) {
  16382. * // filters need to be forgiving so check input validity
  16383. * return text && greet(text) || text;
  16384. * };
  16385. * });
  16386. * }
  16387. * ```
  16388. *
  16389. * The filter function is registered with the `$injector` under the filter name suffix with
  16390. * `Filter`.
  16391. *
  16392. * ```js
  16393. * it('should be the same instance', inject(
  16394. * function($filterProvider) {
  16395. * $filterProvider.register('reverse', function(){
  16396. * return ...;
  16397. * });
  16398. * },
  16399. * function($filter, reverseFilter) {
  16400. * expect($filter('reverse')).toBe(reverseFilter);
  16401. * });
  16402. * ```
  16403. *
  16404. *
  16405. * For more information about how angular filters work, and how to create your own filters, see
  16406. * {@link guide/filter Filters} in the Angular Developer Guide.
  16407. */
  16408. /**
  16409. * @ngdoc service
  16410. * @name $filter
  16411. * @kind function
  16412. * @description
  16413. * Filters are used for formatting data displayed to the user.
  16414. *
  16415. * The general syntax in templates is as follows:
  16416. *
  16417. * {{ expression [| filter_name[:parameter_value] ... ] }}
  16418. *
  16419. * @param {String} name Name of the filter function to retrieve
  16420. * @return {Function} the filter function
  16421. * @example
  16422. <example name="$filter" module="filterExample">
  16423. <file name="index.html">
  16424. <div ng-controller="MainCtrl">
  16425. <h3>{{ originalText }}</h3>
  16426. <h3>{{ filteredText }}</h3>
  16427. </div>
  16428. </file>
  16429. <file name="script.js">
  16430. angular.module('filterExample', [])
  16431. .controller('MainCtrl', function($scope, $filter) {
  16432. $scope.originalText = 'hello';
  16433. $scope.filteredText = $filter('uppercase')($scope.originalText);
  16434. });
  16435. </file>
  16436. </example>
  16437. */
  16438. $FilterProvider.$inject = ['$provide'];
  16439. function $FilterProvider($provide) {
  16440. var suffix = 'Filter';
  16441. /**
  16442. * @ngdoc method
  16443. * @name $filterProvider#register
  16444. * @param {string|Object} name Name of the filter function, or an object map of filters where
  16445. * the keys are the filter names and the values are the filter factories.
  16446. *
  16447. * <div class="alert alert-warning">
  16448. * **Note:** Filter names must be valid angular {@link expression} identifiers, such as `uppercase` or `orderBy`.
  16449. * Names with special characters, such as hyphens and dots, are not allowed. If you wish to namespace
  16450. * your filters, then you can use capitalization (`myappSubsectionFilterx`) or underscores
  16451. * (`myapp_subsection_filterx`).
  16452. * </div>
  16453. * @param {Function} factory If the first argument was a string, a factory function for the filter to be registered.
  16454. * @returns {Object} Registered filter instance, or if a map of filters was provided then a map
  16455. * of the registered filter instances.
  16456. */
  16457. function register(name, factory) {
  16458. if (isObject(name)) {
  16459. var filters = {};
  16460. forEach(name, function(filter, key) {
  16461. filters[key] = register(key, filter);
  16462. });
  16463. return filters;
  16464. } else {
  16465. return $provide.factory(name + suffix, factory);
  16466. }
  16467. }
  16468. this.register = register;
  16469. this.$get = ['$injector', function($injector) {
  16470. return function(name) {
  16471. return $injector.get(name + suffix);
  16472. };
  16473. }];
  16474. ////////////////////////////////////////
  16475. /* global
  16476. currencyFilter: false,
  16477. dateFilter: false,
  16478. filterFilter: false,
  16479. jsonFilter: false,
  16480. limitToFilter: false,
  16481. lowercaseFilter: false,
  16482. numberFilter: false,
  16483. orderByFilter: false,
  16484. uppercaseFilter: false,
  16485. */
  16486. register('currency', currencyFilter);
  16487. register('date', dateFilter);
  16488. register('filter', filterFilter);
  16489. register('json', jsonFilter);
  16490. register('limitTo', limitToFilter);
  16491. register('lowercase', lowercaseFilter);
  16492. register('number', numberFilter);
  16493. register('orderBy', orderByFilter);
  16494. register('uppercase', uppercaseFilter);
  16495. }
  16496. /**
  16497. * @ngdoc filter
  16498. * @name filter
  16499. * @kind function
  16500. *
  16501. * @description
  16502. * Selects a subset of items from `array` and returns it as a new array.
  16503. *
  16504. * @param {Array} array The source array.
  16505. * @param {string|Object|function()} expression The predicate to be used for selecting items from
  16506. * `array`.
  16507. *
  16508. * Can be one of:
  16509. *
  16510. * - `string`: The string is used for matching against the contents of the `array`. All strings or
  16511. * objects with string properties in `array` that match this string will be returned. This also
  16512. * applies to nested object properties.
  16513. * The predicate can be negated by prefixing the string with `!`.
  16514. *
  16515. * - `Object`: A pattern object can be used to filter specific properties on objects contained
  16516. * by `array`. For example `{name:"M", phone:"1"}` predicate will return an array of items
  16517. * which have property `name` containing "M" and property `phone` containing "1". A special
  16518. * property name `$` can be used (as in `{$:"text"}`) to accept a match against any
  16519. * property of the object or its nested object properties. That's equivalent to the simple
  16520. * substring match with a `string` as described above. The predicate can be negated by prefixing
  16521. * the string with `!`.
  16522. * For example `{name: "!M"}` predicate will return an array of items which have property `name`
  16523. * not containing "M".
  16524. *
  16525. * Note that a named property will match properties on the same level only, while the special
  16526. * `$` property will match properties on the same level or deeper. E.g. an array item like
  16527. * `{name: {first: 'John', last: 'Doe'}}` will **not** be matched by `{name: 'John'}`, but
  16528. * **will** be matched by `{$: 'John'}`.
  16529. *
  16530. * - `function(value, index, array)`: A predicate function can be used to write arbitrary filters.
  16531. * The function is called for each element of the array, with the element, its index, and
  16532. * the entire array itself as arguments.
  16533. *
  16534. * The final result is an array of those elements that the predicate returned true for.
  16535. *
  16536. * @param {function(actual, expected)|true|undefined} comparator Comparator which is used in
  16537. * determining if the expected value (from the filter expression) and actual value (from
  16538. * the object in the array) should be considered a match.
  16539. *
  16540. * Can be one of:
  16541. *
  16542. * - `function(actual, expected)`:
  16543. * The function will be given the object value and the predicate value to compare and
  16544. * should return true if both values should be considered equal.
  16545. *
  16546. * - `true`: A shorthand for `function(actual, expected) { return angular.equals(actual, expected)}`.
  16547. * This is essentially strict comparison of expected and actual.
  16548. *
  16549. * - `false|undefined`: A short hand for a function which will look for a substring match in case
  16550. * insensitive way.
  16551. *
  16552. * Primitive values are converted to strings. Objects are not compared against primitives,
  16553. * unless they have a custom `toString` method (e.g. `Date` objects).
  16554. *
  16555. * @example
  16556. <example>
  16557. <file name="index.html">
  16558. <div ng-init="friends = [{name:'John', phone:'555-1276'},
  16559. {name:'Mary', phone:'800-BIG-MARY'},
  16560. {name:'Mike', phone:'555-4321'},
  16561. {name:'Adam', phone:'555-5678'},
  16562. {name:'Julie', phone:'555-8765'},
  16563. {name:'Juliette', phone:'555-5678'}]"></div>
  16564. <label>Search: <input ng-model="searchText"></label>
  16565. <table id="searchTextResults">
  16566. <tr><th>Name</th><th>Phone</th></tr>
  16567. <tr ng-repeat="friend in friends | filter:searchText">
  16568. <td>{{friend.name}}</td>
  16569. <td>{{friend.phone}}</td>
  16570. </tr>
  16571. </table>
  16572. <hr>
  16573. <label>Any: <input ng-model="search.$"></label> <br>
  16574. <label>Name only <input ng-model="search.name"></label><br>
  16575. <label>Phone only <input ng-model="search.phone"></label><br>
  16576. <label>Equality <input type="checkbox" ng-model="strict"></label><br>
  16577. <table id="searchObjResults">
  16578. <tr><th>Name</th><th>Phone</th></tr>
  16579. <tr ng-repeat="friendObj in friends | filter:search:strict">
  16580. <td>{{friendObj.name}}</td>
  16581. <td>{{friendObj.phone}}</td>
  16582. </tr>
  16583. </table>
  16584. </file>
  16585. <file name="protractor.js" type="protractor">
  16586. var expectFriendNames = function(expectedNames, key) {
  16587. element.all(by.repeater(key + ' in friends').column(key + '.name')).then(function(arr) {
  16588. arr.forEach(function(wd, i) {
  16589. expect(wd.getText()).toMatch(expectedNames[i]);
  16590. });
  16591. });
  16592. };
  16593. it('should search across all fields when filtering with a string', function() {
  16594. var searchText = element(by.model('searchText'));
  16595. searchText.clear();
  16596. searchText.sendKeys('m');
  16597. expectFriendNames(['Mary', 'Mike', 'Adam'], 'friend');
  16598. searchText.clear();
  16599. searchText.sendKeys('76');
  16600. expectFriendNames(['John', 'Julie'], 'friend');
  16601. });
  16602. it('should search in specific fields when filtering with a predicate object', function() {
  16603. var searchAny = element(by.model('search.$'));
  16604. searchAny.clear();
  16605. searchAny.sendKeys('i');
  16606. expectFriendNames(['Mary', 'Mike', 'Julie', 'Juliette'], 'friendObj');
  16607. });
  16608. it('should use a equal comparison when comparator is true', function() {
  16609. var searchName = element(by.model('search.name'));
  16610. var strict = element(by.model('strict'));
  16611. searchName.clear();
  16612. searchName.sendKeys('Julie');
  16613. strict.click();
  16614. expectFriendNames(['Julie'], 'friendObj');
  16615. });
  16616. </file>
  16617. </example>
  16618. */
  16619. function filterFilter() {
  16620. return function(array, expression, comparator) {
  16621. if (!isArrayLike(array)) {
  16622. if (array == null) {
  16623. return array;
  16624. } else {
  16625. throw minErr('filter')('notarray', 'Expected array but received: {0}', array);
  16626. }
  16627. }
  16628. var expressionType = getTypeForFilter(expression);
  16629. var predicateFn;
  16630. var matchAgainstAnyProp;
  16631. switch (expressionType) {
  16632. case 'function':
  16633. predicateFn = expression;
  16634. break;
  16635. case 'boolean':
  16636. case 'null':
  16637. case 'number':
  16638. case 'string':
  16639. matchAgainstAnyProp = true;
  16640. //jshint -W086
  16641. case 'object':
  16642. //jshint +W086
  16643. predicateFn = createPredicateFn(expression, comparator, matchAgainstAnyProp);
  16644. break;
  16645. default:
  16646. return array;
  16647. }
  16648. return Array.prototype.filter.call(array, predicateFn);
  16649. };
  16650. }
  16651. // Helper functions for `filterFilter`
  16652. function createPredicateFn(expression, comparator, matchAgainstAnyProp) {
  16653. var shouldMatchPrimitives = isObject(expression) && ('$' in expression);
  16654. var predicateFn;
  16655. if (comparator === true) {
  16656. comparator = equals;
  16657. } else if (!isFunction(comparator)) {
  16658. comparator = function(actual, expected) {
  16659. if (isUndefined(actual)) {
  16660. // No substring matching against `undefined`
  16661. return false;
  16662. }
  16663. if ((actual === null) || (expected === null)) {
  16664. // No substring matching against `null`; only match against `null`
  16665. return actual === expected;
  16666. }
  16667. if (isObject(expected) || (isObject(actual) && !hasCustomToString(actual))) {
  16668. // Should not compare primitives against objects, unless they have custom `toString` method
  16669. return false;
  16670. }
  16671. actual = lowercase('' + actual);
  16672. expected = lowercase('' + expected);
  16673. return actual.indexOf(expected) !== -1;
  16674. };
  16675. }
  16676. predicateFn = function(item) {
  16677. if (shouldMatchPrimitives && !isObject(item)) {
  16678. return deepCompare(item, expression.$, comparator, false);
  16679. }
  16680. return deepCompare(item, expression, comparator, matchAgainstAnyProp);
  16681. };
  16682. return predicateFn;
  16683. }
  16684. function deepCompare(actual, expected, comparator, matchAgainstAnyProp, dontMatchWholeObject) {
  16685. var actualType = getTypeForFilter(actual);
  16686. var expectedType = getTypeForFilter(expected);
  16687. if ((expectedType === 'string') && (expected.charAt(0) === '!')) {
  16688. return !deepCompare(actual, expected.substring(1), comparator, matchAgainstAnyProp);
  16689. } else if (isArray(actual)) {
  16690. // In case `actual` is an array, consider it a match
  16691. // if ANY of it's items matches `expected`
  16692. return actual.some(function(item) {
  16693. return deepCompare(item, expected, comparator, matchAgainstAnyProp);
  16694. });
  16695. }
  16696. switch (actualType) {
  16697. case 'object':
  16698. var key;
  16699. if (matchAgainstAnyProp) {
  16700. for (key in actual) {
  16701. if ((key.charAt(0) !== '$') && deepCompare(actual[key], expected, comparator, true)) {
  16702. return true;
  16703. }
  16704. }
  16705. return dontMatchWholeObject ? false : deepCompare(actual, expected, comparator, false);
  16706. } else if (expectedType === 'object') {
  16707. for (key in expected) {
  16708. var expectedVal = expected[key];
  16709. if (isFunction(expectedVal) || isUndefined(expectedVal)) {
  16710. continue;
  16711. }
  16712. var matchAnyProperty = key === '$';
  16713. var actualVal = matchAnyProperty ? actual : actual[key];
  16714. if (!deepCompare(actualVal, expectedVal, comparator, matchAnyProperty, matchAnyProperty)) {
  16715. return false;
  16716. }
  16717. }
  16718. return true;
  16719. } else {
  16720. return comparator(actual, expected);
  16721. }
  16722. break;
  16723. case 'function':
  16724. return false;
  16725. default:
  16726. return comparator(actual, expected);
  16727. }
  16728. }
  16729. // Used for easily differentiating between `null` and actual `object`
  16730. function getTypeForFilter(val) {
  16731. return (val === null) ? 'null' : typeof val;
  16732. }
  16733. /**
  16734. * @ngdoc filter
  16735. * @name currency
  16736. * @kind function
  16737. *
  16738. * @description
  16739. * Formats a number as a currency (ie $1,234.56). When no currency symbol is provided, default
  16740. * symbol for current locale is used.
  16741. *
  16742. * @param {number} amount Input to filter.
  16743. * @param {string=} symbol Currency symbol or identifier to be displayed.
  16744. * @param {number=} fractionSize Number of decimal places to round the amount to, defaults to default max fraction size for current locale
  16745. * @returns {string} Formatted number.
  16746. *
  16747. *
  16748. * @example
  16749. <example module="currencyExample">
  16750. <file name="index.html">
  16751. <script>
  16752. angular.module('currencyExample', [])
  16753. .controller('ExampleController', ['$scope', function($scope) {
  16754. $scope.amount = 1234.56;
  16755. }]);
  16756. </script>
  16757. <div ng-controller="ExampleController">
  16758. <input type="number" ng-model="amount" aria-label="amount"> <br>
  16759. default currency symbol ($): <span id="currency-default">{{amount | currency}}</span><br>
  16760. custom currency identifier (USD$): <span id="currency-custom">{{amount | currency:"USD$"}}</span>
  16761. no fractions (0): <span id="currency-no-fractions">{{amount | currency:"USD$":0}}</span>
  16762. </div>
  16763. </file>
  16764. <file name="protractor.js" type="protractor">
  16765. it('should init with 1234.56', function() {
  16766. expect(element(by.id('currency-default')).getText()).toBe('$1,234.56');
  16767. expect(element(by.id('currency-custom')).getText()).toBe('USD$1,234.56');
  16768. expect(element(by.id('currency-no-fractions')).getText()).toBe('USD$1,235');
  16769. });
  16770. it('should update', function() {
  16771. if (browser.params.browser == 'safari') {
  16772. // Safari does not understand the minus key. See
  16773. // https://github.com/angular/protractor/issues/481
  16774. return;
  16775. }
  16776. element(by.model('amount')).clear();
  16777. element(by.model('amount')).sendKeys('-1234');
  16778. expect(element(by.id('currency-default')).getText()).toBe('-$1,234.00');
  16779. expect(element(by.id('currency-custom')).getText()).toBe('-USD$1,234.00');
  16780. expect(element(by.id('currency-no-fractions')).getText()).toBe('-USD$1,234');
  16781. });
  16782. </file>
  16783. </example>
  16784. */
  16785. currencyFilter.$inject = ['$locale'];
  16786. function currencyFilter($locale) {
  16787. var formats = $locale.NUMBER_FORMATS;
  16788. return function(amount, currencySymbol, fractionSize) {
  16789. if (isUndefined(currencySymbol)) {
  16790. currencySymbol = formats.CURRENCY_SYM;
  16791. }
  16792. if (isUndefined(fractionSize)) {
  16793. fractionSize = formats.PATTERNS[1].maxFrac;
  16794. }
  16795. // if null or undefined pass it through
  16796. return (amount == null)
  16797. ? amount
  16798. : formatNumber(amount, formats.PATTERNS[1], formats.GROUP_SEP, formats.DECIMAL_SEP, fractionSize).
  16799. replace(/\u00A4/g, currencySymbol);
  16800. };
  16801. }
  16802. /**
  16803. * @ngdoc filter
  16804. * @name number
  16805. * @kind function
  16806. *
  16807. * @description
  16808. * Formats a number as text.
  16809. *
  16810. * If the input is null or undefined, it will just be returned.
  16811. * If the input is infinite (Infinity/-Infinity) the Infinity symbol '∞' is returned.
  16812. * If the input is not a number an empty string is returned.
  16813. *
  16814. *
  16815. * @param {number|string} number Number to format.
  16816. * @param {(number|string)=} fractionSize Number of decimal places to round the number to.
  16817. * If this is not provided then the fraction size is computed from the current locale's number
  16818. * formatting pattern. In the case of the default locale, it will be 3.
  16819. * @returns {string} Number rounded to decimalPlaces and places a “,” after each third digit.
  16820. *
  16821. * @example
  16822. <example module="numberFilterExample">
  16823. <file name="index.html">
  16824. <script>
  16825. angular.module('numberFilterExample', [])
  16826. .controller('ExampleController', ['$scope', function($scope) {
  16827. $scope.val = 1234.56789;
  16828. }]);
  16829. </script>
  16830. <div ng-controller="ExampleController">
  16831. <label>Enter number: <input ng-model='val'></label><br>
  16832. Default formatting: <span id='number-default'>{{val | number}}</span><br>
  16833. No fractions: <span>{{val | number:0}}</span><br>
  16834. Negative number: <span>{{-val | number:4}}</span>
  16835. </div>
  16836. </file>
  16837. <file name="protractor.js" type="protractor">
  16838. it('should format numbers', function() {
  16839. expect(element(by.id('number-default')).getText()).toBe('1,234.568');
  16840. expect(element(by.binding('val | number:0')).getText()).toBe('1,235');
  16841. expect(element(by.binding('-val | number:4')).getText()).toBe('-1,234.5679');
  16842. });
  16843. it('should update', function() {
  16844. element(by.model('val')).clear();
  16845. element(by.model('val')).sendKeys('3374.333');
  16846. expect(element(by.id('number-default')).getText()).toBe('3,374.333');
  16847. expect(element(by.binding('val | number:0')).getText()).toBe('3,374');
  16848. expect(element(by.binding('-val | number:4')).getText()).toBe('-3,374.3330');
  16849. });
  16850. </file>
  16851. </example>
  16852. */
  16853. numberFilter.$inject = ['$locale'];
  16854. function numberFilter($locale) {
  16855. var formats = $locale.NUMBER_FORMATS;
  16856. return function(number, fractionSize) {
  16857. // if null or undefined pass it through
  16858. return (number == null)
  16859. ? number
  16860. : formatNumber(number, formats.PATTERNS[0], formats.GROUP_SEP, formats.DECIMAL_SEP,
  16861. fractionSize);
  16862. };
  16863. }
  16864. var DECIMAL_SEP = '.';
  16865. function formatNumber(number, pattern, groupSep, decimalSep, fractionSize) {
  16866. if (isObject(number)) return '';
  16867. var isNegative = number < 0;
  16868. number = Math.abs(number);
  16869. var isInfinity = number === Infinity;
  16870. if (!isInfinity && !isFinite(number)) return '';
  16871. var numStr = number + '',
  16872. formatedText = '',
  16873. hasExponent = false,
  16874. parts = [];
  16875. if (isInfinity) formatedText = '\u221e';
  16876. if (!isInfinity && numStr.indexOf('e') !== -1) {
  16877. var match = numStr.match(/([\d\.]+)e(-?)(\d+)/);
  16878. if (match && match[2] == '-' && match[3] > fractionSize + 1) {
  16879. number = 0;
  16880. } else {
  16881. formatedText = numStr;
  16882. hasExponent = true;
  16883. }
  16884. }
  16885. if (!isInfinity && !hasExponent) {
  16886. var fractionLen = (numStr.split(DECIMAL_SEP)[1] || '').length;
  16887. // determine fractionSize if it is not specified
  16888. if (isUndefined(fractionSize)) {
  16889. fractionSize = Math.min(Math.max(pattern.minFrac, fractionLen), pattern.maxFrac);
  16890. }
  16891. // safely round numbers in JS without hitting imprecisions of floating-point arithmetics
  16892. // inspired by:
  16893. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/round
  16894. number = +(Math.round(+(number.toString() + 'e' + fractionSize)).toString() + 'e' + -fractionSize);
  16895. var fraction = ('' + number).split(DECIMAL_SEP);
  16896. var whole = fraction[0];
  16897. fraction = fraction[1] || '';
  16898. var i, pos = 0,
  16899. lgroup = pattern.lgSize,
  16900. group = pattern.gSize;
  16901. if (whole.length >= (lgroup + group)) {
  16902. pos = whole.length - lgroup;
  16903. for (i = 0; i < pos; i++) {
  16904. if ((pos - i) % group === 0 && i !== 0) {
  16905. formatedText += groupSep;
  16906. }
  16907. formatedText += whole.charAt(i);
  16908. }
  16909. }
  16910. for (i = pos; i < whole.length; i++) {
  16911. if ((whole.length - i) % lgroup === 0 && i !== 0) {
  16912. formatedText += groupSep;
  16913. }
  16914. formatedText += whole.charAt(i);
  16915. }
  16916. // format fraction part.
  16917. while (fraction.length < fractionSize) {
  16918. fraction += '0';
  16919. }
  16920. if (fractionSize && fractionSize !== "0") formatedText += decimalSep + fraction.substr(0, fractionSize);
  16921. } else {
  16922. if (fractionSize > 0 && number < 1) {
  16923. formatedText = number.toFixed(fractionSize);
  16924. number = parseFloat(formatedText);
  16925. }
  16926. }
  16927. if (number === 0) {
  16928. isNegative = false;
  16929. }
  16930. parts.push(isNegative ? pattern.negPre : pattern.posPre,
  16931. formatedText,
  16932. isNegative ? pattern.negSuf : pattern.posSuf);
  16933. return parts.join('');
  16934. }
  16935. function padNumber(num, digits, trim) {
  16936. var neg = '';
  16937. if (num < 0) {
  16938. neg = '-';
  16939. num = -num;
  16940. }
  16941. num = '' + num;
  16942. while (num.length < digits) num = '0' + num;
  16943. if (trim) {
  16944. num = num.substr(num.length - digits);
  16945. }
  16946. return neg + num;
  16947. }
  16948. function dateGetter(name, size, offset, trim) {
  16949. offset = offset || 0;
  16950. return function(date) {
  16951. var value = date['get' + name]();
  16952. if (offset > 0 || value > -offset) {
  16953. value += offset;
  16954. }
  16955. if (value === 0 && offset == -12) value = 12;
  16956. return padNumber(value, size, trim);
  16957. };
  16958. }
  16959. function dateStrGetter(name, shortForm) {
  16960. return function(date, formats) {
  16961. var value = date['get' + name]();
  16962. var get = uppercase(shortForm ? ('SHORT' + name) : name);
  16963. return formats[get][value];
  16964. };
  16965. }
  16966. function timeZoneGetter(date, formats, offset) {
  16967. var zone = -1 * offset;
  16968. var paddedZone = (zone >= 0) ? "+" : "";
  16969. paddedZone += padNumber(Math[zone > 0 ? 'floor' : 'ceil'](zone / 60), 2) +
  16970. padNumber(Math.abs(zone % 60), 2);
  16971. return paddedZone;
  16972. }
  16973. function getFirstThursdayOfYear(year) {
  16974. // 0 = index of January
  16975. var dayOfWeekOnFirst = (new Date(year, 0, 1)).getDay();
  16976. // 4 = index of Thursday (+1 to account for 1st = 5)
  16977. // 11 = index of *next* Thursday (+1 account for 1st = 12)
  16978. return new Date(year, 0, ((dayOfWeekOnFirst <= 4) ? 5 : 12) - dayOfWeekOnFirst);
  16979. }
  16980. function getThursdayThisWeek(datetime) {
  16981. return new Date(datetime.getFullYear(), datetime.getMonth(),
  16982. // 4 = index of Thursday
  16983. datetime.getDate() + (4 - datetime.getDay()));
  16984. }
  16985. function weekGetter(size) {
  16986. return function(date) {
  16987. var firstThurs = getFirstThursdayOfYear(date.getFullYear()),
  16988. thisThurs = getThursdayThisWeek(date);
  16989. var diff = +thisThurs - +firstThurs,
  16990. result = 1 + Math.round(diff / 6.048e8); // 6.048e8 ms per week
  16991. return padNumber(result, size);
  16992. };
  16993. }
  16994. function ampmGetter(date, formats) {
  16995. return date.getHours() < 12 ? formats.AMPMS[0] : formats.AMPMS[1];
  16996. }
  16997. function eraGetter(date, formats) {
  16998. return date.getFullYear() <= 0 ? formats.ERAS[0] : formats.ERAS[1];
  16999. }
  17000. function longEraGetter(date, formats) {
  17001. return date.getFullYear() <= 0 ? formats.ERANAMES[0] : formats.ERANAMES[1];
  17002. }
  17003. var DATE_FORMATS = {
  17004. yyyy: dateGetter('FullYear', 4),
  17005. yy: dateGetter('FullYear', 2, 0, true),
  17006. y: dateGetter('FullYear', 1),
  17007. MMMM: dateStrGetter('Month'),
  17008. MMM: dateStrGetter('Month', true),
  17009. MM: dateGetter('Month', 2, 1),
  17010. M: dateGetter('Month', 1, 1),
  17011. dd: dateGetter('Date', 2),
  17012. d: dateGetter('Date', 1),
  17013. HH: dateGetter('Hours', 2),
  17014. H: dateGetter('Hours', 1),
  17015. hh: dateGetter('Hours', 2, -12),
  17016. h: dateGetter('Hours', 1, -12),
  17017. mm: dateGetter('Minutes', 2),
  17018. m: dateGetter('Minutes', 1),
  17019. ss: dateGetter('Seconds', 2),
  17020. s: dateGetter('Seconds', 1),
  17021. // while ISO 8601 requires fractions to be prefixed with `.` or `,`
  17022. // we can be just safely rely on using `sss` since we currently don't support single or two digit fractions
  17023. sss: dateGetter('Milliseconds', 3),
  17024. EEEE: dateStrGetter('Day'),
  17025. EEE: dateStrGetter('Day', true),
  17026. a: ampmGetter,
  17027. Z: timeZoneGetter,
  17028. ww: weekGetter(2),
  17029. w: weekGetter(1),
  17030. G: eraGetter,
  17031. GG: eraGetter,
  17032. GGG: eraGetter,
  17033. GGGG: longEraGetter
  17034. };
  17035. var DATE_FORMATS_SPLIT = /((?:[^yMdHhmsaZEwG']+)|(?:'(?:[^']|'')*')|(?:E+|y+|M+|d+|H+|h+|m+|s+|a|Z|G+|w+))(.*)/,
  17036. NUMBER_STRING = /^\-?\d+$/;
  17037. /**
  17038. * @ngdoc filter
  17039. * @name date
  17040. * @kind function
  17041. *
  17042. * @description
  17043. * Formats `date` to a string based on the requested `format`.
  17044. *
  17045. * `format` string can be composed of the following elements:
  17046. *
  17047. * * `'yyyy'`: 4 digit representation of year (e.g. AD 1 => 0001, AD 2010 => 2010)
  17048. * * `'yy'`: 2 digit representation of year, padded (00-99). (e.g. AD 2001 => 01, AD 2010 => 10)
  17049. * * `'y'`: 1 digit representation of year, e.g. (AD 1 => 1, AD 199 => 199)
  17050. * * `'MMMM'`: Month in year (January-December)
  17051. * * `'MMM'`: Month in year (Jan-Dec)
  17052. * * `'MM'`: Month in year, padded (01-12)
  17053. * * `'M'`: Month in year (1-12)
  17054. * * `'dd'`: Day in month, padded (01-31)
  17055. * * `'d'`: Day in month (1-31)
  17056. * * `'EEEE'`: Day in Week,(Sunday-Saturday)
  17057. * * `'EEE'`: Day in Week, (Sun-Sat)
  17058. * * `'HH'`: Hour in day, padded (00-23)
  17059. * * `'H'`: Hour in day (0-23)
  17060. * * `'hh'`: Hour in AM/PM, padded (01-12)
  17061. * * `'h'`: Hour in AM/PM, (1-12)
  17062. * * `'mm'`: Minute in hour, padded (00-59)
  17063. * * `'m'`: Minute in hour (0-59)
  17064. * * `'ss'`: Second in minute, padded (00-59)
  17065. * * `'s'`: Second in minute (0-59)
  17066. * * `'sss'`: Millisecond in second, padded (000-999)
  17067. * * `'a'`: AM/PM marker
  17068. * * `'Z'`: 4 digit (+sign) representation of the timezone offset (-1200-+1200)
  17069. * * `'ww'`: Week of year, padded (00-53). Week 01 is the week with the first Thursday of the year
  17070. * * `'w'`: Week of year (0-53). Week 1 is the week with the first Thursday of the year
  17071. * * `'G'`, `'GG'`, `'GGG'`: The abbreviated form of the era string (e.g. 'AD')
  17072. * * `'GGGG'`: The long form of the era string (e.g. 'Anno Domini')
  17073. *
  17074. * `format` string can also be one of the following predefined
  17075. * {@link guide/i18n localizable formats}:
  17076. *
  17077. * * `'medium'`: equivalent to `'MMM d, y h:mm:ss a'` for en_US locale
  17078. * (e.g. Sep 3, 2010 12:05:08 PM)
  17079. * * `'short'`: equivalent to `'M/d/yy h:mm a'` for en_US locale (e.g. 9/3/10 12:05 PM)
  17080. * * `'fullDate'`: equivalent to `'EEEE, MMMM d, y'` for en_US locale
  17081. * (e.g. Friday, September 3, 2010)
  17082. * * `'longDate'`: equivalent to `'MMMM d, y'` for en_US locale (e.g. September 3, 2010)
  17083. * * `'mediumDate'`: equivalent to `'MMM d, y'` for en_US locale (e.g. Sep 3, 2010)
  17084. * * `'shortDate'`: equivalent to `'M/d/yy'` for en_US locale (e.g. 9/3/10)
  17085. * * `'mediumTime'`: equivalent to `'h:mm:ss a'` for en_US locale (e.g. 12:05:08 PM)
  17086. * * `'shortTime'`: equivalent to `'h:mm a'` for en_US locale (e.g. 12:05 PM)
  17087. *
  17088. * `format` string can contain literal values. These need to be escaped by surrounding with single quotes (e.g.
  17089. * `"h 'in the morning'"`). In order to output a single quote, escape it - i.e., two single quotes in a sequence
  17090. * (e.g. `"h 'o''clock'"`).
  17091. *
  17092. * @param {(Date|number|string)} date Date to format either as Date object, milliseconds (string or
  17093. * number) or various ISO 8601 datetime string formats (e.g. yyyy-MM-ddTHH:mm:ss.sssZ and its
  17094. * shorter versions like yyyy-MM-ddTHH:mmZ, yyyy-MM-dd or yyyyMMddTHHmmssZ). If no timezone is
  17095. * specified in the string input, the time is considered to be in the local timezone.
  17096. * @param {string=} format Formatting rules (see Description). If not specified,
  17097. * `mediumDate` is used.
  17098. * @param {string=} timezone Timezone to be used for formatting. It understands UTC/GMT and the
  17099. * continental US time zone abbreviations, but for general use, use a time zone offset, for
  17100. * example, `'+0430'` (4 hours, 30 minutes east of the Greenwich meridian)
  17101. * If not specified, the timezone of the browser will be used.
  17102. * @returns {string} Formatted string or the input if input is not recognized as date/millis.
  17103. *
  17104. * @example
  17105. <example>
  17106. <file name="index.html">
  17107. <span ng-non-bindable>{{1288323623006 | date:'medium'}}</span>:
  17108. <span>{{1288323623006 | date:'medium'}}</span><br>
  17109. <span ng-non-bindable>{{1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'}}</span>:
  17110. <span>{{1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'}}</span><br>
  17111. <span ng-non-bindable>{{1288323623006 | date:'MM/dd/yyyy @ h:mma'}}</span>:
  17112. <span>{{'1288323623006' | date:'MM/dd/yyyy @ h:mma'}}</span><br>
  17113. <span ng-non-bindable>{{1288323623006 | date:"MM/dd/yyyy 'at' h:mma"}}</span>:
  17114. <span>{{'1288323623006' | date:"MM/dd/yyyy 'at' h:mma"}}</span><br>
  17115. </file>
  17116. <file name="protractor.js" type="protractor">
  17117. it('should format date', function() {
  17118. expect(element(by.binding("1288323623006 | date:'medium'")).getText()).
  17119. toMatch(/Oct 2\d, 2010 \d{1,2}:\d{2}:\d{2} (AM|PM)/);
  17120. expect(element(by.binding("1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'")).getText()).
  17121. toMatch(/2010\-10\-2\d \d{2}:\d{2}:\d{2} (\-|\+)?\d{4}/);
  17122. expect(element(by.binding("'1288323623006' | date:'MM/dd/yyyy @ h:mma'")).getText()).
  17123. toMatch(/10\/2\d\/2010 @ \d{1,2}:\d{2}(AM|PM)/);
  17124. expect(element(by.binding("'1288323623006' | date:\"MM/dd/yyyy 'at' h:mma\"")).getText()).
  17125. toMatch(/10\/2\d\/2010 at \d{1,2}:\d{2}(AM|PM)/);
  17126. });
  17127. </file>
  17128. </example>
  17129. */
  17130. dateFilter.$inject = ['$locale'];
  17131. function dateFilter($locale) {
  17132. var R_ISO8601_STR = /^(\d{4})-?(\d\d)-?(\d\d)(?:T(\d\d)(?::?(\d\d)(?::?(\d\d)(?:\.(\d+))?)?)?(Z|([+-])(\d\d):?(\d\d))?)?$/;
  17133. // 1 2 3 4 5 6 7 8 9 10 11
  17134. function jsonStringToDate(string) {
  17135. var match;
  17136. if (match = string.match(R_ISO8601_STR)) {
  17137. var date = new Date(0),
  17138. tzHour = 0,
  17139. tzMin = 0,
  17140. dateSetter = match[8] ? date.setUTCFullYear : date.setFullYear,
  17141. timeSetter = match[8] ? date.setUTCHours : date.setHours;
  17142. if (match[9]) {
  17143. tzHour = toInt(match[9] + match[10]);
  17144. tzMin = toInt(match[9] + match[11]);
  17145. }
  17146. dateSetter.call(date, toInt(match[1]), toInt(match[2]) - 1, toInt(match[3]));
  17147. var h = toInt(match[4] || 0) - tzHour;
  17148. var m = toInt(match[5] || 0) - tzMin;
  17149. var s = toInt(match[6] || 0);
  17150. var ms = Math.round(parseFloat('0.' + (match[7] || 0)) * 1000);
  17151. timeSetter.call(date, h, m, s, ms);
  17152. return date;
  17153. }
  17154. return string;
  17155. }
  17156. return function(date, format, timezone) {
  17157. var text = '',
  17158. parts = [],
  17159. fn, match;
  17160. format = format || 'mediumDate';
  17161. format = $locale.DATETIME_FORMATS[format] || format;
  17162. if (isString(date)) {
  17163. date = NUMBER_STRING.test(date) ? toInt(date) : jsonStringToDate(date);
  17164. }
  17165. if (isNumber(date)) {
  17166. date = new Date(date);
  17167. }
  17168. if (!isDate(date) || !isFinite(date.getTime())) {
  17169. return date;
  17170. }
  17171. while (format) {
  17172. match = DATE_FORMATS_SPLIT.exec(format);
  17173. if (match) {
  17174. parts = concat(parts, match, 1);
  17175. format = parts.pop();
  17176. } else {
  17177. parts.push(format);
  17178. format = null;
  17179. }
  17180. }
  17181. var dateTimezoneOffset = date.getTimezoneOffset();
  17182. if (timezone) {
  17183. dateTimezoneOffset = timezoneToOffset(timezone, date.getTimezoneOffset());
  17184. date = convertTimezoneToLocal(date, timezone, true);
  17185. }
  17186. forEach(parts, function(value) {
  17187. fn = DATE_FORMATS[value];
  17188. text += fn ? fn(date, $locale.DATETIME_FORMATS, dateTimezoneOffset)
  17189. : value.replace(/(^'|'$)/g, '').replace(/''/g, "'");
  17190. });
  17191. return text;
  17192. };
  17193. }
  17194. /**
  17195. * @ngdoc filter
  17196. * @name json
  17197. * @kind function
  17198. *
  17199. * @description
  17200. * Allows you to convert a JavaScript object into JSON string.
  17201. *
  17202. * This filter is mostly useful for debugging. When using the double curly {{value}} notation
  17203. * the binding is automatically converted to JSON.
  17204. *
  17205. * @param {*} object Any JavaScript object (including arrays and primitive types) to filter.
  17206. * @param {number=} spacing The number of spaces to use per indentation, defaults to 2.
  17207. * @returns {string} JSON string.
  17208. *
  17209. *
  17210. * @example
  17211. <example>
  17212. <file name="index.html">
  17213. <pre id="default-spacing">{{ {'name':'value'} | json }}</pre>
  17214. <pre id="custom-spacing">{{ {'name':'value'} | json:4 }}</pre>
  17215. </file>
  17216. <file name="protractor.js" type="protractor">
  17217. it('should jsonify filtered objects', function() {
  17218. expect(element(by.id('default-spacing')).getText()).toMatch(/\{\n "name": ?"value"\n}/);
  17219. expect(element(by.id('custom-spacing')).getText()).toMatch(/\{\n "name": ?"value"\n}/);
  17220. });
  17221. </file>
  17222. </example>
  17223. *
  17224. */
  17225. function jsonFilter() {
  17226. return function(object, spacing) {
  17227. if (isUndefined(spacing)) {
  17228. spacing = 2;
  17229. }
  17230. return toJson(object, spacing);
  17231. };
  17232. }
  17233. /**
  17234. * @ngdoc filter
  17235. * @name lowercase
  17236. * @kind function
  17237. * @description
  17238. * Converts string to lowercase.
  17239. * @see angular.lowercase
  17240. */
  17241. var lowercaseFilter = valueFn(lowercase);
  17242. /**
  17243. * @ngdoc filter
  17244. * @name uppercase
  17245. * @kind function
  17246. * @description
  17247. * Converts string to uppercase.
  17248. * @see angular.uppercase
  17249. */
  17250. var uppercaseFilter = valueFn(uppercase);
  17251. /**
  17252. * @ngdoc filter
  17253. * @name limitTo
  17254. * @kind function
  17255. *
  17256. * @description
  17257. * Creates a new array or string containing only a specified number of elements. The elements
  17258. * are taken from either the beginning or the end of the source array, string or number, as specified by
  17259. * the value and sign (positive or negative) of `limit`. If a number is used as input, it is
  17260. * converted to a string.
  17261. *
  17262. * @param {Array|string|number} input Source array, string or number to be limited.
  17263. * @param {string|number} limit The length of the returned array or string. If the `limit` number
  17264. * is positive, `limit` number of items from the beginning of the source array/string are copied.
  17265. * If the number is negative, `limit` number of items from the end of the source array/string
  17266. * are copied. The `limit` will be trimmed if it exceeds `array.length`. If `limit` is undefined,
  17267. * the input will be returned unchanged.
  17268. * @param {(string|number)=} begin Index at which to begin limitation. As a negative index, `begin`
  17269. * indicates an offset from the end of `input`. Defaults to `0`.
  17270. * @returns {Array|string} A new sub-array or substring of length `limit` or less if input array
  17271. * had less than `limit` elements.
  17272. *
  17273. * @example
  17274. <example module="limitToExample">
  17275. <file name="index.html">
  17276. <script>
  17277. angular.module('limitToExample', [])
  17278. .controller('ExampleController', ['$scope', function($scope) {
  17279. $scope.numbers = [1,2,3,4,5,6,7,8,9];
  17280. $scope.letters = "abcdefghi";
  17281. $scope.longNumber = 2345432342;
  17282. $scope.numLimit = 3;
  17283. $scope.letterLimit = 3;
  17284. $scope.longNumberLimit = 3;
  17285. }]);
  17286. </script>
  17287. <div ng-controller="ExampleController">
  17288. <label>
  17289. Limit {{numbers}} to:
  17290. <input type="number" step="1" ng-model="numLimit">
  17291. </label>
  17292. <p>Output numbers: {{ numbers | limitTo:numLimit }}</p>
  17293. <label>
  17294. Limit {{letters}} to:
  17295. <input type="number" step="1" ng-model="letterLimit">
  17296. </label>
  17297. <p>Output letters: {{ letters | limitTo:letterLimit }}</p>
  17298. <label>
  17299. Limit {{longNumber}} to:
  17300. <input type="number" step="1" ng-model="longNumberLimit">
  17301. </label>
  17302. <p>Output long number: {{ longNumber | limitTo:longNumberLimit }}</p>
  17303. </div>
  17304. </file>
  17305. <file name="protractor.js" type="protractor">
  17306. var numLimitInput = element(by.model('numLimit'));
  17307. var letterLimitInput = element(by.model('letterLimit'));
  17308. var longNumberLimitInput = element(by.model('longNumberLimit'));
  17309. var limitedNumbers = element(by.binding('numbers | limitTo:numLimit'));
  17310. var limitedLetters = element(by.binding('letters | limitTo:letterLimit'));
  17311. var limitedLongNumber = element(by.binding('longNumber | limitTo:longNumberLimit'));
  17312. it('should limit the number array to first three items', function() {
  17313. expect(numLimitInput.getAttribute('value')).toBe('3');
  17314. expect(letterLimitInput.getAttribute('value')).toBe('3');
  17315. expect(longNumberLimitInput.getAttribute('value')).toBe('3');
  17316. expect(limitedNumbers.getText()).toEqual('Output numbers: [1,2,3]');
  17317. expect(limitedLetters.getText()).toEqual('Output letters: abc');
  17318. expect(limitedLongNumber.getText()).toEqual('Output long number: 234');
  17319. });
  17320. // There is a bug in safari and protractor that doesn't like the minus key
  17321. // it('should update the output when -3 is entered', function() {
  17322. // numLimitInput.clear();
  17323. // numLimitInput.sendKeys('-3');
  17324. // letterLimitInput.clear();
  17325. // letterLimitInput.sendKeys('-3');
  17326. // longNumberLimitInput.clear();
  17327. // longNumberLimitInput.sendKeys('-3');
  17328. // expect(limitedNumbers.getText()).toEqual('Output numbers: [7,8,9]');
  17329. // expect(limitedLetters.getText()).toEqual('Output letters: ghi');
  17330. // expect(limitedLongNumber.getText()).toEqual('Output long number: 342');
  17331. // });
  17332. it('should not exceed the maximum size of input array', function() {
  17333. numLimitInput.clear();
  17334. numLimitInput.sendKeys('100');
  17335. letterLimitInput.clear();
  17336. letterLimitInput.sendKeys('100');
  17337. longNumberLimitInput.clear();
  17338. longNumberLimitInput.sendKeys('100');
  17339. expect(limitedNumbers.getText()).toEqual('Output numbers: [1,2,3,4,5,6,7,8,9]');
  17340. expect(limitedLetters.getText()).toEqual('Output letters: abcdefghi');
  17341. expect(limitedLongNumber.getText()).toEqual('Output long number: 2345432342');
  17342. });
  17343. </file>
  17344. </example>
  17345. */
  17346. function limitToFilter() {
  17347. return function(input, limit, begin) {
  17348. if (Math.abs(Number(limit)) === Infinity) {
  17349. limit = Number(limit);
  17350. } else {
  17351. limit = toInt(limit);
  17352. }
  17353. if (isNaN(limit)) return input;
  17354. if (isNumber(input)) input = input.toString();
  17355. if (!isArray(input) && !isString(input)) return input;
  17356. begin = (!begin || isNaN(begin)) ? 0 : toInt(begin);
  17357. begin = (begin < 0 && begin >= -input.length) ? input.length + begin : begin;
  17358. if (limit >= 0) {
  17359. return input.slice(begin, begin + limit);
  17360. } else {
  17361. if (begin === 0) {
  17362. return input.slice(limit, input.length);
  17363. } else {
  17364. return input.slice(Math.max(0, begin + limit), begin);
  17365. }
  17366. }
  17367. };
  17368. }
  17369. /**
  17370. * @ngdoc filter
  17371. * @name orderBy
  17372. * @kind function
  17373. *
  17374. * @description
  17375. * Orders a specified `array` by the `expression` predicate. It is ordered alphabetically
  17376. * for strings and numerically for numbers. Note: if you notice numbers are not being sorted
  17377. * as expected, make sure they are actually being saved as numbers and not strings.
  17378. *
  17379. * @param {Array} array The array to sort.
  17380. * @param {function(*)|string|Array.<(function(*)|string)>=} expression A predicate to be
  17381. * used by the comparator to determine the order of elements.
  17382. *
  17383. * Can be one of:
  17384. *
  17385. * - `function`: Getter function. The result of this function will be sorted using the
  17386. * `<`, `===`, `>` operator.
  17387. * - `string`: An Angular expression. The result of this expression is used to compare elements
  17388. * (for example `name` to sort by a property called `name` or `name.substr(0, 3)` to sort by
  17389. * 3 first characters of a property called `name`). The result of a constant expression
  17390. * is interpreted as a property name to be used in comparisons (for example `"special name"`
  17391. * to sort object by the value of their `special name` property). An expression can be
  17392. * optionally prefixed with `+` or `-` to control ascending or descending sort order
  17393. * (for example, `+name` or `-name`). If no property is provided, (e.g. `'+'`) then the array
  17394. * element itself is used to compare where sorting.
  17395. * - `Array`: An array of function or string predicates. The first predicate in the array
  17396. * is used for sorting, but when two items are equivalent, the next predicate is used.
  17397. *
  17398. * If the predicate is missing or empty then it defaults to `'+'`.
  17399. *
  17400. * @param {boolean=} reverse Reverse the order of the array.
  17401. * @returns {Array} Sorted copy of the source array.
  17402. *
  17403. *
  17404. * @example
  17405. * The example below demonstrates a simple ngRepeat, where the data is sorted
  17406. * by age in descending order (predicate is set to `'-age'`).
  17407. * `reverse` is not set, which means it defaults to `false`.
  17408. <example module="orderByExample">
  17409. <file name="index.html">
  17410. <script>
  17411. angular.module('orderByExample', [])
  17412. .controller('ExampleController', ['$scope', function($scope) {
  17413. $scope.friends =
  17414. [{name:'John', phone:'555-1212', age:10},
  17415. {name:'Mary', phone:'555-9876', age:19},
  17416. {name:'Mike', phone:'555-4321', age:21},
  17417. {name:'Adam', phone:'555-5678', age:35},
  17418. {name:'Julie', phone:'555-8765', age:29}];
  17419. }]);
  17420. </script>
  17421. <div ng-controller="ExampleController">
  17422. <table class="friend">
  17423. <tr>
  17424. <th>Name</th>
  17425. <th>Phone Number</th>
  17426. <th>Age</th>
  17427. </tr>
  17428. <tr ng-repeat="friend in friends | orderBy:'-age'">
  17429. <td>{{friend.name}}</td>
  17430. <td>{{friend.phone}}</td>
  17431. <td>{{friend.age}}</td>
  17432. </tr>
  17433. </table>
  17434. </div>
  17435. </file>
  17436. </example>
  17437. *
  17438. * The predicate and reverse parameters can be controlled dynamically through scope properties,
  17439. * as shown in the next example.
  17440. * @example
  17441. <example module="orderByExample">
  17442. <file name="index.html">
  17443. <script>
  17444. angular.module('orderByExample', [])
  17445. .controller('ExampleController', ['$scope', function($scope) {
  17446. $scope.friends =
  17447. [{name:'John', phone:'555-1212', age:10},
  17448. {name:'Mary', phone:'555-9876', age:19},
  17449. {name:'Mike', phone:'555-4321', age:21},
  17450. {name:'Adam', phone:'555-5678', age:35},
  17451. {name:'Julie', phone:'555-8765', age:29}];
  17452. $scope.predicate = 'age';
  17453. $scope.reverse = true;
  17454. $scope.order = function(predicate) {
  17455. $scope.reverse = ($scope.predicate === predicate) ? !$scope.reverse : false;
  17456. $scope.predicate = predicate;
  17457. };
  17458. }]);
  17459. </script>
  17460. <style type="text/css">
  17461. .sortorder:after {
  17462. content: '\25b2';
  17463. }
  17464. .sortorder.reverse:after {
  17465. content: '\25bc';
  17466. }
  17467. </style>
  17468. <div ng-controller="ExampleController">
  17469. <pre>Sorting predicate = {{predicate}}; reverse = {{reverse}}</pre>
  17470. <hr/>
  17471. [ <a href="" ng-click="predicate=''">unsorted</a> ]
  17472. <table class="friend">
  17473. <tr>
  17474. <th>
  17475. <a href="" ng-click="order('name')">Name</a>
  17476. <span class="sortorder" ng-show="predicate === 'name'" ng-class="{reverse:reverse}"></span>
  17477. </th>
  17478. <th>
  17479. <a href="" ng-click="order('phone')">Phone Number</a>
  17480. <span class="sortorder" ng-show="predicate === 'phone'" ng-class="{reverse:reverse}"></span>
  17481. </th>
  17482. <th>
  17483. <a href="" ng-click="order('age')">Age</a>
  17484. <span class="sortorder" ng-show="predicate === 'age'" ng-class="{reverse:reverse}"></span>
  17485. </th>
  17486. </tr>
  17487. <tr ng-repeat="friend in friends | orderBy:predicate:reverse">
  17488. <td>{{friend.name}}</td>
  17489. <td>{{friend.phone}}</td>
  17490. <td>{{friend.age}}</td>
  17491. </tr>
  17492. </table>
  17493. </div>
  17494. </file>
  17495. </example>
  17496. *
  17497. * It's also possible to call the orderBy filter manually, by injecting `$filter`, retrieving the
  17498. * filter routine with `$filter('orderBy')`, and calling the returned filter routine with the
  17499. * desired parameters.
  17500. *
  17501. * Example:
  17502. *
  17503. * @example
  17504. <example module="orderByExample">
  17505. <file name="index.html">
  17506. <div ng-controller="ExampleController">
  17507. <table class="friend">
  17508. <tr>
  17509. <th><a href="" ng-click="reverse=false;order('name', false)">Name</a>
  17510. (<a href="" ng-click="order('-name',false)">^</a>)</th>
  17511. <th><a href="" ng-click="reverse=!reverse;order('phone', reverse)">Phone Number</a></th>
  17512. <th><a href="" ng-click="reverse=!reverse;order('age',reverse)">Age</a></th>
  17513. </tr>
  17514. <tr ng-repeat="friend in friends">
  17515. <td>{{friend.name}}</td>
  17516. <td>{{friend.phone}}</td>
  17517. <td>{{friend.age}}</td>
  17518. </tr>
  17519. </table>
  17520. </div>
  17521. </file>
  17522. <file name="script.js">
  17523. angular.module('orderByExample', [])
  17524. .controller('ExampleController', ['$scope', '$filter', function($scope, $filter) {
  17525. var orderBy = $filter('orderBy');
  17526. $scope.friends = [
  17527. { name: 'John', phone: '555-1212', age: 10 },
  17528. { name: 'Mary', phone: '555-9876', age: 19 },
  17529. { name: 'Mike', phone: '555-4321', age: 21 },
  17530. { name: 'Adam', phone: '555-5678', age: 35 },
  17531. { name: 'Julie', phone: '555-8765', age: 29 }
  17532. ];
  17533. $scope.order = function(predicate, reverse) {
  17534. $scope.friends = orderBy($scope.friends, predicate, reverse);
  17535. };
  17536. $scope.order('-age',false);
  17537. }]);
  17538. </file>
  17539. </example>
  17540. */
  17541. orderByFilter.$inject = ['$parse'];
  17542. function orderByFilter($parse) {
  17543. return function(array, sortPredicate, reverseOrder) {
  17544. if (!(isArrayLike(array))) return array;
  17545. if (!isArray(sortPredicate)) { sortPredicate = [sortPredicate]; }
  17546. if (sortPredicate.length === 0) { sortPredicate = ['+']; }
  17547. var predicates = processPredicates(sortPredicate, reverseOrder);
  17548. // Add a predicate at the end that evaluates to the element index. This makes the
  17549. // sort stable as it works as a tie-breaker when all the input predicates cannot
  17550. // distinguish between two elements.
  17551. predicates.push({ get: function() { return {}; }, descending: reverseOrder ? -1 : 1});
  17552. // The next three lines are a version of a Swartzian Transform idiom from Perl
  17553. // (sometimes called the Decorate-Sort-Undecorate idiom)
  17554. // See https://en.wikipedia.org/wiki/Schwartzian_transform
  17555. var compareValues = Array.prototype.map.call(array, getComparisonObject);
  17556. compareValues.sort(doComparison);
  17557. array = compareValues.map(function(item) { return item.value; });
  17558. return array;
  17559. function getComparisonObject(value, index) {
  17560. return {
  17561. value: value,
  17562. predicateValues: predicates.map(function(predicate) {
  17563. return getPredicateValue(predicate.get(value), index);
  17564. })
  17565. };
  17566. }
  17567. function doComparison(v1, v2) {
  17568. var result = 0;
  17569. for (var index=0, length = predicates.length; index < length; ++index) {
  17570. result = compare(v1.predicateValues[index], v2.predicateValues[index]) * predicates[index].descending;
  17571. if (result) break;
  17572. }
  17573. return result;
  17574. }
  17575. };
  17576. function processPredicates(sortPredicate, reverseOrder) {
  17577. reverseOrder = reverseOrder ? -1 : 1;
  17578. return sortPredicate.map(function(predicate) {
  17579. var descending = 1, get = identity;
  17580. if (isFunction(predicate)) {
  17581. get = predicate;
  17582. } else if (isString(predicate)) {
  17583. if ((predicate.charAt(0) == '+' || predicate.charAt(0) == '-')) {
  17584. descending = predicate.charAt(0) == '-' ? -1 : 1;
  17585. predicate = predicate.substring(1);
  17586. }
  17587. if (predicate !== '') {
  17588. get = $parse(predicate);
  17589. if (get.constant) {
  17590. var key = get();
  17591. get = function(value) { return value[key]; };
  17592. }
  17593. }
  17594. }
  17595. return { get: get, descending: descending * reverseOrder };
  17596. });
  17597. }
  17598. function isPrimitive(value) {
  17599. switch (typeof value) {
  17600. case 'number': /* falls through */
  17601. case 'boolean': /* falls through */
  17602. case 'string':
  17603. return true;
  17604. default:
  17605. return false;
  17606. }
  17607. }
  17608. function objectValue(value, index) {
  17609. // If `valueOf` is a valid function use that
  17610. if (typeof value.valueOf === 'function') {
  17611. value = value.valueOf();
  17612. if (isPrimitive(value)) return value;
  17613. }
  17614. // If `toString` is a valid function and not the one from `Object.prototype` use that
  17615. if (hasCustomToString(value)) {
  17616. value = value.toString();
  17617. if (isPrimitive(value)) return value;
  17618. }
  17619. // We have a basic object so we use the position of the object in the collection
  17620. return index;
  17621. }
  17622. function getPredicateValue(value, index) {
  17623. var type = typeof value;
  17624. if (value === null) {
  17625. type = 'string';
  17626. value = 'null';
  17627. } else if (type === 'string') {
  17628. value = value.toLowerCase();
  17629. } else if (type === 'object') {
  17630. value = objectValue(value, index);
  17631. }
  17632. return { value: value, type: type };
  17633. }
  17634. function compare(v1, v2) {
  17635. var result = 0;
  17636. if (v1.type === v2.type) {
  17637. if (v1.value !== v2.value) {
  17638. result = v1.value < v2.value ? -1 : 1;
  17639. }
  17640. } else {
  17641. result = v1.type < v2.type ? -1 : 1;
  17642. }
  17643. return result;
  17644. }
  17645. }
  17646. function ngDirective(directive) {
  17647. if (isFunction(directive)) {
  17648. directive = {
  17649. link: directive
  17650. };
  17651. }
  17652. directive.restrict = directive.restrict || 'AC';
  17653. return valueFn(directive);
  17654. }
  17655. /**
  17656. * @ngdoc directive
  17657. * @name a
  17658. * @restrict E
  17659. *
  17660. * @description
  17661. * Modifies the default behavior of the html A tag so that the default action is prevented when
  17662. * the href attribute is empty.
  17663. *
  17664. * This change permits the easy creation of action links with the `ngClick` directive
  17665. * without changing the location or causing page reloads, e.g.:
  17666. * `<a href="" ng-click="list.addItem()">Add Item</a>`
  17667. */
  17668. var htmlAnchorDirective = valueFn({
  17669. restrict: 'E',
  17670. compile: function(element, attr) {
  17671. if (!attr.href && !attr.xlinkHref) {
  17672. return function(scope, element) {
  17673. // If the linked element is not an anchor tag anymore, do nothing
  17674. if (element[0].nodeName.toLowerCase() !== 'a') return;
  17675. // SVGAElement does not use the href attribute, but rather the 'xlinkHref' attribute.
  17676. var href = toString.call(element.prop('href')) === '[object SVGAnimatedString]' ?
  17677. 'xlink:href' : 'href';
  17678. element.on('click', function(event) {
  17679. // if we have no href url, then don't navigate anywhere.
  17680. if (!element.attr(href)) {
  17681. event.preventDefault();
  17682. }
  17683. });
  17684. };
  17685. }
  17686. }
  17687. });
  17688. /**
  17689. * @ngdoc directive
  17690. * @name ngHref
  17691. * @restrict A
  17692. * @priority 99
  17693. *
  17694. * @description
  17695. * Using Angular markup like `{{hash}}` in an href attribute will
  17696. * make the link go to the wrong URL if the user clicks it before
  17697. * Angular has a chance to replace the `{{hash}}` markup with its
  17698. * value. Until Angular replaces the markup the link will be broken
  17699. * and will most likely return a 404 error. The `ngHref` directive
  17700. * solves this problem.
  17701. *
  17702. * The wrong way to write it:
  17703. * ```html
  17704. * <a href="http://www.gravatar.com/avatar/{{hash}}">link1</a>
  17705. * ```
  17706. *
  17707. * The correct way to write it:
  17708. * ```html
  17709. * <a ng-href="http://www.gravatar.com/avatar/{{hash}}">link1</a>
  17710. * ```
  17711. *
  17712. * @element A
  17713. * @param {template} ngHref any string which can contain `{{}}` markup.
  17714. *
  17715. * @example
  17716. * This example shows various combinations of `href`, `ng-href` and `ng-click` attributes
  17717. * in links and their different behaviors:
  17718. <example>
  17719. <file name="index.html">
  17720. <input ng-model="value" /><br />
  17721. <a id="link-1" href ng-click="value = 1">link 1</a> (link, don't reload)<br />
  17722. <a id="link-2" href="" ng-click="value = 2">link 2</a> (link, don't reload)<br />
  17723. <a id="link-3" ng-href="/{{'123'}}">link 3</a> (link, reload!)<br />
  17724. <a id="link-4" href="" name="xx" ng-click="value = 4">anchor</a> (link, don't reload)<br />
  17725. <a id="link-5" name="xxx" ng-click="value = 5">anchor</a> (no link)<br />
  17726. <a id="link-6" ng-href="{{value}}">link</a> (link, change location)
  17727. </file>
  17728. <file name="protractor.js" type="protractor">
  17729. it('should execute ng-click but not reload when href without value', function() {
  17730. element(by.id('link-1')).click();
  17731. expect(element(by.model('value')).getAttribute('value')).toEqual('1');
  17732. expect(element(by.id('link-1')).getAttribute('href')).toBe('');
  17733. });
  17734. it('should execute ng-click but not reload when href empty string', function() {
  17735. element(by.id('link-2')).click();
  17736. expect(element(by.model('value')).getAttribute('value')).toEqual('2');
  17737. expect(element(by.id('link-2')).getAttribute('href')).toBe('');
  17738. });
  17739. it('should execute ng-click and change url when ng-href specified', function() {
  17740. expect(element(by.id('link-3')).getAttribute('href')).toMatch(/\/123$/);
  17741. element(by.id('link-3')).click();
  17742. // At this point, we navigate away from an Angular page, so we need
  17743. // to use browser.driver to get the base webdriver.
  17744. browser.wait(function() {
  17745. return browser.driver.getCurrentUrl().then(function(url) {
  17746. return url.match(/\/123$/);
  17747. });
  17748. }, 5000, 'page should navigate to /123');
  17749. });
  17750. it('should execute ng-click but not reload when href empty string and name specified', function() {
  17751. element(by.id('link-4')).click();
  17752. expect(element(by.model('value')).getAttribute('value')).toEqual('4');
  17753. expect(element(by.id('link-4')).getAttribute('href')).toBe('');
  17754. });
  17755. it('should execute ng-click but not reload when no href but name specified', function() {
  17756. element(by.id('link-5')).click();
  17757. expect(element(by.model('value')).getAttribute('value')).toEqual('5');
  17758. expect(element(by.id('link-5')).getAttribute('href')).toBe(null);
  17759. });
  17760. it('should only change url when only ng-href', function() {
  17761. element(by.model('value')).clear();
  17762. element(by.model('value')).sendKeys('6');
  17763. expect(element(by.id('link-6')).getAttribute('href')).toMatch(/\/6$/);
  17764. element(by.id('link-6')).click();
  17765. // At this point, we navigate away from an Angular page, so we need
  17766. // to use browser.driver to get the base webdriver.
  17767. browser.wait(function() {
  17768. return browser.driver.getCurrentUrl().then(function(url) {
  17769. return url.match(/\/6$/);
  17770. });
  17771. }, 5000, 'page should navigate to /6');
  17772. });
  17773. </file>
  17774. </example>
  17775. */
  17776. /**
  17777. * @ngdoc directive
  17778. * @name ngSrc
  17779. * @restrict A
  17780. * @priority 99
  17781. *
  17782. * @description
  17783. * Using Angular markup like `{{hash}}` in a `src` attribute doesn't
  17784. * work right: The browser will fetch from the URL with the literal
  17785. * text `{{hash}}` until Angular replaces the expression inside
  17786. * `{{hash}}`. The `ngSrc` directive solves this problem.
  17787. *
  17788. * The buggy way to write it:
  17789. * ```html
  17790. * <img src="http://www.gravatar.com/avatar/{{hash}}" alt="Description"/>
  17791. * ```
  17792. *
  17793. * The correct way to write it:
  17794. * ```html
  17795. * <img ng-src="http://www.gravatar.com/avatar/{{hash}}" alt="Description" />
  17796. * ```
  17797. *
  17798. * @element IMG
  17799. * @param {template} ngSrc any string which can contain `{{}}` markup.
  17800. */
  17801. /**
  17802. * @ngdoc directive
  17803. * @name ngSrcset
  17804. * @restrict A
  17805. * @priority 99
  17806. *
  17807. * @description
  17808. * Using Angular markup like `{{hash}}` in a `srcset` attribute doesn't
  17809. * work right: The browser will fetch from the URL with the literal
  17810. * text `{{hash}}` until Angular replaces the expression inside
  17811. * `{{hash}}`. The `ngSrcset` directive solves this problem.
  17812. *
  17813. * The buggy way to write it:
  17814. * ```html
  17815. * <img srcset="http://www.gravatar.com/avatar/{{hash}} 2x" alt="Description"/>
  17816. * ```
  17817. *
  17818. * The correct way to write it:
  17819. * ```html
  17820. * <img ng-srcset="http://www.gravatar.com/avatar/{{hash}} 2x" alt="Description" />
  17821. * ```
  17822. *
  17823. * @element IMG
  17824. * @param {template} ngSrcset any string which can contain `{{}}` markup.
  17825. */
  17826. /**
  17827. * @ngdoc directive
  17828. * @name ngDisabled
  17829. * @restrict A
  17830. * @priority 100
  17831. *
  17832. * @description
  17833. *
  17834. * This directive sets the `disabled` attribute on the element if the
  17835. * {@link guide/expression expression} inside `ngDisabled` evaluates to truthy.
  17836. *
  17837. * A special directive is necessary because we cannot use interpolation inside the `disabled`
  17838. * attribute. The following example would make the button enabled on Chrome/Firefox
  17839. * but not on older IEs:
  17840. *
  17841. * ```html
  17842. * <!-- See below for an example of ng-disabled being used correctly -->
  17843. * <div ng-init="isDisabled = false">
  17844. * <button disabled="{{isDisabled}}">Disabled</button>
  17845. * </div>
  17846. * ```
  17847. *
  17848. * This is because the HTML specification does not require browsers to preserve the values of
  17849. * boolean attributes such as `disabled` (Their presence means true and their absence means false.)
  17850. * If we put an Angular interpolation expression into such an attribute then the
  17851. * binding information would be lost when the browser removes the attribute.
  17852. *
  17853. * @example
  17854. <example>
  17855. <file name="index.html">
  17856. <label>Click me to toggle: <input type="checkbox" ng-model="checked"></label><br/>
  17857. <button ng-model="button" ng-disabled="checked">Button</button>
  17858. </file>
  17859. <file name="protractor.js" type="protractor">
  17860. it('should toggle button', function() {
  17861. expect(element(by.css('button')).getAttribute('disabled')).toBeFalsy();
  17862. element(by.model('checked')).click();
  17863. expect(element(by.css('button')).getAttribute('disabled')).toBeTruthy();
  17864. });
  17865. </file>
  17866. </example>
  17867. *
  17868. * @element INPUT
  17869. * @param {expression} ngDisabled If the {@link guide/expression expression} is truthy,
  17870. * then the `disabled` attribute will be set on the element
  17871. */
  17872. /**
  17873. * @ngdoc directive
  17874. * @name ngChecked
  17875. * @restrict A
  17876. * @priority 100
  17877. *
  17878. * @description
  17879. * Sets the `checked` attribute on the element, if the expression inside `ngChecked` is truthy.
  17880. *
  17881. * Note that this directive should not be used together with {@link ngModel `ngModel`},
  17882. * as this can lead to unexpected behavior.
  17883. *
  17884. * ### Why do we need `ngChecked`?
  17885. *
  17886. * The HTML specification does not require browsers to preserve the values of boolean attributes
  17887. * such as checked. (Their presence means true and their absence means false.)
  17888. * If we put an Angular interpolation expression into such an attribute then the
  17889. * binding information would be lost when the browser removes the attribute.
  17890. * The `ngChecked` directive solves this problem for the `checked` attribute.
  17891. * This complementary directive is not removed by the browser and so provides
  17892. * a permanent reliable place to store the binding information.
  17893. * @example
  17894. <example>
  17895. <file name="index.html">
  17896. <label>Check me to check both: <input type="checkbox" ng-model="master"></label><br/>
  17897. <input id="checkSlave" type="checkbox" ng-checked="master" aria-label="Slave input">
  17898. </file>
  17899. <file name="protractor.js" type="protractor">
  17900. it('should check both checkBoxes', function() {
  17901. expect(element(by.id('checkSlave')).getAttribute('checked')).toBeFalsy();
  17902. element(by.model('master')).click();
  17903. expect(element(by.id('checkSlave')).getAttribute('checked')).toBeTruthy();
  17904. });
  17905. </file>
  17906. </example>
  17907. *
  17908. * @element INPUT
  17909. * @param {expression} ngChecked If the {@link guide/expression expression} is truthy,
  17910. * then the `checked` attribute will be set on the element
  17911. */
  17912. /**
  17913. * @ngdoc directive
  17914. * @name ngReadonly
  17915. * @restrict A
  17916. * @priority 100
  17917. *
  17918. * @description
  17919. * The HTML specification does not require browsers to preserve the values of boolean attributes
  17920. * such as readonly. (Their presence means true and their absence means false.)
  17921. * If we put an Angular interpolation expression into such an attribute then the
  17922. * binding information would be lost when the browser removes the attribute.
  17923. * The `ngReadonly` directive solves this problem for the `readonly` attribute.
  17924. * This complementary directive is not removed by the browser and so provides
  17925. * a permanent reliable place to store the binding information.
  17926. * @example
  17927. <example>
  17928. <file name="index.html">
  17929. <label>Check me to make text readonly: <input type="checkbox" ng-model="checked"></label><br/>
  17930. <input type="text" ng-readonly="checked" value="I'm Angular" aria-label="Readonly field" />
  17931. </file>
  17932. <file name="protractor.js" type="protractor">
  17933. it('should toggle readonly attr', function() {
  17934. expect(element(by.css('[type="text"]')).getAttribute('readonly')).toBeFalsy();
  17935. element(by.model('checked')).click();
  17936. expect(element(by.css('[type="text"]')).getAttribute('readonly')).toBeTruthy();
  17937. });
  17938. </file>
  17939. </example>
  17940. *
  17941. * @element INPUT
  17942. * @param {expression} ngReadonly If the {@link guide/expression expression} is truthy,
  17943. * then special attribute "readonly" will be set on the element
  17944. */
  17945. /**
  17946. * @ngdoc directive
  17947. * @name ngSelected
  17948. * @restrict A
  17949. * @priority 100
  17950. *
  17951. * @description
  17952. * The HTML specification does not require browsers to preserve the values of boolean attributes
  17953. * such as selected. (Their presence means true and their absence means false.)
  17954. * If we put an Angular interpolation expression into such an attribute then the
  17955. * binding information would be lost when the browser removes the attribute.
  17956. * The `ngSelected` directive solves this problem for the `selected` attribute.
  17957. * This complementary directive is not removed by the browser and so provides
  17958. * a permanent reliable place to store the binding information.
  17959. *
  17960. * @example
  17961. <example>
  17962. <file name="index.html">
  17963. <label>Check me to select: <input type="checkbox" ng-model="selected"></label><br/>
  17964. <select aria-label="ngSelected demo">
  17965. <option>Hello!</option>
  17966. <option id="greet" ng-selected="selected">Greetings!</option>
  17967. </select>
  17968. </file>
  17969. <file name="protractor.js" type="protractor">
  17970. it('should select Greetings!', function() {
  17971. expect(element(by.id('greet')).getAttribute('selected')).toBeFalsy();
  17972. element(by.model('selected')).click();
  17973. expect(element(by.id('greet')).getAttribute('selected')).toBeTruthy();
  17974. });
  17975. </file>
  17976. </example>
  17977. *
  17978. * @element OPTION
  17979. * @param {expression} ngSelected If the {@link guide/expression expression} is truthy,
  17980. * then special attribute "selected" will be set on the element
  17981. */
  17982. /**
  17983. * @ngdoc directive
  17984. * @name ngOpen
  17985. * @restrict A
  17986. * @priority 100
  17987. *
  17988. * @description
  17989. * The HTML specification does not require browsers to preserve the values of boolean attributes
  17990. * such as open. (Their presence means true and their absence means false.)
  17991. * If we put an Angular interpolation expression into such an attribute then the
  17992. * binding information would be lost when the browser removes the attribute.
  17993. * The `ngOpen` directive solves this problem for the `open` attribute.
  17994. * This complementary directive is not removed by the browser and so provides
  17995. * a permanent reliable place to store the binding information.
  17996. * @example
  17997. <example>
  17998. <file name="index.html">
  17999. <label>Check me check multiple: <input type="checkbox" ng-model="open"></label><br/>
  18000. <details id="details" ng-open="open">
  18001. <summary>Show/Hide me</summary>
  18002. </details>
  18003. </file>
  18004. <file name="protractor.js" type="protractor">
  18005. it('should toggle open', function() {
  18006. expect(element(by.id('details')).getAttribute('open')).toBeFalsy();
  18007. element(by.model('open')).click();
  18008. expect(element(by.id('details')).getAttribute('open')).toBeTruthy();
  18009. });
  18010. </file>
  18011. </example>
  18012. *
  18013. * @element DETAILS
  18014. * @param {expression} ngOpen If the {@link guide/expression expression} is truthy,
  18015. * then special attribute "open" will be set on the element
  18016. */
  18017. var ngAttributeAliasDirectives = {};
  18018. // boolean attrs are evaluated
  18019. forEach(BOOLEAN_ATTR, function(propName, attrName) {
  18020. // binding to multiple is not supported
  18021. if (propName == "multiple") return;
  18022. function defaultLinkFn(scope, element, attr) {
  18023. scope.$watch(attr[normalized], function ngBooleanAttrWatchAction(value) {
  18024. attr.$set(attrName, !!value);
  18025. });
  18026. }
  18027. var normalized = directiveNormalize('ng-' + attrName);
  18028. var linkFn = defaultLinkFn;
  18029. if (propName === 'checked') {
  18030. linkFn = function(scope, element, attr) {
  18031. // ensuring ngChecked doesn't interfere with ngModel when both are set on the same input
  18032. if (attr.ngModel !== attr[normalized]) {
  18033. defaultLinkFn(scope, element, attr);
  18034. }
  18035. };
  18036. }
  18037. ngAttributeAliasDirectives[normalized] = function() {
  18038. return {
  18039. restrict: 'A',
  18040. priority: 100,
  18041. link: linkFn
  18042. };
  18043. };
  18044. });
  18045. // aliased input attrs are evaluated
  18046. forEach(ALIASED_ATTR, function(htmlAttr, ngAttr) {
  18047. ngAttributeAliasDirectives[ngAttr] = function() {
  18048. return {
  18049. priority: 100,
  18050. link: function(scope, element, attr) {
  18051. //special case ngPattern when a literal regular expression value
  18052. //is used as the expression (this way we don't have to watch anything).
  18053. if (ngAttr === "ngPattern" && attr.ngPattern.charAt(0) == "/") {
  18054. var match = attr.ngPattern.match(REGEX_STRING_REGEXP);
  18055. if (match) {
  18056. attr.$set("ngPattern", new RegExp(match[1], match[2]));
  18057. return;
  18058. }
  18059. }
  18060. scope.$watch(attr[ngAttr], function ngAttrAliasWatchAction(value) {
  18061. attr.$set(ngAttr, value);
  18062. });
  18063. }
  18064. };
  18065. };
  18066. });
  18067. // ng-src, ng-srcset, ng-href are interpolated
  18068. forEach(['src', 'srcset', 'href'], function(attrName) {
  18069. var normalized = directiveNormalize('ng-' + attrName);
  18070. ngAttributeAliasDirectives[normalized] = function() {
  18071. return {
  18072. priority: 99, // it needs to run after the attributes are interpolated
  18073. link: function(scope, element, attr) {
  18074. var propName = attrName,
  18075. name = attrName;
  18076. if (attrName === 'href' &&
  18077. toString.call(element.prop('href')) === '[object SVGAnimatedString]') {
  18078. name = 'xlinkHref';
  18079. attr.$attr[name] = 'xlink:href';
  18080. propName = null;
  18081. }
  18082. attr.$observe(normalized, function(value) {
  18083. if (!value) {
  18084. if (attrName === 'href') {
  18085. attr.$set(name, null);
  18086. }
  18087. return;
  18088. }
  18089. attr.$set(name, value);
  18090. // on IE, if "ng:src" directive declaration is used and "src" attribute doesn't exist
  18091. // then calling element.setAttribute('src', 'foo') doesn't do anything, so we need
  18092. // to set the property as well to achieve the desired effect.
  18093. // we use attr[attrName] value since $set can sanitize the url.
  18094. if (msie && propName) element.prop(propName, attr[name]);
  18095. });
  18096. }
  18097. };
  18098. };
  18099. });
  18100. /* global -nullFormCtrl, -SUBMITTED_CLASS, addSetValidityMethod: true
  18101. */
  18102. var nullFormCtrl = {
  18103. $addControl: noop,
  18104. $$renameControl: nullFormRenameControl,
  18105. $removeControl: noop,
  18106. $setValidity: noop,
  18107. $setDirty: noop,
  18108. $setPristine: noop,
  18109. $setSubmitted: noop
  18110. },
  18111. SUBMITTED_CLASS = 'ng-submitted';
  18112. function nullFormRenameControl(control, name) {
  18113. control.$name = name;
  18114. }
  18115. /**
  18116. * @ngdoc type
  18117. * @name form.FormController
  18118. *
  18119. * @property {boolean} $pristine True if user has not interacted with the form yet.
  18120. * @property {boolean} $dirty True if user has already interacted with the form.
  18121. * @property {boolean} $valid True if all of the containing forms and controls are valid.
  18122. * @property {boolean} $invalid True if at least one containing control or form is invalid.
  18123. * @property {boolean} $pending True if at least one containing control or form is pending.
  18124. * @property {boolean} $submitted True if user has submitted the form even if its invalid.
  18125. *
  18126. * @property {Object} $error Is an object hash, containing references to controls or
  18127. * forms with failing validators, where:
  18128. *
  18129. * - keys are validation tokens (error names),
  18130. * - values are arrays of controls or forms that have a failing validator for given error name.
  18131. *
  18132. * Built-in validation tokens:
  18133. *
  18134. * - `email`
  18135. * - `max`
  18136. * - `maxlength`
  18137. * - `min`
  18138. * - `minlength`
  18139. * - `number`
  18140. * - `pattern`
  18141. * - `required`
  18142. * - `url`
  18143. * - `date`
  18144. * - `datetimelocal`
  18145. * - `time`
  18146. * - `week`
  18147. * - `month`
  18148. *
  18149. * @description
  18150. * `FormController` keeps track of all its controls and nested forms as well as the state of them,
  18151. * such as being valid/invalid or dirty/pristine.
  18152. *
  18153. * Each {@link ng.directive:form form} directive creates an instance
  18154. * of `FormController`.
  18155. *
  18156. */
  18157. //asks for $scope to fool the BC controller module
  18158. FormController.$inject = ['$element', '$attrs', '$scope', '$animate', '$interpolate'];
  18159. function FormController(element, attrs, $scope, $animate, $interpolate) {
  18160. var form = this,
  18161. controls = [];
  18162. // init state
  18163. form.$error = {};
  18164. form.$$success = {};
  18165. form.$pending = undefined;
  18166. form.$name = $interpolate(attrs.name || attrs.ngForm || '')($scope);
  18167. form.$dirty = false;
  18168. form.$pristine = true;
  18169. form.$valid = true;
  18170. form.$invalid = false;
  18171. form.$submitted = false;
  18172. form.$$parentForm = nullFormCtrl;
  18173. /**
  18174. * @ngdoc method
  18175. * @name form.FormController#$rollbackViewValue
  18176. *
  18177. * @description
  18178. * Rollback all form controls pending updates to the `$modelValue`.
  18179. *
  18180. * Updates may be pending by a debounced event or because the input is waiting for a some future
  18181. * event defined in `ng-model-options`. This method is typically needed by the reset button of
  18182. * a form that uses `ng-model-options` to pend updates.
  18183. */
  18184. form.$rollbackViewValue = function() {
  18185. forEach(controls, function(control) {
  18186. control.$rollbackViewValue();
  18187. });
  18188. };
  18189. /**
  18190. * @ngdoc method
  18191. * @name form.FormController#$commitViewValue
  18192. *
  18193. * @description
  18194. * Commit all form controls pending updates to the `$modelValue`.
  18195. *
  18196. * Updates may be pending by a debounced event or because the input is waiting for a some future
  18197. * event defined in `ng-model-options`. This method is rarely needed as `NgModelController`
  18198. * usually handles calling this in response to input events.
  18199. */
  18200. form.$commitViewValue = function() {
  18201. forEach(controls, function(control) {
  18202. control.$commitViewValue();
  18203. });
  18204. };
  18205. /**
  18206. * @ngdoc method
  18207. * @name form.FormController#$addControl
  18208. * @param {object} control control object, either a {@link form.FormController} or an
  18209. * {@link ngModel.NgModelController}
  18210. *
  18211. * @description
  18212. * Register a control with the form. Input elements using ngModelController do this automatically
  18213. * when they are linked.
  18214. *
  18215. * Note that the current state of the control will not be reflected on the new parent form. This
  18216. * is not an issue with normal use, as freshly compiled and linked controls are in a `$pristine`
  18217. * state.
  18218. *
  18219. * However, if the method is used programmatically, for example by adding dynamically created controls,
  18220. * or controls that have been previously removed without destroying their corresponding DOM element,
  18221. * it's the developers responsiblity to make sure the current state propagates to the parent form.
  18222. *
  18223. * For example, if an input control is added that is already `$dirty` and has `$error` properties,
  18224. * calling `$setDirty()` and `$validate()` afterwards will propagate the state to the parent form.
  18225. */
  18226. form.$addControl = function(control) {
  18227. // Breaking change - before, inputs whose name was "hasOwnProperty" were quietly ignored
  18228. // and not added to the scope. Now we throw an error.
  18229. assertNotHasOwnProperty(control.$name, 'input');
  18230. controls.push(control);
  18231. if (control.$name) {
  18232. form[control.$name] = control;
  18233. }
  18234. control.$$parentForm = form;
  18235. };
  18236. // Private API: rename a form control
  18237. form.$$renameControl = function(control, newName) {
  18238. var oldName = control.$name;
  18239. if (form[oldName] === control) {
  18240. delete form[oldName];
  18241. }
  18242. form[newName] = control;
  18243. control.$name = newName;
  18244. };
  18245. /**
  18246. * @ngdoc method
  18247. * @name form.FormController#$removeControl
  18248. * @param {object} control control object, either a {@link form.FormController} or an
  18249. * {@link ngModel.NgModelController}
  18250. *
  18251. * @description
  18252. * Deregister a control from the form.
  18253. *
  18254. * Input elements using ngModelController do this automatically when they are destroyed.
  18255. *
  18256. * Note that only the removed control's validation state (`$errors`etc.) will be removed from the
  18257. * form. `$dirty`, `$submitted` states will not be changed, because the expected behavior can be
  18258. * different from case to case. For example, removing the only `$dirty` control from a form may or
  18259. * may not mean that the form is still `$dirty`.
  18260. */
  18261. form.$removeControl = function(control) {
  18262. if (control.$name && form[control.$name] === control) {
  18263. delete form[control.$name];
  18264. }
  18265. forEach(form.$pending, function(value, name) {
  18266. form.$setValidity(name, null, control);
  18267. });
  18268. forEach(form.$error, function(value, name) {
  18269. form.$setValidity(name, null, control);
  18270. });
  18271. forEach(form.$$success, function(value, name) {
  18272. form.$setValidity(name, null, control);
  18273. });
  18274. arrayRemove(controls, control);
  18275. control.$$parentForm = nullFormCtrl;
  18276. };
  18277. /**
  18278. * @ngdoc method
  18279. * @name form.FormController#$setValidity
  18280. *
  18281. * @description
  18282. * Sets the validity of a form control.
  18283. *
  18284. * This method will also propagate to parent forms.
  18285. */
  18286. addSetValidityMethod({
  18287. ctrl: this,
  18288. $element: element,
  18289. set: function(object, property, controller) {
  18290. var list = object[property];
  18291. if (!list) {
  18292. object[property] = [controller];
  18293. } else {
  18294. var index = list.indexOf(controller);
  18295. if (index === -1) {
  18296. list.push(controller);
  18297. }
  18298. }
  18299. },
  18300. unset: function(object, property, controller) {
  18301. var list = object[property];
  18302. if (!list) {
  18303. return;
  18304. }
  18305. arrayRemove(list, controller);
  18306. if (list.length === 0) {
  18307. delete object[property];
  18308. }
  18309. },
  18310. $animate: $animate
  18311. });
  18312. /**
  18313. * @ngdoc method
  18314. * @name form.FormController#$setDirty
  18315. *
  18316. * @description
  18317. * Sets the form to a dirty state.
  18318. *
  18319. * This method can be called to add the 'ng-dirty' class and set the form to a dirty
  18320. * state (ng-dirty class). This method will also propagate to parent forms.
  18321. */
  18322. form.$setDirty = function() {
  18323. $animate.removeClass(element, PRISTINE_CLASS);
  18324. $animate.addClass(element, DIRTY_CLASS);
  18325. form.$dirty = true;
  18326. form.$pristine = false;
  18327. form.$$parentForm.$setDirty();
  18328. };
  18329. /**
  18330. * @ngdoc method
  18331. * @name form.FormController#$setPristine
  18332. *
  18333. * @description
  18334. * Sets the form to its pristine state.
  18335. *
  18336. * This method can be called to remove the 'ng-dirty' class and set the form to its pristine
  18337. * state (ng-pristine class). This method will also propagate to all the controls contained
  18338. * in this form.
  18339. *
  18340. * Setting a form back to a pristine state is often useful when we want to 'reuse' a form after
  18341. * saving or resetting it.
  18342. */
  18343. form.$setPristine = function() {
  18344. $animate.setClass(element, PRISTINE_CLASS, DIRTY_CLASS + ' ' + SUBMITTED_CLASS);
  18345. form.$dirty = false;
  18346. form.$pristine = true;
  18347. form.$submitted = false;
  18348. forEach(controls, function(control) {
  18349. control.$setPristine();
  18350. });
  18351. };
  18352. /**
  18353. * @ngdoc method
  18354. * @name form.FormController#$setUntouched
  18355. *
  18356. * @description
  18357. * Sets the form to its untouched state.
  18358. *
  18359. * This method can be called to remove the 'ng-touched' class and set the form controls to their
  18360. * untouched state (ng-untouched class).
  18361. *
  18362. * Setting a form controls back to their untouched state is often useful when setting the form
  18363. * back to its pristine state.
  18364. */
  18365. form.$setUntouched = function() {
  18366. forEach(controls, function(control) {
  18367. control.$setUntouched();
  18368. });
  18369. };
  18370. /**
  18371. * @ngdoc method
  18372. * @name form.FormController#$setSubmitted
  18373. *
  18374. * @description
  18375. * Sets the form to its submitted state.
  18376. */
  18377. form.$setSubmitted = function() {
  18378. $animate.addClass(element, SUBMITTED_CLASS);
  18379. form.$submitted = true;
  18380. form.$$parentForm.$setSubmitted();
  18381. };
  18382. }
  18383. /**
  18384. * @ngdoc directive
  18385. * @name ngForm
  18386. * @restrict EAC
  18387. *
  18388. * @description
  18389. * Nestable alias of {@link ng.directive:form `form`} directive. HTML
  18390. * does not allow nesting of form elements. It is useful to nest forms, for example if the validity of a
  18391. * sub-group of controls needs to be determined.
  18392. *
  18393. * Note: the purpose of `ngForm` is to group controls,
  18394. * but not to be a replacement for the `<form>` tag with all of its capabilities
  18395. * (e.g. posting to the server, ...).
  18396. *
  18397. * @param {string=} ngForm|name Name of the form. If specified, the form controller will be published into
  18398. * related scope, under this name.
  18399. *
  18400. */
  18401. /**
  18402. * @ngdoc directive
  18403. * @name form
  18404. * @restrict E
  18405. *
  18406. * @description
  18407. * Directive that instantiates
  18408. * {@link form.FormController FormController}.
  18409. *
  18410. * If the `name` attribute is specified, the form controller is published onto the current scope under
  18411. * this name.
  18412. *
  18413. * # Alias: {@link ng.directive:ngForm `ngForm`}
  18414. *
  18415. * In Angular, forms can be nested. This means that the outer form is valid when all of the child
  18416. * forms are valid as well. However, browsers do not allow nesting of `<form>` elements, so
  18417. * Angular provides the {@link ng.directive:ngForm `ngForm`} directive which behaves identically to
  18418. * `<form>` but can be nested. This allows you to have nested forms, which is very useful when
  18419. * using Angular validation directives in forms that are dynamically generated using the
  18420. * {@link ng.directive:ngRepeat `ngRepeat`} directive. Since you cannot dynamically generate the `name`
  18421. * attribute of input elements using interpolation, you have to wrap each set of repeated inputs in an
  18422. * `ngForm` directive and nest these in an outer `form` element.
  18423. *
  18424. *
  18425. * # CSS classes
  18426. * - `ng-valid` is set if the form is valid.
  18427. * - `ng-invalid` is set if the form is invalid.
  18428. * - `ng-pending` is set if the form is pending.
  18429. * - `ng-pristine` is set if the form is pristine.
  18430. * - `ng-dirty` is set if the form is dirty.
  18431. * - `ng-submitted` is set if the form was submitted.
  18432. *
  18433. * Keep in mind that ngAnimate can detect each of these classes when added and removed.
  18434. *
  18435. *
  18436. * # Submitting a form and preventing the default action
  18437. *
  18438. * Since the role of forms in client-side Angular applications is different than in classical
  18439. * roundtrip apps, it is desirable for the browser not to translate the form submission into a full
  18440. * page reload that sends the data to the server. Instead some javascript logic should be triggered
  18441. * to handle the form submission in an application-specific way.
  18442. *
  18443. * For this reason, Angular prevents the default action (form submission to the server) unless the
  18444. * `<form>` element has an `action` attribute specified.
  18445. *
  18446. * You can use one of the following two ways to specify what javascript method should be called when
  18447. * a form is submitted:
  18448. *
  18449. * - {@link ng.directive:ngSubmit ngSubmit} directive on the form element
  18450. * - {@link ng.directive:ngClick ngClick} directive on the first
  18451. * button or input field of type submit (input[type=submit])
  18452. *
  18453. * To prevent double execution of the handler, use only one of the {@link ng.directive:ngSubmit ngSubmit}
  18454. * or {@link ng.directive:ngClick ngClick} directives.
  18455. * This is because of the following form submission rules in the HTML specification:
  18456. *
  18457. * - If a form has only one input field then hitting enter in this field triggers form submit
  18458. * (`ngSubmit`)
  18459. * - if a form has 2+ input fields and no buttons or input[type=submit] then hitting enter
  18460. * doesn't trigger submit
  18461. * - if a form has one or more input fields and one or more buttons or input[type=submit] then
  18462. * hitting enter in any of the input fields will trigger the click handler on the *first* button or
  18463. * input[type=submit] (`ngClick`) *and* a submit handler on the enclosing form (`ngSubmit`)
  18464. *
  18465. * Any pending `ngModelOptions` changes will take place immediately when an enclosing form is
  18466. * submitted. Note that `ngClick` events will occur before the model is updated. Use `ngSubmit`
  18467. * to have access to the updated model.
  18468. *
  18469. * ## Animation Hooks
  18470. *
  18471. * Animations in ngForm are triggered when any of the associated CSS classes are added and removed.
  18472. * These classes are: `.ng-pristine`, `.ng-dirty`, `.ng-invalid` and `.ng-valid` as well as any
  18473. * other validations that are performed within the form. Animations in ngForm are similar to how
  18474. * they work in ngClass and animations can be hooked into using CSS transitions, keyframes as well
  18475. * as JS animations.
  18476. *
  18477. * The following example shows a simple way to utilize CSS transitions to style a form element
  18478. * that has been rendered as invalid after it has been validated:
  18479. *
  18480. * <pre>
  18481. * //be sure to include ngAnimate as a module to hook into more
  18482. * //advanced animations
  18483. * .my-form {
  18484. * transition:0.5s linear all;
  18485. * background: white;
  18486. * }
  18487. * .my-form.ng-invalid {
  18488. * background: red;
  18489. * color:white;
  18490. * }
  18491. * </pre>
  18492. *
  18493. * @example
  18494. <example deps="angular-animate.js" animations="true" fixBase="true" module="formExample">
  18495. <file name="index.html">
  18496. <script>
  18497. angular.module('formExample', [])
  18498. .controller('FormController', ['$scope', function($scope) {
  18499. $scope.userType = 'guest';
  18500. }]);
  18501. </script>
  18502. <style>
  18503. .my-form {
  18504. transition:all linear 0.5s;
  18505. background: transparent;
  18506. }
  18507. .my-form.ng-invalid {
  18508. background: red;
  18509. }
  18510. </style>
  18511. <form name="myForm" ng-controller="FormController" class="my-form">
  18512. userType: <input name="input" ng-model="userType" required>
  18513. <span class="error" ng-show="myForm.input.$error.required">Required!</span><br>
  18514. <code>userType = {{userType}}</code><br>
  18515. <code>myForm.input.$valid = {{myForm.input.$valid}}</code><br>
  18516. <code>myForm.input.$error = {{myForm.input.$error}}</code><br>
  18517. <code>myForm.$valid = {{myForm.$valid}}</code><br>
  18518. <code>myForm.$error.required = {{!!myForm.$error.required}}</code><br>
  18519. </form>
  18520. </file>
  18521. <file name="protractor.js" type="protractor">
  18522. it('should initialize to model', function() {
  18523. var userType = element(by.binding('userType'));
  18524. var valid = element(by.binding('myForm.input.$valid'));
  18525. expect(userType.getText()).toContain('guest');
  18526. expect(valid.getText()).toContain('true');
  18527. });
  18528. it('should be invalid if empty', function() {
  18529. var userType = element(by.binding('userType'));
  18530. var valid = element(by.binding('myForm.input.$valid'));
  18531. var userInput = element(by.model('userType'));
  18532. userInput.clear();
  18533. userInput.sendKeys('');
  18534. expect(userType.getText()).toEqual('userType =');
  18535. expect(valid.getText()).toContain('false');
  18536. });
  18537. </file>
  18538. </example>
  18539. *
  18540. * @param {string=} name Name of the form. If specified, the form controller will be published into
  18541. * related scope, under this name.
  18542. */
  18543. var formDirectiveFactory = function(isNgForm) {
  18544. return ['$timeout', '$parse', function($timeout, $parse) {
  18545. var formDirective = {
  18546. name: 'form',
  18547. restrict: isNgForm ? 'EAC' : 'E',
  18548. require: ['form', '^^?form'], //first is the form's own ctrl, second is an optional parent form
  18549. controller: FormController,
  18550. compile: function ngFormCompile(formElement, attr) {
  18551. // Setup initial state of the control
  18552. formElement.addClass(PRISTINE_CLASS).addClass(VALID_CLASS);
  18553. var nameAttr = attr.name ? 'name' : (isNgForm && attr.ngForm ? 'ngForm' : false);
  18554. return {
  18555. pre: function ngFormPreLink(scope, formElement, attr, ctrls) {
  18556. var controller = ctrls[0];
  18557. // if `action` attr is not present on the form, prevent the default action (submission)
  18558. if (!('action' in attr)) {
  18559. // we can't use jq events because if a form is destroyed during submission the default
  18560. // action is not prevented. see #1238
  18561. //
  18562. // IE 9 is not affected because it doesn't fire a submit event and try to do a full
  18563. // page reload if the form was destroyed by submission of the form via a click handler
  18564. // on a button in the form. Looks like an IE9 specific bug.
  18565. var handleFormSubmission = function(event) {
  18566. scope.$apply(function() {
  18567. controller.$commitViewValue();
  18568. controller.$setSubmitted();
  18569. });
  18570. event.preventDefault();
  18571. };
  18572. addEventListenerFn(formElement[0], 'submit', handleFormSubmission);
  18573. // unregister the preventDefault listener so that we don't not leak memory but in a
  18574. // way that will achieve the prevention of the default action.
  18575. formElement.on('$destroy', function() {
  18576. $timeout(function() {
  18577. removeEventListenerFn(formElement[0], 'submit', handleFormSubmission);
  18578. }, 0, false);
  18579. });
  18580. }
  18581. var parentFormCtrl = ctrls[1] || controller.$$parentForm;
  18582. parentFormCtrl.$addControl(controller);
  18583. var setter = nameAttr ? getSetter(controller.$name) : noop;
  18584. if (nameAttr) {
  18585. setter(scope, controller);
  18586. attr.$observe(nameAttr, function(newValue) {
  18587. if (controller.$name === newValue) return;
  18588. setter(scope, undefined);
  18589. controller.$$parentForm.$$renameControl(controller, newValue);
  18590. setter = getSetter(controller.$name);
  18591. setter(scope, controller);
  18592. });
  18593. }
  18594. formElement.on('$destroy', function() {
  18595. controller.$$parentForm.$removeControl(controller);
  18596. setter(scope, undefined);
  18597. extend(controller, nullFormCtrl); //stop propagating child destruction handlers upwards
  18598. });
  18599. }
  18600. };
  18601. }
  18602. };
  18603. return formDirective;
  18604. function getSetter(expression) {
  18605. if (expression === '') {
  18606. //create an assignable expression, so forms with an empty name can be renamed later
  18607. return $parse('this[""]').assign;
  18608. }
  18609. return $parse(expression).assign || noop;
  18610. }
  18611. }];
  18612. };
  18613. var formDirective = formDirectiveFactory();
  18614. var ngFormDirective = formDirectiveFactory(true);
  18615. /* global VALID_CLASS: false,
  18616. INVALID_CLASS: false,
  18617. PRISTINE_CLASS: false,
  18618. DIRTY_CLASS: false,
  18619. UNTOUCHED_CLASS: false,
  18620. TOUCHED_CLASS: false,
  18621. ngModelMinErr: false,
  18622. */
  18623. // Regex code is obtained from SO: https://stackoverflow.com/questions/3143070/javascript-regex-iso-datetime#answer-3143231
  18624. var ISO_DATE_REGEXP = /\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d:[0-5]\d\.\d+([+-][0-2]\d:[0-5]\d|Z)/;
  18625. var URL_REGEXP = /^(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?$/;
  18626. var EMAIL_REGEXP = /^[a-z0-9!#$%&'*+\/=?^_`{|}~.-]+@[a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)*$/i;
  18627. var NUMBER_REGEXP = /^\s*(\-|\+)?(\d+|(\d*(\.\d*)))([eE][+-]?\d+)?\s*$/;
  18628. var DATE_REGEXP = /^(\d{4})-(\d{2})-(\d{2})$/;
  18629. var DATETIMELOCAL_REGEXP = /^(\d{4})-(\d\d)-(\d\d)T(\d\d):(\d\d)(?::(\d\d)(\.\d{1,3})?)?$/;
  18630. var WEEK_REGEXP = /^(\d{4})-W(\d\d)$/;
  18631. var MONTH_REGEXP = /^(\d{4})-(\d\d)$/;
  18632. var TIME_REGEXP = /^(\d\d):(\d\d)(?::(\d\d)(\.\d{1,3})?)?$/;
  18633. var inputType = {
  18634. /**
  18635. * @ngdoc input
  18636. * @name input[text]
  18637. *
  18638. * @description
  18639. * Standard HTML text input with angular data binding, inherited by most of the `input` elements.
  18640. *
  18641. *
  18642. * @param {string} ngModel Assignable angular expression to data-bind to.
  18643. * @param {string=} name Property name of the form under which the control is published.
  18644. * @param {string=} required Adds `required` validation error key if the value is not entered.
  18645. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  18646. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  18647. * `required` when you want to data-bind to the `required` attribute.
  18648. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
  18649. * minlength.
  18650. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
  18651. * maxlength. Setting the attribute to a negative or non-numeric value, allows view values of
  18652. * any length.
  18653. * @param {string=} pattern Similar to `ngPattern` except that the attribute value is the actual string
  18654. * that contains the regular expression body that will be converted to a regular expression
  18655. * as in the ngPattern directive.
  18656. * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel value does not match
  18657. * a RegExp found by evaluating the Angular expression given in the attribute value.
  18658. * If the expression evaluates to a RegExp object, then this is used directly.
  18659. * If the expression evaluates to a string, then it will be converted to a RegExp
  18660. * after wrapping it in `^` and `$` characters. For instance, `"abc"` will be converted to
  18661. * `new RegExp('^abc$')`.<br />
  18662. * **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to
  18663. * start at the index of the last search's match, thus not taking the whole input value into
  18664. * account.
  18665. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  18666. * interaction with the input element.
  18667. * @param {boolean=} [ngTrim=true] If set to false Angular will not automatically trim the input.
  18668. * This parameter is ignored for input[type=password] controls, which will never trim the
  18669. * input.
  18670. *
  18671. * @example
  18672. <example name="text-input-directive" module="textInputExample">
  18673. <file name="index.html">
  18674. <script>
  18675. angular.module('textInputExample', [])
  18676. .controller('ExampleController', ['$scope', function($scope) {
  18677. $scope.example = {
  18678. text: 'guest',
  18679. word: /^\s*\w*\s*$/
  18680. };
  18681. }]);
  18682. </script>
  18683. <form name="myForm" ng-controller="ExampleController">
  18684. <label>Single word:
  18685. <input type="text" name="input" ng-model="example.text"
  18686. ng-pattern="example.word" required ng-trim="false">
  18687. </label>
  18688. <div role="alert">
  18689. <span class="error" ng-show="myForm.input.$error.required">
  18690. Required!</span>
  18691. <span class="error" ng-show="myForm.input.$error.pattern">
  18692. Single word only!</span>
  18693. </div>
  18694. <tt>text = {{example.text}}</tt><br/>
  18695. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  18696. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  18697. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  18698. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  18699. </form>
  18700. </file>
  18701. <file name="protractor.js" type="protractor">
  18702. var text = element(by.binding('example.text'));
  18703. var valid = element(by.binding('myForm.input.$valid'));
  18704. var input = element(by.model('example.text'));
  18705. it('should initialize to model', function() {
  18706. expect(text.getText()).toContain('guest');
  18707. expect(valid.getText()).toContain('true');
  18708. });
  18709. it('should be invalid if empty', function() {
  18710. input.clear();
  18711. input.sendKeys('');
  18712. expect(text.getText()).toEqual('text =');
  18713. expect(valid.getText()).toContain('false');
  18714. });
  18715. it('should be invalid if multi word', function() {
  18716. input.clear();
  18717. input.sendKeys('hello world');
  18718. expect(valid.getText()).toContain('false');
  18719. });
  18720. </file>
  18721. </example>
  18722. */
  18723. 'text': textInputType,
  18724. /**
  18725. * @ngdoc input
  18726. * @name input[date]
  18727. *
  18728. * @description
  18729. * Input with date validation and transformation. In browsers that do not yet support
  18730. * the HTML5 date input, a text element will be used. In that case, text must be entered in a valid ISO-8601
  18731. * date format (yyyy-MM-dd), for example: `2009-01-06`. Since many
  18732. * modern browsers do not yet support this input type, it is important to provide cues to users on the
  18733. * expected input format via a placeholder or label.
  18734. *
  18735. * The model must always be a Date object, otherwise Angular will throw an error.
  18736. * Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string.
  18737. *
  18738. * The timezone to be used to read/write the `Date` instance in the model can be defined using
  18739. * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser.
  18740. *
  18741. * @param {string} ngModel Assignable angular expression to data-bind to.
  18742. * @param {string=} name Property name of the form under which the control is published.
  18743. * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`. This must be a
  18744. * valid ISO date string (yyyy-MM-dd). You can also use interpolation inside this attribute
  18745. * (e.g. `min="{{minDate | date:'yyyy-MM-dd'}}"`). Note that `min` will also add native HTML5
  18746. * constraint validation.
  18747. * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`. This must be
  18748. * a valid ISO date string (yyyy-MM-dd). You can also use interpolation inside this attribute
  18749. * (e.g. `max="{{maxDate | date:'yyyy-MM-dd'}}"`). Note that `max` will also add native HTML5
  18750. * constraint validation.
  18751. * @param {(date|string)=} ngMin Sets the `min` validation constraint to the Date / ISO date string
  18752. * the `ngMin` expression evaluates to. Note that it does not set the `min` attribute.
  18753. * @param {(date|string)=} ngMax Sets the `max` validation constraint to the Date / ISO date string
  18754. * the `ngMax` expression evaluates to. Note that it does not set the `max` attribute.
  18755. * @param {string=} required Sets `required` validation error key if the value is not entered.
  18756. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  18757. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  18758. * `required` when you want to data-bind to the `required` attribute.
  18759. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  18760. * interaction with the input element.
  18761. *
  18762. * @example
  18763. <example name="date-input-directive" module="dateInputExample">
  18764. <file name="index.html">
  18765. <script>
  18766. angular.module('dateInputExample', [])
  18767. .controller('DateController', ['$scope', function($scope) {
  18768. $scope.example = {
  18769. value: new Date(2013, 9, 22)
  18770. };
  18771. }]);
  18772. </script>
  18773. <form name="myForm" ng-controller="DateController as dateCtrl">
  18774. <label for="exampleInput">Pick a date in 2013:</label>
  18775. <input type="date" id="exampleInput" name="input" ng-model="example.value"
  18776. placeholder="yyyy-MM-dd" min="2013-01-01" max="2013-12-31" required />
  18777. <div role="alert">
  18778. <span class="error" ng-show="myForm.input.$error.required">
  18779. Required!</span>
  18780. <span class="error" ng-show="myForm.input.$error.date">
  18781. Not a valid date!</span>
  18782. </div>
  18783. <tt>value = {{example.value | date: "yyyy-MM-dd"}}</tt><br/>
  18784. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  18785. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  18786. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  18787. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  18788. </form>
  18789. </file>
  18790. <file name="protractor.js" type="protractor">
  18791. var value = element(by.binding('example.value | date: "yyyy-MM-dd"'));
  18792. var valid = element(by.binding('myForm.input.$valid'));
  18793. var input = element(by.model('example.value'));
  18794. // currently protractor/webdriver does not support
  18795. // sending keys to all known HTML5 input controls
  18796. // for various browsers (see https://github.com/angular/protractor/issues/562).
  18797. function setInput(val) {
  18798. // set the value of the element and force validation.
  18799. var scr = "var ipt = document.getElementById('exampleInput'); " +
  18800. "ipt.value = '" + val + "';" +
  18801. "angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('" + val + "'); });";
  18802. browser.executeScript(scr);
  18803. }
  18804. it('should initialize to model', function() {
  18805. expect(value.getText()).toContain('2013-10-22');
  18806. expect(valid.getText()).toContain('myForm.input.$valid = true');
  18807. });
  18808. it('should be invalid if empty', function() {
  18809. setInput('');
  18810. expect(value.getText()).toEqual('value =');
  18811. expect(valid.getText()).toContain('myForm.input.$valid = false');
  18812. });
  18813. it('should be invalid if over max', function() {
  18814. setInput('2015-01-01');
  18815. expect(value.getText()).toContain('');
  18816. expect(valid.getText()).toContain('myForm.input.$valid = false');
  18817. });
  18818. </file>
  18819. </example>
  18820. */
  18821. 'date': createDateInputType('date', DATE_REGEXP,
  18822. createDateParser(DATE_REGEXP, ['yyyy', 'MM', 'dd']),
  18823. 'yyyy-MM-dd'),
  18824. /**
  18825. * @ngdoc input
  18826. * @name input[datetime-local]
  18827. *
  18828. * @description
  18829. * Input with datetime validation and transformation. In browsers that do not yet support
  18830. * the HTML5 date input, a text element will be used. In that case, the text must be entered in a valid ISO-8601
  18831. * local datetime format (yyyy-MM-ddTHH:mm:ss), for example: `2010-12-28T14:57:00`.
  18832. *
  18833. * The model must always be a Date object, otherwise Angular will throw an error.
  18834. * Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string.
  18835. *
  18836. * The timezone to be used to read/write the `Date` instance in the model can be defined using
  18837. * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser.
  18838. *
  18839. * @param {string} ngModel Assignable angular expression to data-bind to.
  18840. * @param {string=} name Property name of the form under which the control is published.
  18841. * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`.
  18842. * This must be a valid ISO datetime format (yyyy-MM-ddTHH:mm:ss). You can also use interpolation
  18843. * inside this attribute (e.g. `min="{{minDatetimeLocal | date:'yyyy-MM-ddTHH:mm:ss'}}"`).
  18844. * Note that `min` will also add native HTML5 constraint validation.
  18845. * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`.
  18846. * This must be a valid ISO datetime format (yyyy-MM-ddTHH:mm:ss). You can also use interpolation
  18847. * inside this attribute (e.g. `max="{{maxDatetimeLocal | date:'yyyy-MM-ddTHH:mm:ss'}}"`).
  18848. * Note that `max` will also add native HTML5 constraint validation.
  18849. * @param {(date|string)=} ngMin Sets the `min` validation error key to the Date / ISO datetime string
  18850. * the `ngMin` expression evaluates to. Note that it does not set the `min` attribute.
  18851. * @param {(date|string)=} ngMax Sets the `max` validation error key to the Date / ISO datetime string
  18852. * the `ngMax` expression evaluates to. Note that it does not set the `max` attribute.
  18853. * @param {string=} required Sets `required` validation error key if the value is not entered.
  18854. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  18855. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  18856. * `required` when you want to data-bind to the `required` attribute.
  18857. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  18858. * interaction with the input element.
  18859. *
  18860. * @example
  18861. <example name="datetimelocal-input-directive" module="dateExample">
  18862. <file name="index.html">
  18863. <script>
  18864. angular.module('dateExample', [])
  18865. .controller('DateController', ['$scope', function($scope) {
  18866. $scope.example = {
  18867. value: new Date(2010, 11, 28, 14, 57)
  18868. };
  18869. }]);
  18870. </script>
  18871. <form name="myForm" ng-controller="DateController as dateCtrl">
  18872. <label for="exampleInput">Pick a date between in 2013:</label>
  18873. <input type="datetime-local" id="exampleInput" name="input" ng-model="example.value"
  18874. placeholder="yyyy-MM-ddTHH:mm:ss" min="2001-01-01T00:00:00" max="2013-12-31T00:00:00" required />
  18875. <div role="alert">
  18876. <span class="error" ng-show="myForm.input.$error.required">
  18877. Required!</span>
  18878. <span class="error" ng-show="myForm.input.$error.datetimelocal">
  18879. Not a valid date!</span>
  18880. </div>
  18881. <tt>value = {{example.value | date: "yyyy-MM-ddTHH:mm:ss"}}</tt><br/>
  18882. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  18883. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  18884. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  18885. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  18886. </form>
  18887. </file>
  18888. <file name="protractor.js" type="protractor">
  18889. var value = element(by.binding('example.value | date: "yyyy-MM-ddTHH:mm:ss"'));
  18890. var valid = element(by.binding('myForm.input.$valid'));
  18891. var input = element(by.model('example.value'));
  18892. // currently protractor/webdriver does not support
  18893. // sending keys to all known HTML5 input controls
  18894. // for various browsers (https://github.com/angular/protractor/issues/562).
  18895. function setInput(val) {
  18896. // set the value of the element and force validation.
  18897. var scr = "var ipt = document.getElementById('exampleInput'); " +
  18898. "ipt.value = '" + val + "';" +
  18899. "angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('" + val + "'); });";
  18900. browser.executeScript(scr);
  18901. }
  18902. it('should initialize to model', function() {
  18903. expect(value.getText()).toContain('2010-12-28T14:57:00');
  18904. expect(valid.getText()).toContain('myForm.input.$valid = true');
  18905. });
  18906. it('should be invalid if empty', function() {
  18907. setInput('');
  18908. expect(value.getText()).toEqual('value =');
  18909. expect(valid.getText()).toContain('myForm.input.$valid = false');
  18910. });
  18911. it('should be invalid if over max', function() {
  18912. setInput('2015-01-01T23:59:00');
  18913. expect(value.getText()).toContain('');
  18914. expect(valid.getText()).toContain('myForm.input.$valid = false');
  18915. });
  18916. </file>
  18917. </example>
  18918. */
  18919. 'datetime-local': createDateInputType('datetimelocal', DATETIMELOCAL_REGEXP,
  18920. createDateParser(DATETIMELOCAL_REGEXP, ['yyyy', 'MM', 'dd', 'HH', 'mm', 'ss', 'sss']),
  18921. 'yyyy-MM-ddTHH:mm:ss.sss'),
  18922. /**
  18923. * @ngdoc input
  18924. * @name input[time]
  18925. *
  18926. * @description
  18927. * Input with time validation and transformation. In browsers that do not yet support
  18928. * the HTML5 date input, a text element will be used. In that case, the text must be entered in a valid ISO-8601
  18929. * local time format (HH:mm:ss), for example: `14:57:00`. Model must be a Date object. This binding will always output a
  18930. * Date object to the model of January 1, 1970, or local date `new Date(1970, 0, 1, HH, mm, ss)`.
  18931. *
  18932. * The model must always be a Date object, otherwise Angular will throw an error.
  18933. * Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string.
  18934. *
  18935. * The timezone to be used to read/write the `Date` instance in the model can be defined using
  18936. * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser.
  18937. *
  18938. * @param {string} ngModel Assignable angular expression to data-bind to.
  18939. * @param {string=} name Property name of the form under which the control is published.
  18940. * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`.
  18941. * This must be a valid ISO time format (HH:mm:ss). You can also use interpolation inside this
  18942. * attribute (e.g. `min="{{minTime | date:'HH:mm:ss'}}"`). Note that `min` will also add
  18943. * native HTML5 constraint validation.
  18944. * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`.
  18945. * This must be a valid ISO time format (HH:mm:ss). You can also use interpolation inside this
  18946. * attribute (e.g. `max="{{maxTime | date:'HH:mm:ss'}}"`). Note that `max` will also add
  18947. * native HTML5 constraint validation.
  18948. * @param {(date|string)=} ngMin Sets the `min` validation constraint to the Date / ISO time string the
  18949. * `ngMin` expression evaluates to. Note that it does not set the `min` attribute.
  18950. * @param {(date|string)=} ngMax Sets the `max` validation constraint to the Date / ISO time string the
  18951. * `ngMax` expression evaluates to. Note that it does not set the `max` attribute.
  18952. * @param {string=} required Sets `required` validation error key if the value is not entered.
  18953. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  18954. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  18955. * `required` when you want to data-bind to the `required` attribute.
  18956. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  18957. * interaction with the input element.
  18958. *
  18959. * @example
  18960. <example name="time-input-directive" module="timeExample">
  18961. <file name="index.html">
  18962. <script>
  18963. angular.module('timeExample', [])
  18964. .controller('DateController', ['$scope', function($scope) {
  18965. $scope.example = {
  18966. value: new Date(1970, 0, 1, 14, 57, 0)
  18967. };
  18968. }]);
  18969. </script>
  18970. <form name="myForm" ng-controller="DateController as dateCtrl">
  18971. <label for="exampleInput">Pick a between 8am and 5pm:</label>
  18972. <input type="time" id="exampleInput" name="input" ng-model="example.value"
  18973. placeholder="HH:mm:ss" min="08:00:00" max="17:00:00" required />
  18974. <div role="alert">
  18975. <span class="error" ng-show="myForm.input.$error.required">
  18976. Required!</span>
  18977. <span class="error" ng-show="myForm.input.$error.time">
  18978. Not a valid date!</span>
  18979. </div>
  18980. <tt>value = {{example.value | date: "HH:mm:ss"}}</tt><br/>
  18981. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  18982. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  18983. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  18984. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  18985. </form>
  18986. </file>
  18987. <file name="protractor.js" type="protractor">
  18988. var value = element(by.binding('example.value | date: "HH:mm:ss"'));
  18989. var valid = element(by.binding('myForm.input.$valid'));
  18990. var input = element(by.model('example.value'));
  18991. // currently protractor/webdriver does not support
  18992. // sending keys to all known HTML5 input controls
  18993. // for various browsers (https://github.com/angular/protractor/issues/562).
  18994. function setInput(val) {
  18995. // set the value of the element and force validation.
  18996. var scr = "var ipt = document.getElementById('exampleInput'); " +
  18997. "ipt.value = '" + val + "';" +
  18998. "angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('" + val + "'); });";
  18999. browser.executeScript(scr);
  19000. }
  19001. it('should initialize to model', function() {
  19002. expect(value.getText()).toContain('14:57:00');
  19003. expect(valid.getText()).toContain('myForm.input.$valid = true');
  19004. });
  19005. it('should be invalid if empty', function() {
  19006. setInput('');
  19007. expect(value.getText()).toEqual('value =');
  19008. expect(valid.getText()).toContain('myForm.input.$valid = false');
  19009. });
  19010. it('should be invalid if over max', function() {
  19011. setInput('23:59:00');
  19012. expect(value.getText()).toContain('');
  19013. expect(valid.getText()).toContain('myForm.input.$valid = false');
  19014. });
  19015. </file>
  19016. </example>
  19017. */
  19018. 'time': createDateInputType('time', TIME_REGEXP,
  19019. createDateParser(TIME_REGEXP, ['HH', 'mm', 'ss', 'sss']),
  19020. 'HH:mm:ss.sss'),
  19021. /**
  19022. * @ngdoc input
  19023. * @name input[week]
  19024. *
  19025. * @description
  19026. * Input with week-of-the-year validation and transformation to Date. In browsers that do not yet support
  19027. * the HTML5 week input, a text element will be used. In that case, the text must be entered in a valid ISO-8601
  19028. * week format (yyyy-W##), for example: `2013-W02`.
  19029. *
  19030. * The model must always be a Date object, otherwise Angular will throw an error.
  19031. * Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string.
  19032. *
  19033. * The timezone to be used to read/write the `Date` instance in the model can be defined using
  19034. * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser.
  19035. *
  19036. * @param {string} ngModel Assignable angular expression to data-bind to.
  19037. * @param {string=} name Property name of the form under which the control is published.
  19038. * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`.
  19039. * This must be a valid ISO week format (yyyy-W##). You can also use interpolation inside this
  19040. * attribute (e.g. `min="{{minWeek | date:'yyyy-Www'}}"`). Note that `min` will also add
  19041. * native HTML5 constraint validation.
  19042. * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`.
  19043. * This must be a valid ISO week format (yyyy-W##). You can also use interpolation inside this
  19044. * attribute (e.g. `max="{{maxWeek | date:'yyyy-Www'}}"`). Note that `max` will also add
  19045. * native HTML5 constraint validation.
  19046. * @param {(date|string)=} ngMin Sets the `min` validation constraint to the Date / ISO week string
  19047. * the `ngMin` expression evaluates to. Note that it does not set the `min` attribute.
  19048. * @param {(date|string)=} ngMax Sets the `max` validation constraint to the Date / ISO week string
  19049. * the `ngMax` expression evaluates to. Note that it does not set the `max` attribute.
  19050. * @param {string=} required Sets `required` validation error key if the value is not entered.
  19051. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  19052. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  19053. * `required` when you want to data-bind to the `required` attribute.
  19054. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  19055. * interaction with the input element.
  19056. *
  19057. * @example
  19058. <example name="week-input-directive" module="weekExample">
  19059. <file name="index.html">
  19060. <script>
  19061. angular.module('weekExample', [])
  19062. .controller('DateController', ['$scope', function($scope) {
  19063. $scope.example = {
  19064. value: new Date(2013, 0, 3)
  19065. };
  19066. }]);
  19067. </script>
  19068. <form name="myForm" ng-controller="DateController as dateCtrl">
  19069. <label>Pick a date between in 2013:
  19070. <input id="exampleInput" type="week" name="input" ng-model="example.value"
  19071. placeholder="YYYY-W##" min="2012-W32"
  19072. max="2013-W52" required />
  19073. </label>
  19074. <div role="alert">
  19075. <span class="error" ng-show="myForm.input.$error.required">
  19076. Required!</span>
  19077. <span class="error" ng-show="myForm.input.$error.week">
  19078. Not a valid date!</span>
  19079. </div>
  19080. <tt>value = {{example.value | date: "yyyy-Www"}}</tt><br/>
  19081. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  19082. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  19083. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  19084. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  19085. </form>
  19086. </file>
  19087. <file name="protractor.js" type="protractor">
  19088. var value = element(by.binding('example.value | date: "yyyy-Www"'));
  19089. var valid = element(by.binding('myForm.input.$valid'));
  19090. var input = element(by.model('example.value'));
  19091. // currently protractor/webdriver does not support
  19092. // sending keys to all known HTML5 input controls
  19093. // for various browsers (https://github.com/angular/protractor/issues/562).
  19094. function setInput(val) {
  19095. // set the value of the element and force validation.
  19096. var scr = "var ipt = document.getElementById('exampleInput'); " +
  19097. "ipt.value = '" + val + "';" +
  19098. "angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('" + val + "'); });";
  19099. browser.executeScript(scr);
  19100. }
  19101. it('should initialize to model', function() {
  19102. expect(value.getText()).toContain('2013-W01');
  19103. expect(valid.getText()).toContain('myForm.input.$valid = true');
  19104. });
  19105. it('should be invalid if empty', function() {
  19106. setInput('');
  19107. expect(value.getText()).toEqual('value =');
  19108. expect(valid.getText()).toContain('myForm.input.$valid = false');
  19109. });
  19110. it('should be invalid if over max', function() {
  19111. setInput('2015-W01');
  19112. expect(value.getText()).toContain('');
  19113. expect(valid.getText()).toContain('myForm.input.$valid = false');
  19114. });
  19115. </file>
  19116. </example>
  19117. */
  19118. 'week': createDateInputType('week', WEEK_REGEXP, weekParser, 'yyyy-Www'),
  19119. /**
  19120. * @ngdoc input
  19121. * @name input[month]
  19122. *
  19123. * @description
  19124. * Input with month validation and transformation. In browsers that do not yet support
  19125. * the HTML5 month input, a text element will be used. In that case, the text must be entered in a valid ISO-8601
  19126. * month format (yyyy-MM), for example: `2009-01`.
  19127. *
  19128. * The model must always be a Date object, otherwise Angular will throw an error.
  19129. * Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string.
  19130. * If the model is not set to the first of the month, the next view to model update will set it
  19131. * to the first of the month.
  19132. *
  19133. * The timezone to be used to read/write the `Date` instance in the model can be defined using
  19134. * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser.
  19135. *
  19136. * @param {string} ngModel Assignable angular expression to data-bind to.
  19137. * @param {string=} name Property name of the form under which the control is published.
  19138. * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`.
  19139. * This must be a valid ISO month format (yyyy-MM). You can also use interpolation inside this
  19140. * attribute (e.g. `min="{{minMonth | date:'yyyy-MM'}}"`). Note that `min` will also add
  19141. * native HTML5 constraint validation.
  19142. * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`.
  19143. * This must be a valid ISO month format (yyyy-MM). You can also use interpolation inside this
  19144. * attribute (e.g. `max="{{maxMonth | date:'yyyy-MM'}}"`). Note that `max` will also add
  19145. * native HTML5 constraint validation.
  19146. * @param {(date|string)=} ngMin Sets the `min` validation constraint to the Date / ISO week string
  19147. * the `ngMin` expression evaluates to. Note that it does not set the `min` attribute.
  19148. * @param {(date|string)=} ngMax Sets the `max` validation constraint to the Date / ISO week string
  19149. * the `ngMax` expression evaluates to. Note that it does not set the `max` attribute.
  19150. * @param {string=} required Sets `required` validation error key if the value is not entered.
  19151. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  19152. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  19153. * `required` when you want to data-bind to the `required` attribute.
  19154. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  19155. * interaction with the input element.
  19156. *
  19157. * @example
  19158. <example name="month-input-directive" module="monthExample">
  19159. <file name="index.html">
  19160. <script>
  19161. angular.module('monthExample', [])
  19162. .controller('DateController', ['$scope', function($scope) {
  19163. $scope.example = {
  19164. value: new Date(2013, 9, 1)
  19165. };
  19166. }]);
  19167. </script>
  19168. <form name="myForm" ng-controller="DateController as dateCtrl">
  19169. <label for="exampleInput">Pick a month in 2013:</label>
  19170. <input id="exampleInput" type="month" name="input" ng-model="example.value"
  19171. placeholder="yyyy-MM" min="2013-01" max="2013-12" required />
  19172. <div role="alert">
  19173. <span class="error" ng-show="myForm.input.$error.required">
  19174. Required!</span>
  19175. <span class="error" ng-show="myForm.input.$error.month">
  19176. Not a valid month!</span>
  19177. </div>
  19178. <tt>value = {{example.value | date: "yyyy-MM"}}</tt><br/>
  19179. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  19180. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  19181. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  19182. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  19183. </form>
  19184. </file>
  19185. <file name="protractor.js" type="protractor">
  19186. var value = element(by.binding('example.value | date: "yyyy-MM"'));
  19187. var valid = element(by.binding('myForm.input.$valid'));
  19188. var input = element(by.model('example.value'));
  19189. // currently protractor/webdriver does not support
  19190. // sending keys to all known HTML5 input controls
  19191. // for various browsers (https://github.com/angular/protractor/issues/562).
  19192. function setInput(val) {
  19193. // set the value of the element and force validation.
  19194. var scr = "var ipt = document.getElementById('exampleInput'); " +
  19195. "ipt.value = '" + val + "';" +
  19196. "angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('" + val + "'); });";
  19197. browser.executeScript(scr);
  19198. }
  19199. it('should initialize to model', function() {
  19200. expect(value.getText()).toContain('2013-10');
  19201. expect(valid.getText()).toContain('myForm.input.$valid = true');
  19202. });
  19203. it('should be invalid if empty', function() {
  19204. setInput('');
  19205. expect(value.getText()).toEqual('value =');
  19206. expect(valid.getText()).toContain('myForm.input.$valid = false');
  19207. });
  19208. it('should be invalid if over max', function() {
  19209. setInput('2015-01');
  19210. expect(value.getText()).toContain('');
  19211. expect(valid.getText()).toContain('myForm.input.$valid = false');
  19212. });
  19213. </file>
  19214. </example>
  19215. */
  19216. 'month': createDateInputType('month', MONTH_REGEXP,
  19217. createDateParser(MONTH_REGEXP, ['yyyy', 'MM']),
  19218. 'yyyy-MM'),
  19219. /**
  19220. * @ngdoc input
  19221. * @name input[number]
  19222. *
  19223. * @description
  19224. * Text input with number validation and transformation. Sets the `number` validation
  19225. * error if not a valid number.
  19226. *
  19227. * <div class="alert alert-warning">
  19228. * The model must always be of type `number` otherwise Angular will throw an error.
  19229. * Be aware that a string containing a number is not enough. See the {@link ngModel:numfmt}
  19230. * error docs for more information and an example of how to convert your model if necessary.
  19231. * </div>
  19232. *
  19233. * ## Issues with HTML5 constraint validation
  19234. *
  19235. * In browsers that follow the
  19236. * [HTML5 specification](https://html.spec.whatwg.org/multipage/forms.html#number-state-%28type=number%29),
  19237. * `input[number]` does not work as expected with {@link ngModelOptions `ngModelOptions.allowInvalid`}.
  19238. * If a non-number is entered in the input, the browser will report the value as an empty string,
  19239. * which means the view / model values in `ngModel` and subsequently the scope value
  19240. * will also be an empty string.
  19241. *
  19242. *
  19243. * @param {string} ngModel Assignable angular expression to data-bind to.
  19244. * @param {string=} name Property name of the form under which the control is published.
  19245. * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`.
  19246. * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`.
  19247. * @param {string=} required Sets `required` validation error key if the value is not entered.
  19248. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  19249. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  19250. * `required` when you want to data-bind to the `required` attribute.
  19251. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
  19252. * minlength.
  19253. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
  19254. * maxlength. Setting the attribute to a negative or non-numeric value, allows view values of
  19255. * any length.
  19256. * @param {string=} pattern Similar to `ngPattern` except that the attribute value is the actual string
  19257. * that contains the regular expression body that will be converted to a regular expression
  19258. * as in the ngPattern directive.
  19259. * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel value does not match
  19260. * a RegExp found by evaluating the Angular expression given in the attribute value.
  19261. * If the expression evaluates to a RegExp object, then this is used directly.
  19262. * If the expression evaluates to a string, then it will be converted to a RegExp
  19263. * after wrapping it in `^` and `$` characters. For instance, `"abc"` will be converted to
  19264. * `new RegExp('^abc$')`.<br />
  19265. * **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to
  19266. * start at the index of the last search's match, thus not taking the whole input value into
  19267. * account.
  19268. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  19269. * interaction with the input element.
  19270. *
  19271. * @example
  19272. <example name="number-input-directive" module="numberExample">
  19273. <file name="index.html">
  19274. <script>
  19275. angular.module('numberExample', [])
  19276. .controller('ExampleController', ['$scope', function($scope) {
  19277. $scope.example = {
  19278. value: 12
  19279. };
  19280. }]);
  19281. </script>
  19282. <form name="myForm" ng-controller="ExampleController">
  19283. <label>Number:
  19284. <input type="number" name="input" ng-model="example.value"
  19285. min="0" max="99" required>
  19286. </label>
  19287. <div role="alert">
  19288. <span class="error" ng-show="myForm.input.$error.required">
  19289. Required!</span>
  19290. <span class="error" ng-show="myForm.input.$error.number">
  19291. Not valid number!</span>
  19292. </div>
  19293. <tt>value = {{example.value}}</tt><br/>
  19294. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  19295. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  19296. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  19297. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  19298. </form>
  19299. </file>
  19300. <file name="protractor.js" type="protractor">
  19301. var value = element(by.binding('example.value'));
  19302. var valid = element(by.binding('myForm.input.$valid'));
  19303. var input = element(by.model('example.value'));
  19304. it('should initialize to model', function() {
  19305. expect(value.getText()).toContain('12');
  19306. expect(valid.getText()).toContain('true');
  19307. });
  19308. it('should be invalid if empty', function() {
  19309. input.clear();
  19310. input.sendKeys('');
  19311. expect(value.getText()).toEqual('value =');
  19312. expect(valid.getText()).toContain('false');
  19313. });
  19314. it('should be invalid if over max', function() {
  19315. input.clear();
  19316. input.sendKeys('123');
  19317. expect(value.getText()).toEqual('value =');
  19318. expect(valid.getText()).toContain('false');
  19319. });
  19320. </file>
  19321. </example>
  19322. */
  19323. 'number': numberInputType,
  19324. /**
  19325. * @ngdoc input
  19326. * @name input[url]
  19327. *
  19328. * @description
  19329. * Text input with URL validation. Sets the `url` validation error key if the content is not a
  19330. * valid URL.
  19331. *
  19332. * <div class="alert alert-warning">
  19333. * **Note:** `input[url]` uses a regex to validate urls that is derived from the regex
  19334. * used in Chromium. If you need stricter validation, you can use `ng-pattern` or modify
  19335. * the built-in validators (see the {@link guide/forms Forms guide})
  19336. * </div>
  19337. *
  19338. * @param {string} ngModel Assignable angular expression to data-bind to.
  19339. * @param {string=} name Property name of the form under which the control is published.
  19340. * @param {string=} required Sets `required` validation error key if the value is not entered.
  19341. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  19342. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  19343. * `required` when you want to data-bind to the `required` attribute.
  19344. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
  19345. * minlength.
  19346. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
  19347. * maxlength. Setting the attribute to a negative or non-numeric value, allows view values of
  19348. * any length.
  19349. * @param {string=} pattern Similar to `ngPattern` except that the attribute value is the actual string
  19350. * that contains the regular expression body that will be converted to a regular expression
  19351. * as in the ngPattern directive.
  19352. * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel value does not match
  19353. * a RegExp found by evaluating the Angular expression given in the attribute value.
  19354. * If the expression evaluates to a RegExp object, then this is used directly.
  19355. * If the expression evaluates to a string, then it will be converted to a RegExp
  19356. * after wrapping it in `^` and `$` characters. For instance, `"abc"` will be converted to
  19357. * `new RegExp('^abc$')`.<br />
  19358. * **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to
  19359. * start at the index of the last search's match, thus not taking the whole input value into
  19360. * account.
  19361. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  19362. * interaction with the input element.
  19363. *
  19364. * @example
  19365. <example name="url-input-directive" module="urlExample">
  19366. <file name="index.html">
  19367. <script>
  19368. angular.module('urlExample', [])
  19369. .controller('ExampleController', ['$scope', function($scope) {
  19370. $scope.url = {
  19371. text: 'http://google.com'
  19372. };
  19373. }]);
  19374. </script>
  19375. <form name="myForm" ng-controller="ExampleController">
  19376. <label>URL:
  19377. <input type="url" name="input" ng-model="url.text" required>
  19378. <label>
  19379. <div role="alert">
  19380. <span class="error" ng-show="myForm.input.$error.required">
  19381. Required!</span>
  19382. <span class="error" ng-show="myForm.input.$error.url">
  19383. Not valid url!</span>
  19384. </div>
  19385. <tt>text = {{url.text}}</tt><br/>
  19386. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  19387. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  19388. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  19389. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  19390. <tt>myForm.$error.url = {{!!myForm.$error.url}}</tt><br/>
  19391. </form>
  19392. </file>
  19393. <file name="protractor.js" type="protractor">
  19394. var text = element(by.binding('url.text'));
  19395. var valid = element(by.binding('myForm.input.$valid'));
  19396. var input = element(by.model('url.text'));
  19397. it('should initialize to model', function() {
  19398. expect(text.getText()).toContain('http://google.com');
  19399. expect(valid.getText()).toContain('true');
  19400. });
  19401. it('should be invalid if empty', function() {
  19402. input.clear();
  19403. input.sendKeys('');
  19404. expect(text.getText()).toEqual('text =');
  19405. expect(valid.getText()).toContain('false');
  19406. });
  19407. it('should be invalid if not url', function() {
  19408. input.clear();
  19409. input.sendKeys('box');
  19410. expect(valid.getText()).toContain('false');
  19411. });
  19412. </file>
  19413. </example>
  19414. */
  19415. 'url': urlInputType,
  19416. /**
  19417. * @ngdoc input
  19418. * @name input[email]
  19419. *
  19420. * @description
  19421. * Text input with email validation. Sets the `email` validation error key if not a valid email
  19422. * address.
  19423. *
  19424. * <div class="alert alert-warning">
  19425. * **Note:** `input[email]` uses a regex to validate email addresses that is derived from the regex
  19426. * used in Chromium. If you need stricter validation (e.g. requiring a top-level domain), you can
  19427. * use `ng-pattern` or modify the built-in validators (see the {@link guide/forms Forms guide})
  19428. * </div>
  19429. *
  19430. * @param {string} ngModel Assignable angular expression to data-bind to.
  19431. * @param {string=} name Property name of the form under which the control is published.
  19432. * @param {string=} required Sets `required` validation error key if the value is not entered.
  19433. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  19434. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  19435. * `required` when you want to data-bind to the `required` attribute.
  19436. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
  19437. * minlength.
  19438. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
  19439. * maxlength. Setting the attribute to a negative or non-numeric value, allows view values of
  19440. * any length.
  19441. * @param {string=} pattern Similar to `ngPattern` except that the attribute value is the actual string
  19442. * that contains the regular expression body that will be converted to a regular expression
  19443. * as in the ngPattern directive.
  19444. * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel value does not match
  19445. * a RegExp found by evaluating the Angular expression given in the attribute value.
  19446. * If the expression evaluates to a RegExp object, then this is used directly.
  19447. * If the expression evaluates to a string, then it will be converted to a RegExp
  19448. * after wrapping it in `^` and `$` characters. For instance, `"abc"` will be converted to
  19449. * `new RegExp('^abc$')`.<br />
  19450. * **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to
  19451. * start at the index of the last search's match, thus not taking the whole input value into
  19452. * account.
  19453. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  19454. * interaction with the input element.
  19455. *
  19456. * @example
  19457. <example name="email-input-directive" module="emailExample">
  19458. <file name="index.html">
  19459. <script>
  19460. angular.module('emailExample', [])
  19461. .controller('ExampleController', ['$scope', function($scope) {
  19462. $scope.email = {
  19463. text: 'me@example.com'
  19464. };
  19465. }]);
  19466. </script>
  19467. <form name="myForm" ng-controller="ExampleController">
  19468. <label>Email:
  19469. <input type="email" name="input" ng-model="email.text" required>
  19470. </label>
  19471. <div role="alert">
  19472. <span class="error" ng-show="myForm.input.$error.required">
  19473. Required!</span>
  19474. <span class="error" ng-show="myForm.input.$error.email">
  19475. Not valid email!</span>
  19476. </div>
  19477. <tt>text = {{email.text}}</tt><br/>
  19478. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  19479. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  19480. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  19481. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  19482. <tt>myForm.$error.email = {{!!myForm.$error.email}}</tt><br/>
  19483. </form>
  19484. </file>
  19485. <file name="protractor.js" type="protractor">
  19486. var text = element(by.binding('email.text'));
  19487. var valid = element(by.binding('myForm.input.$valid'));
  19488. var input = element(by.model('email.text'));
  19489. it('should initialize to model', function() {
  19490. expect(text.getText()).toContain('me@example.com');
  19491. expect(valid.getText()).toContain('true');
  19492. });
  19493. it('should be invalid if empty', function() {
  19494. input.clear();
  19495. input.sendKeys('');
  19496. expect(text.getText()).toEqual('text =');
  19497. expect(valid.getText()).toContain('false');
  19498. });
  19499. it('should be invalid if not email', function() {
  19500. input.clear();
  19501. input.sendKeys('xxx');
  19502. expect(valid.getText()).toContain('false');
  19503. });
  19504. </file>
  19505. </example>
  19506. */
  19507. 'email': emailInputType,
  19508. /**
  19509. * @ngdoc input
  19510. * @name input[radio]
  19511. *
  19512. * @description
  19513. * HTML radio button.
  19514. *
  19515. * @param {string} ngModel Assignable angular expression to data-bind to.
  19516. * @param {string} value The value to which the `ngModel` expression should be set when selected.
  19517. * Note that `value` only supports `string` values, i.e. the scope model needs to be a string,
  19518. * too. Use `ngValue` if you need complex models (`number`, `object`, ...).
  19519. * @param {string=} name Property name of the form under which the control is published.
  19520. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  19521. * interaction with the input element.
  19522. * @param {string} ngValue Angular expression to which `ngModel` will be be set when the radio
  19523. * is selected. Should be used instead of the `value` attribute if you need
  19524. * a non-string `ngModel` (`boolean`, `array`, ...).
  19525. *
  19526. * @example
  19527. <example name="radio-input-directive" module="radioExample">
  19528. <file name="index.html">
  19529. <script>
  19530. angular.module('radioExample', [])
  19531. .controller('ExampleController', ['$scope', function($scope) {
  19532. $scope.color = {
  19533. name: 'blue'
  19534. };
  19535. $scope.specialValue = {
  19536. "id": "12345",
  19537. "value": "green"
  19538. };
  19539. }]);
  19540. </script>
  19541. <form name="myForm" ng-controller="ExampleController">
  19542. <label>
  19543. <input type="radio" ng-model="color.name" value="red">
  19544. Red
  19545. </label><br/>
  19546. <label>
  19547. <input type="radio" ng-model="color.name" ng-value="specialValue">
  19548. Green
  19549. </label><br/>
  19550. <label>
  19551. <input type="radio" ng-model="color.name" value="blue">
  19552. Blue
  19553. </label><br/>
  19554. <tt>color = {{color.name | json}}</tt><br/>
  19555. </form>
  19556. Note that `ng-value="specialValue"` sets radio item's value to be the value of `$scope.specialValue`.
  19557. </file>
  19558. <file name="protractor.js" type="protractor">
  19559. it('should change state', function() {
  19560. var color = element(by.binding('color.name'));
  19561. expect(color.getText()).toContain('blue');
  19562. element.all(by.model('color.name')).get(0).click();
  19563. expect(color.getText()).toContain('red');
  19564. });
  19565. </file>
  19566. </example>
  19567. */
  19568. 'radio': radioInputType,
  19569. /**
  19570. * @ngdoc input
  19571. * @name input[checkbox]
  19572. *
  19573. * @description
  19574. * HTML checkbox.
  19575. *
  19576. * @param {string} ngModel Assignable angular expression to data-bind to.
  19577. * @param {string=} name Property name of the form under which the control is published.
  19578. * @param {expression=} ngTrueValue The value to which the expression should be set when selected.
  19579. * @param {expression=} ngFalseValue The value to which the expression should be set when not selected.
  19580. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  19581. * interaction with the input element.
  19582. *
  19583. * @example
  19584. <example name="checkbox-input-directive" module="checkboxExample">
  19585. <file name="index.html">
  19586. <script>
  19587. angular.module('checkboxExample', [])
  19588. .controller('ExampleController', ['$scope', function($scope) {
  19589. $scope.checkboxModel = {
  19590. value1 : true,
  19591. value2 : 'YES'
  19592. };
  19593. }]);
  19594. </script>
  19595. <form name="myForm" ng-controller="ExampleController">
  19596. <label>Value1:
  19597. <input type="checkbox" ng-model="checkboxModel.value1">
  19598. </label><br/>
  19599. <label>Value2:
  19600. <input type="checkbox" ng-model="checkboxModel.value2"
  19601. ng-true-value="'YES'" ng-false-value="'NO'">
  19602. </label><br/>
  19603. <tt>value1 = {{checkboxModel.value1}}</tt><br/>
  19604. <tt>value2 = {{checkboxModel.value2}}</tt><br/>
  19605. </form>
  19606. </file>
  19607. <file name="protractor.js" type="protractor">
  19608. it('should change state', function() {
  19609. var value1 = element(by.binding('checkboxModel.value1'));
  19610. var value2 = element(by.binding('checkboxModel.value2'));
  19611. expect(value1.getText()).toContain('true');
  19612. expect(value2.getText()).toContain('YES');
  19613. element(by.model('checkboxModel.value1')).click();
  19614. element(by.model('checkboxModel.value2')).click();
  19615. expect(value1.getText()).toContain('false');
  19616. expect(value2.getText()).toContain('NO');
  19617. });
  19618. </file>
  19619. </example>
  19620. */
  19621. 'checkbox': checkboxInputType,
  19622. 'hidden': noop,
  19623. 'button': noop,
  19624. 'submit': noop,
  19625. 'reset': noop,
  19626. 'file': noop
  19627. };
  19628. function stringBasedInputType(ctrl) {
  19629. ctrl.$formatters.push(function(value) {
  19630. return ctrl.$isEmpty(value) ? value : value.toString();
  19631. });
  19632. }
  19633. function textInputType(scope, element, attr, ctrl, $sniffer, $browser) {
  19634. baseInputType(scope, element, attr, ctrl, $sniffer, $browser);
  19635. stringBasedInputType(ctrl);
  19636. }
  19637. function baseInputType(scope, element, attr, ctrl, $sniffer, $browser) {
  19638. var type = lowercase(element[0].type);
  19639. // In composition mode, users are still inputing intermediate text buffer,
  19640. // hold the listener until composition is done.
  19641. // More about composition events: https://developer.mozilla.org/en-US/docs/Web/API/CompositionEvent
  19642. if (!$sniffer.android) {
  19643. var composing = false;
  19644. element.on('compositionstart', function(data) {
  19645. composing = true;
  19646. });
  19647. element.on('compositionend', function() {
  19648. composing = false;
  19649. listener();
  19650. });
  19651. }
  19652. var listener = function(ev) {
  19653. if (timeout) {
  19654. $browser.defer.cancel(timeout);
  19655. timeout = null;
  19656. }
  19657. if (composing) return;
  19658. var value = element.val(),
  19659. event = ev && ev.type;
  19660. // By default we will trim the value
  19661. // If the attribute ng-trim exists we will avoid trimming
  19662. // If input type is 'password', the value is never trimmed
  19663. if (type !== 'password' && (!attr.ngTrim || attr.ngTrim !== 'false')) {
  19664. value = trim(value);
  19665. }
  19666. // If a control is suffering from bad input (due to native validators), browsers discard its
  19667. // value, so it may be necessary to revalidate (by calling $setViewValue again) even if the
  19668. // control's value is the same empty value twice in a row.
  19669. if (ctrl.$viewValue !== value || (value === '' && ctrl.$$hasNativeValidators)) {
  19670. ctrl.$setViewValue(value, event);
  19671. }
  19672. };
  19673. // if the browser does support "input" event, we are fine - except on IE9 which doesn't fire the
  19674. // input event on backspace, delete or cut
  19675. if ($sniffer.hasEvent('input')) {
  19676. element.on('input', listener);
  19677. } else {
  19678. var timeout;
  19679. var deferListener = function(ev, input, origValue) {
  19680. if (!timeout) {
  19681. timeout = $browser.defer(function() {
  19682. timeout = null;
  19683. if (!input || input.value !== origValue) {
  19684. listener(ev);
  19685. }
  19686. });
  19687. }
  19688. };
  19689. element.on('keydown', function(event) {
  19690. var key = event.keyCode;
  19691. // ignore
  19692. // command modifiers arrows
  19693. if (key === 91 || (15 < key && key < 19) || (37 <= key && key <= 40)) return;
  19694. deferListener(event, this, this.value);
  19695. });
  19696. // if user modifies input value using context menu in IE, we need "paste" and "cut" events to catch it
  19697. if ($sniffer.hasEvent('paste')) {
  19698. element.on('paste cut', deferListener);
  19699. }
  19700. }
  19701. // if user paste into input using mouse on older browser
  19702. // or form autocomplete on newer browser, we need "change" event to catch it
  19703. element.on('change', listener);
  19704. ctrl.$render = function() {
  19705. // Workaround for Firefox validation #12102.
  19706. var value = ctrl.$isEmpty(ctrl.$viewValue) ? '' : ctrl.$viewValue;
  19707. if (element.val() !== value) {
  19708. element.val(value);
  19709. }
  19710. };
  19711. }
  19712. function weekParser(isoWeek, existingDate) {
  19713. if (isDate(isoWeek)) {
  19714. return isoWeek;
  19715. }
  19716. if (isString(isoWeek)) {
  19717. WEEK_REGEXP.lastIndex = 0;
  19718. var parts = WEEK_REGEXP.exec(isoWeek);
  19719. if (parts) {
  19720. var year = +parts[1],
  19721. week = +parts[2],
  19722. hours = 0,
  19723. minutes = 0,
  19724. seconds = 0,
  19725. milliseconds = 0,
  19726. firstThurs = getFirstThursdayOfYear(year),
  19727. addDays = (week - 1) * 7;
  19728. if (existingDate) {
  19729. hours = existingDate.getHours();
  19730. minutes = existingDate.getMinutes();
  19731. seconds = existingDate.getSeconds();
  19732. milliseconds = existingDate.getMilliseconds();
  19733. }
  19734. return new Date(year, 0, firstThurs.getDate() + addDays, hours, minutes, seconds, milliseconds);
  19735. }
  19736. }
  19737. return NaN;
  19738. }
  19739. function createDateParser(regexp, mapping) {
  19740. return function(iso, date) {
  19741. var parts, map;
  19742. if (isDate(iso)) {
  19743. return iso;
  19744. }
  19745. if (isString(iso)) {
  19746. // When a date is JSON'ified to wraps itself inside of an extra
  19747. // set of double quotes. This makes the date parsing code unable
  19748. // to match the date string and parse it as a date.
  19749. if (iso.charAt(0) == '"' && iso.charAt(iso.length - 1) == '"') {
  19750. iso = iso.substring(1, iso.length - 1);
  19751. }
  19752. if (ISO_DATE_REGEXP.test(iso)) {
  19753. return new Date(iso);
  19754. }
  19755. regexp.lastIndex = 0;
  19756. parts = regexp.exec(iso);
  19757. if (parts) {
  19758. parts.shift();
  19759. if (date) {
  19760. map = {
  19761. yyyy: date.getFullYear(),
  19762. MM: date.getMonth() + 1,
  19763. dd: date.getDate(),
  19764. HH: date.getHours(),
  19765. mm: date.getMinutes(),
  19766. ss: date.getSeconds(),
  19767. sss: date.getMilliseconds() / 1000
  19768. };
  19769. } else {
  19770. map = { yyyy: 1970, MM: 1, dd: 1, HH: 0, mm: 0, ss: 0, sss: 0 };
  19771. }
  19772. forEach(parts, function(part, index) {
  19773. if (index < mapping.length) {
  19774. map[mapping[index]] = +part;
  19775. }
  19776. });
  19777. return new Date(map.yyyy, map.MM - 1, map.dd, map.HH, map.mm, map.ss || 0, map.sss * 1000 || 0);
  19778. }
  19779. }
  19780. return NaN;
  19781. };
  19782. }
  19783. function createDateInputType(type, regexp, parseDate, format) {
  19784. return function dynamicDateInputType(scope, element, attr, ctrl, $sniffer, $browser, $filter) {
  19785. badInputChecker(scope, element, attr, ctrl);
  19786. baseInputType(scope, element, attr, ctrl, $sniffer, $browser);
  19787. var timezone = ctrl && ctrl.$options && ctrl.$options.timezone;
  19788. var previousDate;
  19789. ctrl.$$parserName = type;
  19790. ctrl.$parsers.push(function(value) {
  19791. if (ctrl.$isEmpty(value)) return null;
  19792. if (regexp.test(value)) {
  19793. // Note: We cannot read ctrl.$modelValue, as there might be a different
  19794. // parser/formatter in the processing chain so that the model
  19795. // contains some different data format!
  19796. var parsedDate = parseDate(value, previousDate);
  19797. if (timezone) {
  19798. parsedDate = convertTimezoneToLocal(parsedDate, timezone);
  19799. }
  19800. return parsedDate;
  19801. }
  19802. return undefined;
  19803. });
  19804. ctrl.$formatters.push(function(value) {
  19805. if (value && !isDate(value)) {
  19806. throw ngModelMinErr('datefmt', 'Expected `{0}` to be a date', value);
  19807. }
  19808. if (isValidDate(value)) {
  19809. previousDate = value;
  19810. if (previousDate && timezone) {
  19811. previousDate = convertTimezoneToLocal(previousDate, timezone, true);
  19812. }
  19813. return $filter('date')(value, format, timezone);
  19814. } else {
  19815. previousDate = null;
  19816. return '';
  19817. }
  19818. });
  19819. if (isDefined(attr.min) || attr.ngMin) {
  19820. var minVal;
  19821. ctrl.$validators.min = function(value) {
  19822. return !isValidDate(value) || isUndefined(minVal) || parseDate(value) >= minVal;
  19823. };
  19824. attr.$observe('min', function(val) {
  19825. minVal = parseObservedDateValue(val);
  19826. ctrl.$validate();
  19827. });
  19828. }
  19829. if (isDefined(attr.max) || attr.ngMax) {
  19830. var maxVal;
  19831. ctrl.$validators.max = function(value) {
  19832. return !isValidDate(value) || isUndefined(maxVal) || parseDate(value) <= maxVal;
  19833. };
  19834. attr.$observe('max', function(val) {
  19835. maxVal = parseObservedDateValue(val);
  19836. ctrl.$validate();
  19837. });
  19838. }
  19839. function isValidDate(value) {
  19840. // Invalid Date: getTime() returns NaN
  19841. return value && !(value.getTime && value.getTime() !== value.getTime());
  19842. }
  19843. function parseObservedDateValue(val) {
  19844. return isDefined(val) && !isDate(val) ? parseDate(val) || undefined : val;
  19845. }
  19846. };
  19847. }
  19848. function badInputChecker(scope, element, attr, ctrl) {
  19849. var node = element[0];
  19850. var nativeValidation = ctrl.$$hasNativeValidators = isObject(node.validity);
  19851. if (nativeValidation) {
  19852. ctrl.$parsers.push(function(value) {
  19853. var validity = element.prop(VALIDITY_STATE_PROPERTY) || {};
  19854. // Detect bug in FF35 for input[email] (https://bugzilla.mozilla.org/show_bug.cgi?id=1064430):
  19855. // - also sets validity.badInput (should only be validity.typeMismatch).
  19856. // - see http://www.whatwg.org/specs/web-apps/current-work/multipage/forms.html#e-mail-state-(type=email)
  19857. // - can ignore this case as we can still read out the erroneous email...
  19858. return validity.badInput && !validity.typeMismatch ? undefined : value;
  19859. });
  19860. }
  19861. }
  19862. function numberInputType(scope, element, attr, ctrl, $sniffer, $browser) {
  19863. badInputChecker(scope, element, attr, ctrl);
  19864. baseInputType(scope, element, attr, ctrl, $sniffer, $browser);
  19865. ctrl.$$parserName = 'number';
  19866. ctrl.$parsers.push(function(value) {
  19867. if (ctrl.$isEmpty(value)) return null;
  19868. if (NUMBER_REGEXP.test(value)) return parseFloat(value);
  19869. return undefined;
  19870. });
  19871. ctrl.$formatters.push(function(value) {
  19872. if (!ctrl.$isEmpty(value)) {
  19873. if (!isNumber(value)) {
  19874. throw ngModelMinErr('numfmt', 'Expected `{0}` to be a number', value);
  19875. }
  19876. value = value.toString();
  19877. }
  19878. return value;
  19879. });
  19880. if (isDefined(attr.min) || attr.ngMin) {
  19881. var minVal;
  19882. ctrl.$validators.min = function(value) {
  19883. return ctrl.$isEmpty(value) || isUndefined(minVal) || value >= minVal;
  19884. };
  19885. attr.$observe('min', function(val) {
  19886. if (isDefined(val) && !isNumber(val)) {
  19887. val = parseFloat(val, 10);
  19888. }
  19889. minVal = isNumber(val) && !isNaN(val) ? val : undefined;
  19890. // TODO(matsko): implement validateLater to reduce number of validations
  19891. ctrl.$validate();
  19892. });
  19893. }
  19894. if (isDefined(attr.max) || attr.ngMax) {
  19895. var maxVal;
  19896. ctrl.$validators.max = function(value) {
  19897. return ctrl.$isEmpty(value) || isUndefined(maxVal) || value <= maxVal;
  19898. };
  19899. attr.$observe('max', function(val) {
  19900. if (isDefined(val) && !isNumber(val)) {
  19901. val = parseFloat(val, 10);
  19902. }
  19903. maxVal = isNumber(val) && !isNaN(val) ? val : undefined;
  19904. // TODO(matsko): implement validateLater to reduce number of validations
  19905. ctrl.$validate();
  19906. });
  19907. }
  19908. }
  19909. function urlInputType(scope, element, attr, ctrl, $sniffer, $browser) {
  19910. // Note: no badInputChecker here by purpose as `url` is only a validation
  19911. // in browsers, i.e. we can always read out input.value even if it is not valid!
  19912. baseInputType(scope, element, attr, ctrl, $sniffer, $browser);
  19913. stringBasedInputType(ctrl);
  19914. ctrl.$$parserName = 'url';
  19915. ctrl.$validators.url = function(modelValue, viewValue) {
  19916. var value = modelValue || viewValue;
  19917. return ctrl.$isEmpty(value) || URL_REGEXP.test(value);
  19918. };
  19919. }
  19920. function emailInputType(scope, element, attr, ctrl, $sniffer, $browser) {
  19921. // Note: no badInputChecker here by purpose as `url` is only a validation
  19922. // in browsers, i.e. we can always read out input.value even if it is not valid!
  19923. baseInputType(scope, element, attr, ctrl, $sniffer, $browser);
  19924. stringBasedInputType(ctrl);
  19925. ctrl.$$parserName = 'email';
  19926. ctrl.$validators.email = function(modelValue, viewValue) {
  19927. var value = modelValue || viewValue;
  19928. return ctrl.$isEmpty(value) || EMAIL_REGEXP.test(value);
  19929. };
  19930. }
  19931. function radioInputType(scope, element, attr, ctrl) {
  19932. // make the name unique, if not defined
  19933. if (isUndefined(attr.name)) {
  19934. element.attr('name', nextUid());
  19935. }
  19936. var listener = function(ev) {
  19937. if (element[0].checked) {
  19938. ctrl.$setViewValue(attr.value, ev && ev.type);
  19939. }
  19940. };
  19941. element.on('click', listener);
  19942. ctrl.$render = function() {
  19943. var value = attr.value;
  19944. element[0].checked = (value == ctrl.$viewValue);
  19945. };
  19946. attr.$observe('value', ctrl.$render);
  19947. }
  19948. function parseConstantExpr($parse, context, name, expression, fallback) {
  19949. var parseFn;
  19950. if (isDefined(expression)) {
  19951. parseFn = $parse(expression);
  19952. if (!parseFn.constant) {
  19953. throw ngModelMinErr('constexpr', 'Expected constant expression for `{0}`, but saw ' +
  19954. '`{1}`.', name, expression);
  19955. }
  19956. return parseFn(context);
  19957. }
  19958. return fallback;
  19959. }
  19960. function checkboxInputType(scope, element, attr, ctrl, $sniffer, $browser, $filter, $parse) {
  19961. var trueValue = parseConstantExpr($parse, scope, 'ngTrueValue', attr.ngTrueValue, true);
  19962. var falseValue = parseConstantExpr($parse, scope, 'ngFalseValue', attr.ngFalseValue, false);
  19963. var listener = function(ev) {
  19964. ctrl.$setViewValue(element[0].checked, ev && ev.type);
  19965. };
  19966. element.on('click', listener);
  19967. ctrl.$render = function() {
  19968. element[0].checked = ctrl.$viewValue;
  19969. };
  19970. // Override the standard `$isEmpty` because the $viewValue of an empty checkbox is always set to `false`
  19971. // This is because of the parser below, which compares the `$modelValue` with `trueValue` to convert
  19972. // it to a boolean.
  19973. ctrl.$isEmpty = function(value) {
  19974. return value === false;
  19975. };
  19976. ctrl.$formatters.push(function(value) {
  19977. return equals(value, trueValue);
  19978. });
  19979. ctrl.$parsers.push(function(value) {
  19980. return value ? trueValue : falseValue;
  19981. });
  19982. }
  19983. /**
  19984. * @ngdoc directive
  19985. * @name textarea
  19986. * @restrict E
  19987. *
  19988. * @description
  19989. * HTML textarea element control with angular data-binding. The data-binding and validation
  19990. * properties of this element are exactly the same as those of the
  19991. * {@link ng.directive:input input element}.
  19992. *
  19993. * @param {string} ngModel Assignable angular expression to data-bind to.
  19994. * @param {string=} name Property name of the form under which the control is published.
  19995. * @param {string=} required Sets `required` validation error key if the value is not entered.
  19996. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  19997. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  19998. * `required` when you want to data-bind to the `required` attribute.
  19999. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
  20000. * minlength.
  20001. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
  20002. * maxlength. Setting the attribute to a negative or non-numeric value, allows view values of any
  20003. * length.
  20004. * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel value does not match
  20005. * a RegExp found by evaluating the Angular expression given in the attribute value.
  20006. * If the expression evaluates to a RegExp object, then this is used directly.
  20007. * If the expression evaluates to a string, then it will be converted to a RegExp
  20008. * after wrapping it in `^` and `$` characters. For instance, `"abc"` will be converted to
  20009. * `new RegExp('^abc$')`.<br />
  20010. * **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to
  20011. * start at the index of the last search's match, thus not taking the whole input value into
  20012. * account.
  20013. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  20014. * interaction with the input element.
  20015. * @param {boolean=} [ngTrim=true] If set to false Angular will not automatically trim the input.
  20016. */
  20017. /**
  20018. * @ngdoc directive
  20019. * @name input
  20020. * @restrict E
  20021. *
  20022. * @description
  20023. * HTML input element control. When used together with {@link ngModel `ngModel`}, it provides data-binding,
  20024. * input state control, and validation.
  20025. * Input control follows HTML5 input types and polyfills the HTML5 validation behavior for older browsers.
  20026. *
  20027. * <div class="alert alert-warning">
  20028. * **Note:** Not every feature offered is available for all input types.
  20029. * Specifically, data binding and event handling via `ng-model` is unsupported for `input[file]`.
  20030. * </div>
  20031. *
  20032. * @param {string} ngModel Assignable angular expression to data-bind to.
  20033. * @param {string=} name Property name of the form under which the control is published.
  20034. * @param {string=} required Sets `required` validation error key if the value is not entered.
  20035. * @param {boolean=} ngRequired Sets `required` attribute if set to true
  20036. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
  20037. * minlength.
  20038. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
  20039. * maxlength. Setting the attribute to a negative or non-numeric value, allows view values of any
  20040. * length.
  20041. * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel value does not match
  20042. * a RegExp found by evaluating the Angular expression given in the attribute value.
  20043. * If the expression evaluates to a RegExp object, then this is used directly.
  20044. * If the expression evaluates to a string, then it will be converted to a RegExp
  20045. * after wrapping it in `^` and `$` characters. For instance, `"abc"` will be converted to
  20046. * `new RegExp('^abc$')`.<br />
  20047. * **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to
  20048. * start at the index of the last search's match, thus not taking the whole input value into
  20049. * account.
  20050. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  20051. * interaction with the input element.
  20052. * @param {boolean=} [ngTrim=true] If set to false Angular will not automatically trim the input.
  20053. * This parameter is ignored for input[type=password] controls, which will never trim the
  20054. * input.
  20055. *
  20056. * @example
  20057. <example name="input-directive" module="inputExample">
  20058. <file name="index.html">
  20059. <script>
  20060. angular.module('inputExample', [])
  20061. .controller('ExampleController', ['$scope', function($scope) {
  20062. $scope.user = {name: 'guest', last: 'visitor'};
  20063. }]);
  20064. </script>
  20065. <div ng-controller="ExampleController">
  20066. <form name="myForm">
  20067. <label>
  20068. User name:
  20069. <input type="text" name="userName" ng-model="user.name" required>
  20070. </label>
  20071. <div role="alert">
  20072. <span class="error" ng-show="myForm.userName.$error.required">
  20073. Required!</span>
  20074. </div>
  20075. <label>
  20076. Last name:
  20077. <input type="text" name="lastName" ng-model="user.last"
  20078. ng-minlength="3" ng-maxlength="10">
  20079. </label>
  20080. <div role="alert">
  20081. <span class="error" ng-show="myForm.lastName.$error.minlength">
  20082. Too short!</span>
  20083. <span class="error" ng-show="myForm.lastName.$error.maxlength">
  20084. Too long!</span>
  20085. </div>
  20086. </form>
  20087. <hr>
  20088. <tt>user = {{user}}</tt><br/>
  20089. <tt>myForm.userName.$valid = {{myForm.userName.$valid}}</tt><br/>
  20090. <tt>myForm.userName.$error = {{myForm.userName.$error}}</tt><br/>
  20091. <tt>myForm.lastName.$valid = {{myForm.lastName.$valid}}</tt><br/>
  20092. <tt>myForm.lastName.$error = {{myForm.lastName.$error}}</tt><br/>
  20093. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  20094. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  20095. <tt>myForm.$error.minlength = {{!!myForm.$error.minlength}}</tt><br/>
  20096. <tt>myForm.$error.maxlength = {{!!myForm.$error.maxlength}}</tt><br/>
  20097. </div>
  20098. </file>
  20099. <file name="protractor.js" type="protractor">
  20100. var user = element(by.exactBinding('user'));
  20101. var userNameValid = element(by.binding('myForm.userName.$valid'));
  20102. var lastNameValid = element(by.binding('myForm.lastName.$valid'));
  20103. var lastNameError = element(by.binding('myForm.lastName.$error'));
  20104. var formValid = element(by.binding('myForm.$valid'));
  20105. var userNameInput = element(by.model('user.name'));
  20106. var userLastInput = element(by.model('user.last'));
  20107. it('should initialize to model', function() {
  20108. expect(user.getText()).toContain('{"name":"guest","last":"visitor"}');
  20109. expect(userNameValid.getText()).toContain('true');
  20110. expect(formValid.getText()).toContain('true');
  20111. });
  20112. it('should be invalid if empty when required', function() {
  20113. userNameInput.clear();
  20114. userNameInput.sendKeys('');
  20115. expect(user.getText()).toContain('{"last":"visitor"}');
  20116. expect(userNameValid.getText()).toContain('false');
  20117. expect(formValid.getText()).toContain('false');
  20118. });
  20119. it('should be valid if empty when min length is set', function() {
  20120. userLastInput.clear();
  20121. userLastInput.sendKeys('');
  20122. expect(user.getText()).toContain('{"name":"guest","last":""}');
  20123. expect(lastNameValid.getText()).toContain('true');
  20124. expect(formValid.getText()).toContain('true');
  20125. });
  20126. it('should be invalid if less than required min length', function() {
  20127. userLastInput.clear();
  20128. userLastInput.sendKeys('xx');
  20129. expect(user.getText()).toContain('{"name":"guest"}');
  20130. expect(lastNameValid.getText()).toContain('false');
  20131. expect(lastNameError.getText()).toContain('minlength');
  20132. expect(formValid.getText()).toContain('false');
  20133. });
  20134. it('should be invalid if longer than max length', function() {
  20135. userLastInput.clear();
  20136. userLastInput.sendKeys('some ridiculously long name');
  20137. expect(user.getText()).toContain('{"name":"guest"}');
  20138. expect(lastNameValid.getText()).toContain('false');
  20139. expect(lastNameError.getText()).toContain('maxlength');
  20140. expect(formValid.getText()).toContain('false');
  20141. });
  20142. </file>
  20143. </example>
  20144. */
  20145. var inputDirective = ['$browser', '$sniffer', '$filter', '$parse',
  20146. function($browser, $sniffer, $filter, $parse) {
  20147. return {
  20148. restrict: 'E',
  20149. require: ['?ngModel'],
  20150. link: {
  20151. pre: function(scope, element, attr, ctrls) {
  20152. if (ctrls[0]) {
  20153. (inputType[lowercase(attr.type)] || inputType.text)(scope, element, attr, ctrls[0], $sniffer,
  20154. $browser, $filter, $parse);
  20155. }
  20156. }
  20157. }
  20158. };
  20159. }];
  20160. var CONSTANT_VALUE_REGEXP = /^(true|false|\d+)$/;
  20161. /**
  20162. * @ngdoc directive
  20163. * @name ngValue
  20164. *
  20165. * @description
  20166. * Binds the given expression to the value of `<option>` or {@link input[radio] `input[radio]`},
  20167. * so that when the element is selected, the {@link ngModel `ngModel`} of that element is set to
  20168. * the bound value.
  20169. *
  20170. * `ngValue` is useful when dynamically generating lists of radio buttons using
  20171. * {@link ngRepeat `ngRepeat`}, as shown below.
  20172. *
  20173. * Likewise, `ngValue` can be used to generate `<option>` elements for
  20174. * the {@link select `select`} element. In that case however, only strings are supported
  20175. * for the `value `attribute, so the resulting `ngModel` will always be a string.
  20176. * Support for `select` models with non-string values is available via `ngOptions`.
  20177. *
  20178. * @element input
  20179. * @param {string=} ngValue angular expression, whose value will be bound to the `value` attribute
  20180. * of the `input` element
  20181. *
  20182. * @example
  20183. <example name="ngValue-directive" module="valueExample">
  20184. <file name="index.html">
  20185. <script>
  20186. angular.module('valueExample', [])
  20187. .controller('ExampleController', ['$scope', function($scope) {
  20188. $scope.names = ['pizza', 'unicorns', 'robots'];
  20189. $scope.my = { favorite: 'unicorns' };
  20190. }]);
  20191. </script>
  20192. <form ng-controller="ExampleController">
  20193. <h2>Which is your favorite?</h2>
  20194. <label ng-repeat="name in names" for="{{name}}">
  20195. {{name}}
  20196. <input type="radio"
  20197. ng-model="my.favorite"
  20198. ng-value="name"
  20199. id="{{name}}"
  20200. name="favorite">
  20201. </label>
  20202. <div>You chose {{my.favorite}}</div>
  20203. </form>
  20204. </file>
  20205. <file name="protractor.js" type="protractor">
  20206. var favorite = element(by.binding('my.favorite'));
  20207. it('should initialize to model', function() {
  20208. expect(favorite.getText()).toContain('unicorns');
  20209. });
  20210. it('should bind the values to the inputs', function() {
  20211. element.all(by.model('my.favorite')).get(0).click();
  20212. expect(favorite.getText()).toContain('pizza');
  20213. });
  20214. </file>
  20215. </example>
  20216. */
  20217. var ngValueDirective = function() {
  20218. return {
  20219. restrict: 'A',
  20220. priority: 100,
  20221. compile: function(tpl, tplAttr) {
  20222. if (CONSTANT_VALUE_REGEXP.test(tplAttr.ngValue)) {
  20223. return function ngValueConstantLink(scope, elm, attr) {
  20224. attr.$set('value', scope.$eval(attr.ngValue));
  20225. };
  20226. } else {
  20227. return function ngValueLink(scope, elm, attr) {
  20228. scope.$watch(attr.ngValue, function valueWatchAction(value) {
  20229. attr.$set('value', value);
  20230. });
  20231. };
  20232. }
  20233. }
  20234. };
  20235. };
  20236. /**
  20237. * @ngdoc directive
  20238. * @name ngBind
  20239. * @restrict AC
  20240. *
  20241. * @description
  20242. * The `ngBind` attribute tells Angular to replace the text content of the specified HTML element
  20243. * with the value of a given expression, and to update the text content when the value of that
  20244. * expression changes.
  20245. *
  20246. * Typically, you don't use `ngBind` directly, but instead you use the double curly markup like
  20247. * `{{ expression }}` which is similar but less verbose.
  20248. *
  20249. * It is preferable to use `ngBind` instead of `{{ expression }}` if a template is momentarily
  20250. * displayed by the browser in its raw state before Angular compiles it. Since `ngBind` is an
  20251. * element attribute, it makes the bindings invisible to the user while the page is loading.
  20252. *
  20253. * An alternative solution to this problem would be using the
  20254. * {@link ng.directive:ngCloak ngCloak} directive.
  20255. *
  20256. *
  20257. * @element ANY
  20258. * @param {expression} ngBind {@link guide/expression Expression} to evaluate.
  20259. *
  20260. * @example
  20261. * Enter a name in the Live Preview text box; the greeting below the text box changes instantly.
  20262. <example module="bindExample">
  20263. <file name="index.html">
  20264. <script>
  20265. angular.module('bindExample', [])
  20266. .controller('ExampleController', ['$scope', function($scope) {
  20267. $scope.name = 'Whirled';
  20268. }]);
  20269. </script>
  20270. <div ng-controller="ExampleController">
  20271. <label>Enter name: <input type="text" ng-model="name"></label><br>
  20272. Hello <span ng-bind="name"></span>!
  20273. </div>
  20274. </file>
  20275. <file name="protractor.js" type="protractor">
  20276. it('should check ng-bind', function() {
  20277. var nameInput = element(by.model('name'));
  20278. expect(element(by.binding('name')).getText()).toBe('Whirled');
  20279. nameInput.clear();
  20280. nameInput.sendKeys('world');
  20281. expect(element(by.binding('name')).getText()).toBe('world');
  20282. });
  20283. </file>
  20284. </example>
  20285. */
  20286. var ngBindDirective = ['$compile', function($compile) {
  20287. return {
  20288. restrict: 'AC',
  20289. compile: function ngBindCompile(templateElement) {
  20290. $compile.$$addBindingClass(templateElement);
  20291. return function ngBindLink(scope, element, attr) {
  20292. $compile.$$addBindingInfo(element, attr.ngBind);
  20293. element = element[0];
  20294. scope.$watch(attr.ngBind, function ngBindWatchAction(value) {
  20295. element.textContent = isUndefined(value) ? '' : value;
  20296. });
  20297. };
  20298. }
  20299. };
  20300. }];
  20301. /**
  20302. * @ngdoc directive
  20303. * @name ngBindTemplate
  20304. *
  20305. * @description
  20306. * The `ngBindTemplate` directive specifies that the element
  20307. * text content should be replaced with the interpolation of the template
  20308. * in the `ngBindTemplate` attribute.
  20309. * Unlike `ngBind`, the `ngBindTemplate` can contain multiple `{{` `}}`
  20310. * expressions. This directive is needed since some HTML elements
  20311. * (such as TITLE and OPTION) cannot contain SPAN elements.
  20312. *
  20313. * @element ANY
  20314. * @param {string} ngBindTemplate template of form
  20315. * <tt>{{</tt> <tt>expression</tt> <tt>}}</tt> to eval.
  20316. *
  20317. * @example
  20318. * Try it here: enter text in text box and watch the greeting change.
  20319. <example module="bindExample">
  20320. <file name="index.html">
  20321. <script>
  20322. angular.module('bindExample', [])
  20323. .controller('ExampleController', ['$scope', function($scope) {
  20324. $scope.salutation = 'Hello';
  20325. $scope.name = 'World';
  20326. }]);
  20327. </script>
  20328. <div ng-controller="ExampleController">
  20329. <label>Salutation: <input type="text" ng-model="salutation"></label><br>
  20330. <label>Name: <input type="text" ng-model="name"></label><br>
  20331. <pre ng-bind-template="{{salutation}} {{name}}!"></pre>
  20332. </div>
  20333. </file>
  20334. <file name="protractor.js" type="protractor">
  20335. it('should check ng-bind', function() {
  20336. var salutationElem = element(by.binding('salutation'));
  20337. var salutationInput = element(by.model('salutation'));
  20338. var nameInput = element(by.model('name'));
  20339. expect(salutationElem.getText()).toBe('Hello World!');
  20340. salutationInput.clear();
  20341. salutationInput.sendKeys('Greetings');
  20342. nameInput.clear();
  20343. nameInput.sendKeys('user');
  20344. expect(salutationElem.getText()).toBe('Greetings user!');
  20345. });
  20346. </file>
  20347. </example>
  20348. */
  20349. var ngBindTemplateDirective = ['$interpolate', '$compile', function($interpolate, $compile) {
  20350. return {
  20351. compile: function ngBindTemplateCompile(templateElement) {
  20352. $compile.$$addBindingClass(templateElement);
  20353. return function ngBindTemplateLink(scope, element, attr) {
  20354. var interpolateFn = $interpolate(element.attr(attr.$attr.ngBindTemplate));
  20355. $compile.$$addBindingInfo(element, interpolateFn.expressions);
  20356. element = element[0];
  20357. attr.$observe('ngBindTemplate', function(value) {
  20358. element.textContent = isUndefined(value) ? '' : value;
  20359. });
  20360. };
  20361. }
  20362. };
  20363. }];
  20364. /**
  20365. * @ngdoc directive
  20366. * @name ngBindHtml
  20367. *
  20368. * @description
  20369. * Evaluates the expression and inserts the resulting HTML into the element in a secure way. By default,
  20370. * the resulting HTML content will be sanitized using the {@link ngSanitize.$sanitize $sanitize} service.
  20371. * To utilize this functionality, ensure that `$sanitize` is available, for example, by including {@link
  20372. * ngSanitize} in your module's dependencies (not in core Angular). In order to use {@link ngSanitize}
  20373. * in your module's dependencies, you need to include "angular-sanitize.js" in your application.
  20374. *
  20375. * You may also bypass sanitization for values you know are safe. To do so, bind to
  20376. * an explicitly trusted value via {@link ng.$sce#trustAsHtml $sce.trustAsHtml}. See the example
  20377. * under {@link ng.$sce#show-me-an-example-using-sce- Strict Contextual Escaping (SCE)}.
  20378. *
  20379. * Note: If a `$sanitize` service is unavailable and the bound value isn't explicitly trusted, you
  20380. * will have an exception (instead of an exploit.)
  20381. *
  20382. * @element ANY
  20383. * @param {expression} ngBindHtml {@link guide/expression Expression} to evaluate.
  20384. *
  20385. * @example
  20386. <example module="bindHtmlExample" deps="angular-sanitize.js">
  20387. <file name="index.html">
  20388. <div ng-controller="ExampleController">
  20389. <p ng-bind-html="myHTML"></p>
  20390. </div>
  20391. </file>
  20392. <file name="script.js">
  20393. angular.module('bindHtmlExample', ['ngSanitize'])
  20394. .controller('ExampleController', ['$scope', function($scope) {
  20395. $scope.myHTML =
  20396. 'I am an <code>HTML</code>string with ' +
  20397. '<a href="#">links!</a> and other <em>stuff</em>';
  20398. }]);
  20399. </file>
  20400. <file name="protractor.js" type="protractor">
  20401. it('should check ng-bind-html', function() {
  20402. expect(element(by.binding('myHTML')).getText()).toBe(
  20403. 'I am an HTMLstring with links! and other stuff');
  20404. });
  20405. </file>
  20406. </example>
  20407. */
  20408. var ngBindHtmlDirective = ['$sce', '$parse', '$compile', function($sce, $parse, $compile) {
  20409. return {
  20410. restrict: 'A',
  20411. compile: function ngBindHtmlCompile(tElement, tAttrs) {
  20412. var ngBindHtmlGetter = $parse(tAttrs.ngBindHtml);
  20413. var ngBindHtmlWatch = $parse(tAttrs.ngBindHtml, function getStringValue(value) {
  20414. return (value || '').toString();
  20415. });
  20416. $compile.$$addBindingClass(tElement);
  20417. return function ngBindHtmlLink(scope, element, attr) {
  20418. $compile.$$addBindingInfo(element, attr.ngBindHtml);
  20419. scope.$watch(ngBindHtmlWatch, function ngBindHtmlWatchAction() {
  20420. // we re-evaluate the expr because we want a TrustedValueHolderType
  20421. // for $sce, not a string
  20422. element.html($sce.getTrustedHtml(ngBindHtmlGetter(scope)) || '');
  20423. });
  20424. };
  20425. }
  20426. };
  20427. }];
  20428. /**
  20429. * @ngdoc directive
  20430. * @name ngChange
  20431. *
  20432. * @description
  20433. * Evaluate the given expression when the user changes the input.
  20434. * The expression is evaluated immediately, unlike the JavaScript onchange event
  20435. * which only triggers at the end of a change (usually, when the user leaves the
  20436. * form element or presses the return key).
  20437. *
  20438. * The `ngChange` expression is only evaluated when a change in the input value causes
  20439. * a new value to be committed to the model.
  20440. *
  20441. * It will not be evaluated:
  20442. * * if the value returned from the `$parsers` transformation pipeline has not changed
  20443. * * if the input has continued to be invalid since the model will stay `null`
  20444. * * if the model is changed programmatically and not by a change to the input value
  20445. *
  20446. *
  20447. * Note, this directive requires `ngModel` to be present.
  20448. *
  20449. * @element input
  20450. * @param {expression} ngChange {@link guide/expression Expression} to evaluate upon change
  20451. * in input value.
  20452. *
  20453. * @example
  20454. * <example name="ngChange-directive" module="changeExample">
  20455. * <file name="index.html">
  20456. * <script>
  20457. * angular.module('changeExample', [])
  20458. * .controller('ExampleController', ['$scope', function($scope) {
  20459. * $scope.counter = 0;
  20460. * $scope.change = function() {
  20461. * $scope.counter++;
  20462. * };
  20463. * }]);
  20464. * </script>
  20465. * <div ng-controller="ExampleController">
  20466. * <input type="checkbox" ng-model="confirmed" ng-change="change()" id="ng-change-example1" />
  20467. * <input type="checkbox" ng-model="confirmed" id="ng-change-example2" />
  20468. * <label for="ng-change-example2">Confirmed</label><br />
  20469. * <tt>debug = {{confirmed}}</tt><br/>
  20470. * <tt>counter = {{counter}}</tt><br/>
  20471. * </div>
  20472. * </file>
  20473. * <file name="protractor.js" type="protractor">
  20474. * var counter = element(by.binding('counter'));
  20475. * var debug = element(by.binding('confirmed'));
  20476. *
  20477. * it('should evaluate the expression if changing from view', function() {
  20478. * expect(counter.getText()).toContain('0');
  20479. *
  20480. * element(by.id('ng-change-example1')).click();
  20481. *
  20482. * expect(counter.getText()).toContain('1');
  20483. * expect(debug.getText()).toContain('true');
  20484. * });
  20485. *
  20486. * it('should not evaluate the expression if changing from model', function() {
  20487. * element(by.id('ng-change-example2')).click();
  20488. * expect(counter.getText()).toContain('0');
  20489. * expect(debug.getText()).toContain('true');
  20490. * });
  20491. * </file>
  20492. * </example>
  20493. */
  20494. var ngChangeDirective = valueFn({
  20495. restrict: 'A',
  20496. require: 'ngModel',
  20497. link: function(scope, element, attr, ctrl) {
  20498. ctrl.$viewChangeListeners.push(function() {
  20499. scope.$eval(attr.ngChange);
  20500. });
  20501. }
  20502. });
  20503. function classDirective(name, selector) {
  20504. name = 'ngClass' + name;
  20505. return ['$animate', function($animate) {
  20506. return {
  20507. restrict: 'AC',
  20508. link: function(scope, element, attr) {
  20509. var oldVal;
  20510. scope.$watch(attr[name], ngClassWatchAction, true);
  20511. attr.$observe('class', function(value) {
  20512. ngClassWatchAction(scope.$eval(attr[name]));
  20513. });
  20514. if (name !== 'ngClass') {
  20515. scope.$watch('$index', function($index, old$index) {
  20516. // jshint bitwise: false
  20517. var mod = $index & 1;
  20518. if (mod !== (old$index & 1)) {
  20519. var classes = arrayClasses(scope.$eval(attr[name]));
  20520. mod === selector ?
  20521. addClasses(classes) :
  20522. removeClasses(classes);
  20523. }
  20524. });
  20525. }
  20526. function addClasses(classes) {
  20527. var newClasses = digestClassCounts(classes, 1);
  20528. attr.$addClass(newClasses);
  20529. }
  20530. function removeClasses(classes) {
  20531. var newClasses = digestClassCounts(classes, -1);
  20532. attr.$removeClass(newClasses);
  20533. }
  20534. function digestClassCounts(classes, count) {
  20535. // Use createMap() to prevent class assumptions involving property
  20536. // names in Object.prototype
  20537. var classCounts = element.data('$classCounts') || createMap();
  20538. var classesToUpdate = [];
  20539. forEach(classes, function(className) {
  20540. if (count > 0 || classCounts[className]) {
  20541. classCounts[className] = (classCounts[className] || 0) + count;
  20542. if (classCounts[className] === +(count > 0)) {
  20543. classesToUpdate.push(className);
  20544. }
  20545. }
  20546. });
  20547. element.data('$classCounts', classCounts);
  20548. return classesToUpdate.join(' ');
  20549. }
  20550. function updateClasses(oldClasses, newClasses) {
  20551. var toAdd = arrayDifference(newClasses, oldClasses);
  20552. var toRemove = arrayDifference(oldClasses, newClasses);
  20553. toAdd = digestClassCounts(toAdd, 1);
  20554. toRemove = digestClassCounts(toRemove, -1);
  20555. if (toAdd && toAdd.length) {
  20556. $animate.addClass(element, toAdd);
  20557. }
  20558. if (toRemove && toRemove.length) {
  20559. $animate.removeClass(element, toRemove);
  20560. }
  20561. }
  20562. function ngClassWatchAction(newVal) {
  20563. if (selector === true || scope.$index % 2 === selector) {
  20564. var newClasses = arrayClasses(newVal || []);
  20565. if (!oldVal) {
  20566. addClasses(newClasses);
  20567. } else if (!equals(newVal,oldVal)) {
  20568. var oldClasses = arrayClasses(oldVal);
  20569. updateClasses(oldClasses, newClasses);
  20570. }
  20571. }
  20572. oldVal = shallowCopy(newVal);
  20573. }
  20574. }
  20575. };
  20576. function arrayDifference(tokens1, tokens2) {
  20577. var values = [];
  20578. outer:
  20579. for (var i = 0; i < tokens1.length; i++) {
  20580. var token = tokens1[i];
  20581. for (var j = 0; j < tokens2.length; j++) {
  20582. if (token == tokens2[j]) continue outer;
  20583. }
  20584. values.push(token);
  20585. }
  20586. return values;
  20587. }
  20588. function arrayClasses(classVal) {
  20589. var classes = [];
  20590. if (isArray(classVal)) {
  20591. forEach(classVal, function(v) {
  20592. classes = classes.concat(arrayClasses(v));
  20593. });
  20594. return classes;
  20595. } else if (isString(classVal)) {
  20596. return classVal.split(' ');
  20597. } else if (isObject(classVal)) {
  20598. forEach(classVal, function(v, k) {
  20599. if (v) {
  20600. classes = classes.concat(k.split(' '));
  20601. }
  20602. });
  20603. return classes;
  20604. }
  20605. return classVal;
  20606. }
  20607. }];
  20608. }
  20609. /**
  20610. * @ngdoc directive
  20611. * @name ngClass
  20612. * @restrict AC
  20613. *
  20614. * @description
  20615. * The `ngClass` directive allows you to dynamically set CSS classes on an HTML element by databinding
  20616. * an expression that represents all classes to be added.
  20617. *
  20618. * The directive operates in three different ways, depending on which of three types the expression
  20619. * evaluates to:
  20620. *
  20621. * 1. If the expression evaluates to a string, the string should be one or more space-delimited class
  20622. * names.
  20623. *
  20624. * 2. If the expression evaluates to an object, then for each key-value pair of the
  20625. * object with a truthy value the corresponding key is used as a class name.
  20626. *
  20627. * 3. If the expression evaluates to an array, each element of the array should either be a string as in
  20628. * type 1 or an object as in type 2. This means that you can mix strings and objects together in an array
  20629. * to give you more control over what CSS classes appear. See the code below for an example of this.
  20630. *
  20631. *
  20632. * The directive won't add duplicate classes if a particular class was already set.
  20633. *
  20634. * When the expression changes, the previously added classes are removed and only then are the
  20635. * new classes added.
  20636. *
  20637. * @animations
  20638. * **add** - happens just before the class is applied to the elements
  20639. *
  20640. * **remove** - happens just before the class is removed from the element
  20641. *
  20642. * @element ANY
  20643. * @param {expression} ngClass {@link guide/expression Expression} to eval. The result
  20644. * of the evaluation can be a string representing space delimited class
  20645. * names, an array, or a map of class names to boolean values. In the case of a map, the
  20646. * names of the properties whose values are truthy will be added as css classes to the
  20647. * element.
  20648. *
  20649. * @example Example that demonstrates basic bindings via ngClass directive.
  20650. <example>
  20651. <file name="index.html">
  20652. <p ng-class="{strike: deleted, bold: important, 'has-error': error}">Map Syntax Example</p>
  20653. <label>
  20654. <input type="checkbox" ng-model="deleted">
  20655. deleted (apply "strike" class)
  20656. </label><br>
  20657. <label>
  20658. <input type="checkbox" ng-model="important">
  20659. important (apply "bold" class)
  20660. </label><br>
  20661. <label>
  20662. <input type="checkbox" ng-model="error">
  20663. error (apply "has-error" class)
  20664. </label>
  20665. <hr>
  20666. <p ng-class="style">Using String Syntax</p>
  20667. <input type="text" ng-model="style"
  20668. placeholder="Type: bold strike red" aria-label="Type: bold strike red">
  20669. <hr>
  20670. <p ng-class="[style1, style2, style3]">Using Array Syntax</p>
  20671. <input ng-model="style1"
  20672. placeholder="Type: bold, strike or red" aria-label="Type: bold, strike or red"><br>
  20673. <input ng-model="style2"
  20674. placeholder="Type: bold, strike or red" aria-label="Type: bold, strike or red 2"><br>
  20675. <input ng-model="style3"
  20676. placeholder="Type: bold, strike or red" aria-label="Type: bold, strike or red 3"><br>
  20677. <hr>
  20678. <p ng-class="[style4, {orange: warning}]">Using Array and Map Syntax</p>
  20679. <input ng-model="style4" placeholder="Type: bold, strike" aria-label="Type: bold, strike"><br>
  20680. <label><input type="checkbox" ng-model="warning"> warning (apply "orange" class)</label>
  20681. </file>
  20682. <file name="style.css">
  20683. .strike {
  20684. text-decoration: line-through;
  20685. }
  20686. .bold {
  20687. font-weight: bold;
  20688. }
  20689. .red {
  20690. color: red;
  20691. }
  20692. .has-error {
  20693. color: red;
  20694. background-color: yellow;
  20695. }
  20696. .orange {
  20697. color: orange;
  20698. }
  20699. </file>
  20700. <file name="protractor.js" type="protractor">
  20701. var ps = element.all(by.css('p'));
  20702. it('should let you toggle the class', function() {
  20703. expect(ps.first().getAttribute('class')).not.toMatch(/bold/);
  20704. expect(ps.first().getAttribute('class')).not.toMatch(/has-error/);
  20705. element(by.model('important')).click();
  20706. expect(ps.first().getAttribute('class')).toMatch(/bold/);
  20707. element(by.model('error')).click();
  20708. expect(ps.first().getAttribute('class')).toMatch(/has-error/);
  20709. });
  20710. it('should let you toggle string example', function() {
  20711. expect(ps.get(1).getAttribute('class')).toBe('');
  20712. element(by.model('style')).clear();
  20713. element(by.model('style')).sendKeys('red');
  20714. expect(ps.get(1).getAttribute('class')).toBe('red');
  20715. });
  20716. it('array example should have 3 classes', function() {
  20717. expect(ps.get(2).getAttribute('class')).toBe('');
  20718. element(by.model('style1')).sendKeys('bold');
  20719. element(by.model('style2')).sendKeys('strike');
  20720. element(by.model('style3')).sendKeys('red');
  20721. expect(ps.get(2).getAttribute('class')).toBe('bold strike red');
  20722. });
  20723. it('array with map example should have 2 classes', function() {
  20724. expect(ps.last().getAttribute('class')).toBe('');
  20725. element(by.model('style4')).sendKeys('bold');
  20726. element(by.model('warning')).click();
  20727. expect(ps.last().getAttribute('class')).toBe('bold orange');
  20728. });
  20729. </file>
  20730. </example>
  20731. ## Animations
  20732. The example below demonstrates how to perform animations using ngClass.
  20733. <example module="ngAnimate" deps="angular-animate.js" animations="true">
  20734. <file name="index.html">
  20735. <input id="setbtn" type="button" value="set" ng-click="myVar='my-class'">
  20736. <input id="clearbtn" type="button" value="clear" ng-click="myVar=''">
  20737. <br>
  20738. <span class="base-class" ng-class="myVar">Sample Text</span>
  20739. </file>
  20740. <file name="style.css">
  20741. .base-class {
  20742. transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
  20743. }
  20744. .base-class.my-class {
  20745. color: red;
  20746. font-size:3em;
  20747. }
  20748. </file>
  20749. <file name="protractor.js" type="protractor">
  20750. it('should check ng-class', function() {
  20751. expect(element(by.css('.base-class')).getAttribute('class')).not.
  20752. toMatch(/my-class/);
  20753. element(by.id('setbtn')).click();
  20754. expect(element(by.css('.base-class')).getAttribute('class')).
  20755. toMatch(/my-class/);
  20756. element(by.id('clearbtn')).click();
  20757. expect(element(by.css('.base-class')).getAttribute('class')).not.
  20758. toMatch(/my-class/);
  20759. });
  20760. </file>
  20761. </example>
  20762. ## ngClass and pre-existing CSS3 Transitions/Animations
  20763. The ngClass directive still supports CSS3 Transitions/Animations even if they do not follow the ngAnimate CSS naming structure.
  20764. Upon animation ngAnimate will apply supplementary CSS classes to track the start and end of an animation, but this will not hinder
  20765. any pre-existing CSS transitions already on the element. To get an idea of what happens during a class-based animation, be sure
  20766. to view the step by step details of {@link $animate#addClass $animate.addClass} and
  20767. {@link $animate#removeClass $animate.removeClass}.
  20768. */
  20769. var ngClassDirective = classDirective('', true);
  20770. /**
  20771. * @ngdoc directive
  20772. * @name ngClassOdd
  20773. * @restrict AC
  20774. *
  20775. * @description
  20776. * The `ngClassOdd` and `ngClassEven` directives work exactly as
  20777. * {@link ng.directive:ngClass ngClass}, except they work in
  20778. * conjunction with `ngRepeat` and take effect only on odd (even) rows.
  20779. *
  20780. * This directive can be applied only within the scope of an
  20781. * {@link ng.directive:ngRepeat ngRepeat}.
  20782. *
  20783. * @element ANY
  20784. * @param {expression} ngClassOdd {@link guide/expression Expression} to eval. The result
  20785. * of the evaluation can be a string representing space delimited class names or an array.
  20786. *
  20787. * @example
  20788. <example>
  20789. <file name="index.html">
  20790. <ol ng-init="names=['John', 'Mary', 'Cate', 'Suz']">
  20791. <li ng-repeat="name in names">
  20792. <span ng-class-odd="'odd'" ng-class-even="'even'">
  20793. {{name}}
  20794. </span>
  20795. </li>
  20796. </ol>
  20797. </file>
  20798. <file name="style.css">
  20799. .odd {
  20800. color: red;
  20801. }
  20802. .even {
  20803. color: blue;
  20804. }
  20805. </file>
  20806. <file name="protractor.js" type="protractor">
  20807. it('should check ng-class-odd and ng-class-even', function() {
  20808. expect(element(by.repeater('name in names').row(0).column('name')).getAttribute('class')).
  20809. toMatch(/odd/);
  20810. expect(element(by.repeater('name in names').row(1).column('name')).getAttribute('class')).
  20811. toMatch(/even/);
  20812. });
  20813. </file>
  20814. </example>
  20815. */
  20816. var ngClassOddDirective = classDirective('Odd', 0);
  20817. /**
  20818. * @ngdoc directive
  20819. * @name ngClassEven
  20820. * @restrict AC
  20821. *
  20822. * @description
  20823. * The `ngClassOdd` and `ngClassEven` directives work exactly as
  20824. * {@link ng.directive:ngClass ngClass}, except they work in
  20825. * conjunction with `ngRepeat` and take effect only on odd (even) rows.
  20826. *
  20827. * This directive can be applied only within the scope of an
  20828. * {@link ng.directive:ngRepeat ngRepeat}.
  20829. *
  20830. * @element ANY
  20831. * @param {expression} ngClassEven {@link guide/expression Expression} to eval. The
  20832. * result of the evaluation can be a string representing space delimited class names or an array.
  20833. *
  20834. * @example
  20835. <example>
  20836. <file name="index.html">
  20837. <ol ng-init="names=['John', 'Mary', 'Cate', 'Suz']">
  20838. <li ng-repeat="name in names">
  20839. <span ng-class-odd="'odd'" ng-class-even="'even'">
  20840. {{name}} &nbsp; &nbsp; &nbsp;
  20841. </span>
  20842. </li>
  20843. </ol>
  20844. </file>
  20845. <file name="style.css">
  20846. .odd {
  20847. color: red;
  20848. }
  20849. .even {
  20850. color: blue;
  20851. }
  20852. </file>
  20853. <file name="protractor.js" type="protractor">
  20854. it('should check ng-class-odd and ng-class-even', function() {
  20855. expect(element(by.repeater('name in names').row(0).column('name')).getAttribute('class')).
  20856. toMatch(/odd/);
  20857. expect(element(by.repeater('name in names').row(1).column('name')).getAttribute('class')).
  20858. toMatch(/even/);
  20859. });
  20860. </file>
  20861. </example>
  20862. */
  20863. var ngClassEvenDirective = classDirective('Even', 1);
  20864. /**
  20865. * @ngdoc directive
  20866. * @name ngCloak
  20867. * @restrict AC
  20868. *
  20869. * @description
  20870. * The `ngCloak` directive is used to prevent the Angular html template from being briefly
  20871. * displayed by the browser in its raw (uncompiled) form while your application is loading. Use this
  20872. * directive to avoid the undesirable flicker effect caused by the html template display.
  20873. *
  20874. * The directive can be applied to the `<body>` element, but the preferred usage is to apply
  20875. * multiple `ngCloak` directives to small portions of the page to permit progressive rendering
  20876. * of the browser view.
  20877. *
  20878. * `ngCloak` works in cooperation with the following css rule embedded within `angular.js` and
  20879. * `angular.min.js`.
  20880. * For CSP mode please add `angular-csp.css` to your html file (see {@link ng.directive:ngCsp ngCsp}).
  20881. *
  20882. * ```css
  20883. * [ng\:cloak], [ng-cloak], [data-ng-cloak], [x-ng-cloak], .ng-cloak, .x-ng-cloak {
  20884. * display: none !important;
  20885. * }
  20886. * ```
  20887. *
  20888. * When this css rule is loaded by the browser, all html elements (including their children) that
  20889. * are tagged with the `ngCloak` directive are hidden. When Angular encounters this directive
  20890. * during the compilation of the template it deletes the `ngCloak` element attribute, making
  20891. * the compiled element visible.
  20892. *
  20893. * For the best result, the `angular.js` script must be loaded in the head section of the html
  20894. * document; alternatively, the css rule above must be included in the external stylesheet of the
  20895. * application.
  20896. *
  20897. * @element ANY
  20898. *
  20899. * @example
  20900. <example>
  20901. <file name="index.html">
  20902. <div id="template1" ng-cloak>{{ 'hello' }}</div>
  20903. <div id="template2" class="ng-cloak">{{ 'world' }}</div>
  20904. </file>
  20905. <file name="protractor.js" type="protractor">
  20906. it('should remove the template directive and css class', function() {
  20907. expect($('#template1').getAttribute('ng-cloak')).
  20908. toBeNull();
  20909. expect($('#template2').getAttribute('ng-cloak')).
  20910. toBeNull();
  20911. });
  20912. </file>
  20913. </example>
  20914. *
  20915. */
  20916. var ngCloakDirective = ngDirective({
  20917. compile: function(element, attr) {
  20918. attr.$set('ngCloak', undefined);
  20919. element.removeClass('ng-cloak');
  20920. }
  20921. });
  20922. /**
  20923. * @ngdoc directive
  20924. * @name ngController
  20925. *
  20926. * @description
  20927. * The `ngController` directive attaches a controller class to the view. This is a key aspect of how angular
  20928. * supports the principles behind the Model-View-Controller design pattern.
  20929. *
  20930. * MVC components in angular:
  20931. *
  20932. * * Model — Models are the properties of a scope; scopes are attached to the DOM where scope properties
  20933. * are accessed through bindings.
  20934. * * View — The template (HTML with data bindings) that is rendered into the View.
  20935. * * Controller — The `ngController` directive specifies a Controller class; the class contains business
  20936. * logic behind the application to decorate the scope with functions and values
  20937. *
  20938. * Note that you can also attach controllers to the DOM by declaring it in a route definition
  20939. * via the {@link ngRoute.$route $route} service. A common mistake is to declare the controller
  20940. * again using `ng-controller` in the template itself. This will cause the controller to be attached
  20941. * and executed twice.
  20942. *
  20943. * @element ANY
  20944. * @scope
  20945. * @priority 500
  20946. * @param {expression} ngController Name of a constructor function registered with the current
  20947. * {@link ng.$controllerProvider $controllerProvider} or an {@link guide/expression expression}
  20948. * that on the current scope evaluates to a constructor function.
  20949. *
  20950. * The controller instance can be published into a scope property by specifying
  20951. * `ng-controller="as propertyName"`.
  20952. *
  20953. * If the current `$controllerProvider` is configured to use globals (via
  20954. * {@link ng.$controllerProvider#allowGlobals `$controllerProvider.allowGlobals()` }), this may
  20955. * also be the name of a globally accessible constructor function (not recommended).
  20956. *
  20957. * @example
  20958. * Here is a simple form for editing user contact information. Adding, removing, clearing, and
  20959. * greeting are methods declared on the controller (see source tab). These methods can
  20960. * easily be called from the angular markup. Any changes to the data are automatically reflected
  20961. * in the View without the need for a manual update.
  20962. *
  20963. * Two different declaration styles are included below:
  20964. *
  20965. * * one binds methods and properties directly onto the controller using `this`:
  20966. * `ng-controller="SettingsController1 as settings"`
  20967. * * one injects `$scope` into the controller:
  20968. * `ng-controller="SettingsController2"`
  20969. *
  20970. * The second option is more common in the Angular community, and is generally used in boilerplates
  20971. * and in this guide. However, there are advantages to binding properties directly to the controller
  20972. * and avoiding scope.
  20973. *
  20974. * * Using `controller as` makes it obvious which controller you are accessing in the template when
  20975. * multiple controllers apply to an element.
  20976. * * If you are writing your controllers as classes you have easier access to the properties and
  20977. * methods, which will appear on the scope, from inside the controller code.
  20978. * * Since there is always a `.` in the bindings, you don't have to worry about prototypal
  20979. * inheritance masking primitives.
  20980. *
  20981. * This example demonstrates the `controller as` syntax.
  20982. *
  20983. * <example name="ngControllerAs" module="controllerAsExample">
  20984. * <file name="index.html">
  20985. * <div id="ctrl-as-exmpl" ng-controller="SettingsController1 as settings">
  20986. * <label>Name: <input type="text" ng-model="settings.name"/></label>
  20987. * <button ng-click="settings.greet()">greet</button><br/>
  20988. * Contact:
  20989. * <ul>
  20990. * <li ng-repeat="contact in settings.contacts">
  20991. * <select ng-model="contact.type" aria-label="Contact method" id="select_{{$index}}">
  20992. * <option>phone</option>
  20993. * <option>email</option>
  20994. * </select>
  20995. * <input type="text" ng-model="contact.value" aria-labelledby="select_{{$index}}" />
  20996. * <button ng-click="settings.clearContact(contact)">clear</button>
  20997. * <button ng-click="settings.removeContact(contact)" aria-label="Remove">X</button>
  20998. * </li>
  20999. * <li><button ng-click="settings.addContact()">add</button></li>
  21000. * </ul>
  21001. * </div>
  21002. * </file>
  21003. * <file name="app.js">
  21004. * angular.module('controllerAsExample', [])
  21005. * .controller('SettingsController1', SettingsController1);
  21006. *
  21007. * function SettingsController1() {
  21008. * this.name = "John Smith";
  21009. * this.contacts = [
  21010. * {type: 'phone', value: '408 555 1212'},
  21011. * {type: 'email', value: 'john.smith@example.org'} ];
  21012. * }
  21013. *
  21014. * SettingsController1.prototype.greet = function() {
  21015. * alert(this.name);
  21016. * };
  21017. *
  21018. * SettingsController1.prototype.addContact = function() {
  21019. * this.contacts.push({type: 'email', value: 'yourname@example.org'});
  21020. * };
  21021. *
  21022. * SettingsController1.prototype.removeContact = function(contactToRemove) {
  21023. * var index = this.contacts.indexOf(contactToRemove);
  21024. * this.contacts.splice(index, 1);
  21025. * };
  21026. *
  21027. * SettingsController1.prototype.clearContact = function(contact) {
  21028. * contact.type = 'phone';
  21029. * contact.value = '';
  21030. * };
  21031. * </file>
  21032. * <file name="protractor.js" type="protractor">
  21033. * it('should check controller as', function() {
  21034. * var container = element(by.id('ctrl-as-exmpl'));
  21035. * expect(container.element(by.model('settings.name'))
  21036. * .getAttribute('value')).toBe('John Smith');
  21037. *
  21038. * var firstRepeat =
  21039. * container.element(by.repeater('contact in settings.contacts').row(0));
  21040. * var secondRepeat =
  21041. * container.element(by.repeater('contact in settings.contacts').row(1));
  21042. *
  21043. * expect(firstRepeat.element(by.model('contact.value')).getAttribute('value'))
  21044. * .toBe('408 555 1212');
  21045. *
  21046. * expect(secondRepeat.element(by.model('contact.value')).getAttribute('value'))
  21047. * .toBe('john.smith@example.org');
  21048. *
  21049. * firstRepeat.element(by.buttonText('clear')).click();
  21050. *
  21051. * expect(firstRepeat.element(by.model('contact.value')).getAttribute('value'))
  21052. * .toBe('');
  21053. *
  21054. * container.element(by.buttonText('add')).click();
  21055. *
  21056. * expect(container.element(by.repeater('contact in settings.contacts').row(2))
  21057. * .element(by.model('contact.value'))
  21058. * .getAttribute('value'))
  21059. * .toBe('yourname@example.org');
  21060. * });
  21061. * </file>
  21062. * </example>
  21063. *
  21064. * This example demonstrates the "attach to `$scope`" style of controller.
  21065. *
  21066. * <example name="ngController" module="controllerExample">
  21067. * <file name="index.html">
  21068. * <div id="ctrl-exmpl" ng-controller="SettingsController2">
  21069. * <label>Name: <input type="text" ng-model="name"/></label>
  21070. * <button ng-click="greet()">greet</button><br/>
  21071. * Contact:
  21072. * <ul>
  21073. * <li ng-repeat="contact in contacts">
  21074. * <select ng-model="contact.type" id="select_{{$index}}">
  21075. * <option>phone</option>
  21076. * <option>email</option>
  21077. * </select>
  21078. * <input type="text" ng-model="contact.value" aria-labelledby="select_{{$index}}" />
  21079. * <button ng-click="clearContact(contact)">clear</button>
  21080. * <button ng-click="removeContact(contact)">X</button>
  21081. * </li>
  21082. * <li>[ <button ng-click="addContact()">add</button> ]</li>
  21083. * </ul>
  21084. * </div>
  21085. * </file>
  21086. * <file name="app.js">
  21087. * angular.module('controllerExample', [])
  21088. * .controller('SettingsController2', ['$scope', SettingsController2]);
  21089. *
  21090. * function SettingsController2($scope) {
  21091. * $scope.name = "John Smith";
  21092. * $scope.contacts = [
  21093. * {type:'phone', value:'408 555 1212'},
  21094. * {type:'email', value:'john.smith@example.org'} ];
  21095. *
  21096. * $scope.greet = function() {
  21097. * alert($scope.name);
  21098. * };
  21099. *
  21100. * $scope.addContact = function() {
  21101. * $scope.contacts.push({type:'email', value:'yourname@example.org'});
  21102. * };
  21103. *
  21104. * $scope.removeContact = function(contactToRemove) {
  21105. * var index = $scope.contacts.indexOf(contactToRemove);
  21106. * $scope.contacts.splice(index, 1);
  21107. * };
  21108. *
  21109. * $scope.clearContact = function(contact) {
  21110. * contact.type = 'phone';
  21111. * contact.value = '';
  21112. * };
  21113. * }
  21114. * </file>
  21115. * <file name="protractor.js" type="protractor">
  21116. * it('should check controller', function() {
  21117. * var container = element(by.id('ctrl-exmpl'));
  21118. *
  21119. * expect(container.element(by.model('name'))
  21120. * .getAttribute('value')).toBe('John Smith');
  21121. *
  21122. * var firstRepeat =
  21123. * container.element(by.repeater('contact in contacts').row(0));
  21124. * var secondRepeat =
  21125. * container.element(by.repeater('contact in contacts').row(1));
  21126. *
  21127. * expect(firstRepeat.element(by.model('contact.value')).getAttribute('value'))
  21128. * .toBe('408 555 1212');
  21129. * expect(secondRepeat.element(by.model('contact.value')).getAttribute('value'))
  21130. * .toBe('john.smith@example.org');
  21131. *
  21132. * firstRepeat.element(by.buttonText('clear')).click();
  21133. *
  21134. * expect(firstRepeat.element(by.model('contact.value')).getAttribute('value'))
  21135. * .toBe('');
  21136. *
  21137. * container.element(by.buttonText('add')).click();
  21138. *
  21139. * expect(container.element(by.repeater('contact in contacts').row(2))
  21140. * .element(by.model('contact.value'))
  21141. * .getAttribute('value'))
  21142. * .toBe('yourname@example.org');
  21143. * });
  21144. * </file>
  21145. *</example>
  21146. */
  21147. var ngControllerDirective = [function() {
  21148. return {
  21149. restrict: 'A',
  21150. scope: true,
  21151. controller: '@',
  21152. priority: 500
  21153. };
  21154. }];
  21155. /**
  21156. * @ngdoc directive
  21157. * @name ngCsp
  21158. *
  21159. * @element html
  21160. * @description
  21161. *
  21162. * Angular has some features that can break certain
  21163. * [CSP (Content Security Policy)](https://developer.mozilla.org/en/Security/CSP) rules.
  21164. *
  21165. * If you intend to implement these rules then you must tell Angular not to use these features.
  21166. *
  21167. * This is necessary when developing things like Google Chrome Extensions or Universal Windows Apps.
  21168. *
  21169. *
  21170. * The following rules affect Angular:
  21171. *
  21172. * * `unsafe-eval`: this rule forbids apps to use `eval` or `Function(string)` generated functions
  21173. * (among other things). Angular makes use of this in the {@link $parse} service to provide a 30%
  21174. * increase in the speed of evaluating Angular expressions.
  21175. *
  21176. * * `unsafe-inline`: this rule forbids apps from inject custom styles into the document. Angular
  21177. * makes use of this to include some CSS rules (e.g. {@link ngCloak} and {@link ngHide}).
  21178. * To make these directives work when a CSP rule is blocking inline styles, you must link to the
  21179. * `angular-csp.css` in your HTML manually.
  21180. *
  21181. * If you do not provide `ngCsp` then Angular tries to autodetect if CSP is blocking unsafe-eval
  21182. * and automatically deactivates this feature in the {@link $parse} service. This autodetection,
  21183. * however, triggers a CSP error to be logged in the console:
  21184. *
  21185. * ```
  21186. * Refused to evaluate a string as JavaScript because 'unsafe-eval' is not an allowed source of
  21187. * script in the following Content Security Policy directive: "default-src 'self'". Note that
  21188. * 'script-src' was not explicitly set, so 'default-src' is used as a fallback.
  21189. * ```
  21190. *
  21191. * This error is harmless but annoying. To prevent the error from showing up, put the `ngCsp`
  21192. * directive on an element of the HTML document that appears before the `<script>` tag that loads
  21193. * the `angular.js` file.
  21194. *
  21195. * *Note: This directive is only available in the `ng-csp` and `data-ng-csp` attribute form.*
  21196. *
  21197. * You can specify which of the CSP related Angular features should be deactivated by providing
  21198. * a value for the `ng-csp` attribute. The options are as follows:
  21199. *
  21200. * * no-inline-style: this stops Angular from injecting CSS styles into the DOM
  21201. *
  21202. * * no-unsafe-eval: this stops Angular from optimising $parse with unsafe eval of strings
  21203. *
  21204. * You can use these values in the following combinations:
  21205. *
  21206. *
  21207. * * No declaration means that Angular will assume that you can do inline styles, but it will do
  21208. * a runtime check for unsafe-eval. E.g. `<body>`. This is backwardly compatible with previous versions
  21209. * of Angular.
  21210. *
  21211. * * A simple `ng-csp` (or `data-ng-csp`) attribute will tell Angular to deactivate both inline
  21212. * styles and unsafe eval. E.g. `<body ng-csp>`. This is backwardly compatible with previous versions
  21213. * of Angular.
  21214. *
  21215. * * Specifying only `no-unsafe-eval` tells Angular that we must not use eval, but that we can inject
  21216. * inline styles. E.g. `<body ng-csp="no-unsafe-eval">`.
  21217. *
  21218. * * Specifying only `no-inline-style` tells Angular that we must not inject styles, but that we can
  21219. * run eval - no automcatic check for unsafe eval will occur. E.g. `<body ng-csp="no-inline-style">`
  21220. *
  21221. * * Specifying both `no-unsafe-eval` and `no-inline-style` tells Angular that we must not inject
  21222. * styles nor use eval, which is the same as an empty: ng-csp.
  21223. * E.g.`<body ng-csp="no-inline-style;no-unsafe-eval">`
  21224. *
  21225. * @example
  21226. * This example shows how to apply the `ngCsp` directive to the `html` tag.
  21227. ```html
  21228. <!doctype html>
  21229. <html ng-app ng-csp>
  21230. ...
  21231. ...
  21232. </html>
  21233. ```
  21234. * @example
  21235. // Note: the suffix `.csp` in the example name triggers
  21236. // csp mode in our http server!
  21237. <example name="example.csp" module="cspExample" ng-csp="true">
  21238. <file name="index.html">
  21239. <div ng-controller="MainController as ctrl">
  21240. <div>
  21241. <button ng-click="ctrl.inc()" id="inc">Increment</button>
  21242. <span id="counter">
  21243. {{ctrl.counter}}
  21244. </span>
  21245. </div>
  21246. <div>
  21247. <button ng-click="ctrl.evil()" id="evil">Evil</button>
  21248. <span id="evilError">
  21249. {{ctrl.evilError}}
  21250. </span>
  21251. </div>
  21252. </div>
  21253. </file>
  21254. <file name="script.js">
  21255. angular.module('cspExample', [])
  21256. .controller('MainController', function() {
  21257. this.counter = 0;
  21258. this.inc = function() {
  21259. this.counter++;
  21260. };
  21261. this.evil = function() {
  21262. // jshint evil:true
  21263. try {
  21264. eval('1+2');
  21265. } catch (e) {
  21266. this.evilError = e.message;
  21267. }
  21268. };
  21269. });
  21270. </file>
  21271. <file name="protractor.js" type="protractor">
  21272. var util, webdriver;
  21273. var incBtn = element(by.id('inc'));
  21274. var counter = element(by.id('counter'));
  21275. var evilBtn = element(by.id('evil'));
  21276. var evilError = element(by.id('evilError'));
  21277. function getAndClearSevereErrors() {
  21278. return browser.manage().logs().get('browser').then(function(browserLog) {
  21279. return browserLog.filter(function(logEntry) {
  21280. return logEntry.level.value > webdriver.logging.Level.WARNING.value;
  21281. });
  21282. });
  21283. }
  21284. function clearErrors() {
  21285. getAndClearSevereErrors();
  21286. }
  21287. function expectNoErrors() {
  21288. getAndClearSevereErrors().then(function(filteredLog) {
  21289. expect(filteredLog.length).toEqual(0);
  21290. if (filteredLog.length) {
  21291. console.log('browser console errors: ' + util.inspect(filteredLog));
  21292. }
  21293. });
  21294. }
  21295. function expectError(regex) {
  21296. getAndClearSevereErrors().then(function(filteredLog) {
  21297. var found = false;
  21298. filteredLog.forEach(function(log) {
  21299. if (log.message.match(regex)) {
  21300. found = true;
  21301. }
  21302. });
  21303. if (!found) {
  21304. throw new Error('expected an error that matches ' + regex);
  21305. }
  21306. });
  21307. }
  21308. beforeEach(function() {
  21309. util = require('util');
  21310. webdriver = require('protractor/node_modules/selenium-webdriver');
  21311. });
  21312. // For now, we only test on Chrome,
  21313. // as Safari does not load the page with Protractor's injected scripts,
  21314. // and Firefox webdriver always disables content security policy (#6358)
  21315. if (browser.params.browser !== 'chrome') {
  21316. return;
  21317. }
  21318. it('should not report errors when the page is loaded', function() {
  21319. // clear errors so we are not dependent on previous tests
  21320. clearErrors();
  21321. // Need to reload the page as the page is already loaded when
  21322. // we come here
  21323. browser.driver.getCurrentUrl().then(function(url) {
  21324. browser.get(url);
  21325. });
  21326. expectNoErrors();
  21327. });
  21328. it('should evaluate expressions', function() {
  21329. expect(counter.getText()).toEqual('0');
  21330. incBtn.click();
  21331. expect(counter.getText()).toEqual('1');
  21332. expectNoErrors();
  21333. });
  21334. it('should throw and report an error when using "eval"', function() {
  21335. evilBtn.click();
  21336. expect(evilError.getText()).toMatch(/Content Security Policy/);
  21337. expectError(/Content Security Policy/);
  21338. });
  21339. </file>
  21340. </example>
  21341. */
  21342. // ngCsp is not implemented as a proper directive any more, because we need it be processed while we
  21343. // bootstrap the system (before $parse is instantiated), for this reason we just have
  21344. // the csp() fn that looks for the `ng-csp` attribute anywhere in the current doc
  21345. /**
  21346. * @ngdoc directive
  21347. * @name ngClick
  21348. *
  21349. * @description
  21350. * The ngClick directive allows you to specify custom behavior when
  21351. * an element is clicked.
  21352. *
  21353. * @element ANY
  21354. * @priority 0
  21355. * @param {expression} ngClick {@link guide/expression Expression} to evaluate upon
  21356. * click. ({@link guide/expression#-event- Event object is available as `$event`})
  21357. *
  21358. * @example
  21359. <example>
  21360. <file name="index.html">
  21361. <button ng-click="count = count + 1" ng-init="count=0">
  21362. Increment
  21363. </button>
  21364. <span>
  21365. count: {{count}}
  21366. </span>
  21367. </file>
  21368. <file name="protractor.js" type="protractor">
  21369. it('should check ng-click', function() {
  21370. expect(element(by.binding('count')).getText()).toMatch('0');
  21371. element(by.css('button')).click();
  21372. expect(element(by.binding('count')).getText()).toMatch('1');
  21373. });
  21374. </file>
  21375. </example>
  21376. */
  21377. /*
  21378. * A collection of directives that allows creation of custom event handlers that are defined as
  21379. * angular expressions and are compiled and executed within the current scope.
  21380. */
  21381. var ngEventDirectives = {};
  21382. // For events that might fire synchronously during DOM manipulation
  21383. // we need to execute their event handlers asynchronously using $evalAsync,
  21384. // so that they are not executed in an inconsistent state.
  21385. var forceAsyncEvents = {
  21386. 'blur': true,
  21387. 'focus': true
  21388. };
  21389. forEach(
  21390. 'click dblclick mousedown mouseup mouseover mouseout mousemove mouseenter mouseleave keydown keyup keypress submit focus blur copy cut paste'.split(' '),
  21391. function(eventName) {
  21392. var directiveName = directiveNormalize('ng-' + eventName);
  21393. ngEventDirectives[directiveName] = ['$parse', '$rootScope', function($parse, $rootScope) {
  21394. return {
  21395. restrict: 'A',
  21396. compile: function($element, attr) {
  21397. // We expose the powerful $event object on the scope that provides access to the Window,
  21398. // etc. that isn't protected by the fast paths in $parse. We explicitly request better
  21399. // checks at the cost of speed since event handler expressions are not executed as
  21400. // frequently as regular change detection.
  21401. var fn = $parse(attr[directiveName], /* interceptorFn */ null, /* expensiveChecks */ true);
  21402. return function ngEventHandler(scope, element) {
  21403. element.on(eventName, function(event) {
  21404. var callback = function() {
  21405. fn(scope, {$event:event});
  21406. };
  21407. if (forceAsyncEvents[eventName] && $rootScope.$$phase) {
  21408. scope.$evalAsync(callback);
  21409. } else {
  21410. scope.$apply(callback);
  21411. }
  21412. });
  21413. };
  21414. }
  21415. };
  21416. }];
  21417. }
  21418. );
  21419. /**
  21420. * @ngdoc directive
  21421. * @name ngDblclick
  21422. *
  21423. * @description
  21424. * The `ngDblclick` directive allows you to specify custom behavior on a dblclick event.
  21425. *
  21426. * @element ANY
  21427. * @priority 0
  21428. * @param {expression} ngDblclick {@link guide/expression Expression} to evaluate upon
  21429. * a dblclick. (The Event object is available as `$event`)
  21430. *
  21431. * @example
  21432. <example>
  21433. <file name="index.html">
  21434. <button ng-dblclick="count = count + 1" ng-init="count=0">
  21435. Increment (on double click)
  21436. </button>
  21437. count: {{count}}
  21438. </file>
  21439. </example>
  21440. */
  21441. /**
  21442. * @ngdoc directive
  21443. * @name ngMousedown
  21444. *
  21445. * @description
  21446. * The ngMousedown directive allows you to specify custom behavior on mousedown event.
  21447. *
  21448. * @element ANY
  21449. * @priority 0
  21450. * @param {expression} ngMousedown {@link guide/expression Expression} to evaluate upon
  21451. * mousedown. ({@link guide/expression#-event- Event object is available as `$event`})
  21452. *
  21453. * @example
  21454. <example>
  21455. <file name="index.html">
  21456. <button ng-mousedown="count = count + 1" ng-init="count=0">
  21457. Increment (on mouse down)
  21458. </button>
  21459. count: {{count}}
  21460. </file>
  21461. </example>
  21462. */
  21463. /**
  21464. * @ngdoc directive
  21465. * @name ngMouseup
  21466. *
  21467. * @description
  21468. * Specify custom behavior on mouseup event.
  21469. *
  21470. * @element ANY
  21471. * @priority 0
  21472. * @param {expression} ngMouseup {@link guide/expression Expression} to evaluate upon
  21473. * mouseup. ({@link guide/expression#-event- Event object is available as `$event`})
  21474. *
  21475. * @example
  21476. <example>
  21477. <file name="index.html">
  21478. <button ng-mouseup="count = count + 1" ng-init="count=0">
  21479. Increment (on mouse up)
  21480. </button>
  21481. count: {{count}}
  21482. </file>
  21483. </example>
  21484. */
  21485. /**
  21486. * @ngdoc directive
  21487. * @name ngMouseover
  21488. *
  21489. * @description
  21490. * Specify custom behavior on mouseover event.
  21491. *
  21492. * @element ANY
  21493. * @priority 0
  21494. * @param {expression} ngMouseover {@link guide/expression Expression} to evaluate upon
  21495. * mouseover. ({@link guide/expression#-event- Event object is available as `$event`})
  21496. *
  21497. * @example
  21498. <example>
  21499. <file name="index.html">
  21500. <button ng-mouseover="count = count + 1" ng-init="count=0">
  21501. Increment (when mouse is over)
  21502. </button>
  21503. count: {{count}}
  21504. </file>
  21505. </example>
  21506. */
  21507. /**
  21508. * @ngdoc directive
  21509. * @name ngMouseenter
  21510. *
  21511. * @description
  21512. * Specify custom behavior on mouseenter event.
  21513. *
  21514. * @element ANY
  21515. * @priority 0
  21516. * @param {expression} ngMouseenter {@link guide/expression Expression} to evaluate upon
  21517. * mouseenter. ({@link guide/expression#-event- Event object is available as `$event`})
  21518. *
  21519. * @example
  21520. <example>
  21521. <file name="index.html">
  21522. <button ng-mouseenter="count = count + 1" ng-init="count=0">
  21523. Increment (when mouse enters)
  21524. </button>
  21525. count: {{count}}
  21526. </file>
  21527. </example>
  21528. */
  21529. /**
  21530. * @ngdoc directive
  21531. * @name ngMouseleave
  21532. *
  21533. * @description
  21534. * Specify custom behavior on mouseleave event.
  21535. *
  21536. * @element ANY
  21537. * @priority 0
  21538. * @param {expression} ngMouseleave {@link guide/expression Expression} to evaluate upon
  21539. * mouseleave. ({@link guide/expression#-event- Event object is available as `$event`})
  21540. *
  21541. * @example
  21542. <example>
  21543. <file name="index.html">
  21544. <button ng-mouseleave="count = count + 1" ng-init="count=0">
  21545. Increment (when mouse leaves)
  21546. </button>
  21547. count: {{count}}
  21548. </file>
  21549. </example>
  21550. */
  21551. /**
  21552. * @ngdoc directive
  21553. * @name ngMousemove
  21554. *
  21555. * @description
  21556. * Specify custom behavior on mousemove event.
  21557. *
  21558. * @element ANY
  21559. * @priority 0
  21560. * @param {expression} ngMousemove {@link guide/expression Expression} to evaluate upon
  21561. * mousemove. ({@link guide/expression#-event- Event object is available as `$event`})
  21562. *
  21563. * @example
  21564. <example>
  21565. <file name="index.html">
  21566. <button ng-mousemove="count = count + 1" ng-init="count=0">
  21567. Increment (when mouse moves)
  21568. </button>
  21569. count: {{count}}
  21570. </file>
  21571. </example>
  21572. */
  21573. /**
  21574. * @ngdoc directive
  21575. * @name ngKeydown
  21576. *
  21577. * @description
  21578. * Specify custom behavior on keydown event.
  21579. *
  21580. * @element ANY
  21581. * @priority 0
  21582. * @param {expression} ngKeydown {@link guide/expression Expression} to evaluate upon
  21583. * keydown. (Event object is available as `$event` and can be interrogated for keyCode, altKey, etc.)
  21584. *
  21585. * @example
  21586. <example>
  21587. <file name="index.html">
  21588. <input ng-keydown="count = count + 1" ng-init="count=0">
  21589. key down count: {{count}}
  21590. </file>
  21591. </example>
  21592. */
  21593. /**
  21594. * @ngdoc directive
  21595. * @name ngKeyup
  21596. *
  21597. * @description
  21598. * Specify custom behavior on keyup event.
  21599. *
  21600. * @element ANY
  21601. * @priority 0
  21602. * @param {expression} ngKeyup {@link guide/expression Expression} to evaluate upon
  21603. * keyup. (Event object is available as `$event` and can be interrogated for keyCode, altKey, etc.)
  21604. *
  21605. * @example
  21606. <example>
  21607. <file name="index.html">
  21608. <p>Typing in the input box below updates the key count</p>
  21609. <input ng-keyup="count = count + 1" ng-init="count=0"> key up count: {{count}}
  21610. <p>Typing in the input box below updates the keycode</p>
  21611. <input ng-keyup="event=$event">
  21612. <p>event keyCode: {{ event.keyCode }}</p>
  21613. <p>event altKey: {{ event.altKey }}</p>
  21614. </file>
  21615. </example>
  21616. */
  21617. /**
  21618. * @ngdoc directive
  21619. * @name ngKeypress
  21620. *
  21621. * @description
  21622. * Specify custom behavior on keypress event.
  21623. *
  21624. * @element ANY
  21625. * @param {expression} ngKeypress {@link guide/expression Expression} to evaluate upon
  21626. * keypress. ({@link guide/expression#-event- Event object is available as `$event`}
  21627. * and can be interrogated for keyCode, altKey, etc.)
  21628. *
  21629. * @example
  21630. <example>
  21631. <file name="index.html">
  21632. <input ng-keypress="count = count + 1" ng-init="count=0">
  21633. key press count: {{count}}
  21634. </file>
  21635. </example>
  21636. */
  21637. /**
  21638. * @ngdoc directive
  21639. * @name ngSubmit
  21640. *
  21641. * @description
  21642. * Enables binding angular expressions to onsubmit events.
  21643. *
  21644. * Additionally it prevents the default action (which for form means sending the request to the
  21645. * server and reloading the current page), but only if the form does not contain `action`,
  21646. * `data-action`, or `x-action` attributes.
  21647. *
  21648. * <div class="alert alert-warning">
  21649. * **Warning:** Be careful not to cause "double-submission" by using both the `ngClick` and
  21650. * `ngSubmit` handlers together. See the
  21651. * {@link form#submitting-a-form-and-preventing-the-default-action `form` directive documentation}
  21652. * for a detailed discussion of when `ngSubmit` may be triggered.
  21653. * </div>
  21654. *
  21655. * @element form
  21656. * @priority 0
  21657. * @param {expression} ngSubmit {@link guide/expression Expression} to eval.
  21658. * ({@link guide/expression#-event- Event object is available as `$event`})
  21659. *
  21660. * @example
  21661. <example module="submitExample">
  21662. <file name="index.html">
  21663. <script>
  21664. angular.module('submitExample', [])
  21665. .controller('ExampleController', ['$scope', function($scope) {
  21666. $scope.list = [];
  21667. $scope.text = 'hello';
  21668. $scope.submit = function() {
  21669. if ($scope.text) {
  21670. $scope.list.push(this.text);
  21671. $scope.text = '';
  21672. }
  21673. };
  21674. }]);
  21675. </script>
  21676. <form ng-submit="submit()" ng-controller="ExampleController">
  21677. Enter text and hit enter:
  21678. <input type="text" ng-model="text" name="text" />
  21679. <input type="submit" id="submit" value="Submit" />
  21680. <pre>list={{list}}</pre>
  21681. </form>
  21682. </file>
  21683. <file name="protractor.js" type="protractor">
  21684. it('should check ng-submit', function() {
  21685. expect(element(by.binding('list')).getText()).toBe('list=[]');
  21686. element(by.css('#submit')).click();
  21687. expect(element(by.binding('list')).getText()).toContain('hello');
  21688. expect(element(by.model('text')).getAttribute('value')).toBe('');
  21689. });
  21690. it('should ignore empty strings', function() {
  21691. expect(element(by.binding('list')).getText()).toBe('list=[]');
  21692. element(by.css('#submit')).click();
  21693. element(by.css('#submit')).click();
  21694. expect(element(by.binding('list')).getText()).toContain('hello');
  21695. });
  21696. </file>
  21697. </example>
  21698. */
  21699. /**
  21700. * @ngdoc directive
  21701. * @name ngFocus
  21702. *
  21703. * @description
  21704. * Specify custom behavior on focus event.
  21705. *
  21706. * Note: As the `focus` event is executed synchronously when calling `input.focus()`
  21707. * AngularJS executes the expression using `scope.$evalAsync` if the event is fired
  21708. * during an `$apply` to ensure a consistent state.
  21709. *
  21710. * @element window, input, select, textarea, a
  21711. * @priority 0
  21712. * @param {expression} ngFocus {@link guide/expression Expression} to evaluate upon
  21713. * focus. ({@link guide/expression#-event- Event object is available as `$event`})
  21714. *
  21715. * @example
  21716. * See {@link ng.directive:ngClick ngClick}
  21717. */
  21718. /**
  21719. * @ngdoc directive
  21720. * @name ngBlur
  21721. *
  21722. * @description
  21723. * Specify custom behavior on blur event.
  21724. *
  21725. * A [blur event](https://developer.mozilla.org/en-US/docs/Web/Events/blur) fires when
  21726. * an element has lost focus.
  21727. *
  21728. * Note: As the `blur` event is executed synchronously also during DOM manipulations
  21729. * (e.g. removing a focussed input),
  21730. * AngularJS executes the expression using `scope.$evalAsync` if the event is fired
  21731. * during an `$apply` to ensure a consistent state.
  21732. *
  21733. * @element window, input, select, textarea, a
  21734. * @priority 0
  21735. * @param {expression} ngBlur {@link guide/expression Expression} to evaluate upon
  21736. * blur. ({@link guide/expression#-event- Event object is available as `$event`})
  21737. *
  21738. * @example
  21739. * See {@link ng.directive:ngClick ngClick}
  21740. */
  21741. /**
  21742. * @ngdoc directive
  21743. * @name ngCopy
  21744. *
  21745. * @description
  21746. * Specify custom behavior on copy event.
  21747. *
  21748. * @element window, input, select, textarea, a
  21749. * @priority 0
  21750. * @param {expression} ngCopy {@link guide/expression Expression} to evaluate upon
  21751. * copy. ({@link guide/expression#-event- Event object is available as `$event`})
  21752. *
  21753. * @example
  21754. <example>
  21755. <file name="index.html">
  21756. <input ng-copy="copied=true" ng-init="copied=false; value='copy me'" ng-model="value">
  21757. copied: {{copied}}
  21758. </file>
  21759. </example>
  21760. */
  21761. /**
  21762. * @ngdoc directive
  21763. * @name ngCut
  21764. *
  21765. * @description
  21766. * Specify custom behavior on cut event.
  21767. *
  21768. * @element window, input, select, textarea, a
  21769. * @priority 0
  21770. * @param {expression} ngCut {@link guide/expression Expression} to evaluate upon
  21771. * cut. ({@link guide/expression#-event- Event object is available as `$event`})
  21772. *
  21773. * @example
  21774. <example>
  21775. <file name="index.html">
  21776. <input ng-cut="cut=true" ng-init="cut=false; value='cut me'" ng-model="value">
  21777. cut: {{cut}}
  21778. </file>
  21779. </example>
  21780. */
  21781. /**
  21782. * @ngdoc directive
  21783. * @name ngPaste
  21784. *
  21785. * @description
  21786. * Specify custom behavior on paste event.
  21787. *
  21788. * @element window, input, select, textarea, a
  21789. * @priority 0
  21790. * @param {expression} ngPaste {@link guide/expression Expression} to evaluate upon
  21791. * paste. ({@link guide/expression#-event- Event object is available as `$event`})
  21792. *
  21793. * @example
  21794. <example>
  21795. <file name="index.html">
  21796. <input ng-paste="paste=true" ng-init="paste=false" placeholder='paste here'>
  21797. pasted: {{paste}}
  21798. </file>
  21799. </example>
  21800. */
  21801. /**
  21802. * @ngdoc directive
  21803. * @name ngIf
  21804. * @restrict A
  21805. * @multiElement
  21806. *
  21807. * @description
  21808. * The `ngIf` directive removes or recreates a portion of the DOM tree based on an
  21809. * {expression}. If the expression assigned to `ngIf` evaluates to a false
  21810. * value then the element is removed from the DOM, otherwise a clone of the
  21811. * element is reinserted into the DOM.
  21812. *
  21813. * `ngIf` differs from `ngShow` and `ngHide` in that `ngIf` completely removes and recreates the
  21814. * element in the DOM rather than changing its visibility via the `display` css property. A common
  21815. * case when this difference is significant is when using css selectors that rely on an element's
  21816. * position within the DOM, such as the `:first-child` or `:last-child` pseudo-classes.
  21817. *
  21818. * Note that when an element is removed using `ngIf` its scope is destroyed and a new scope
  21819. * is created when the element is restored. The scope created within `ngIf` inherits from
  21820. * its parent scope using
  21821. * [prototypal inheritance](https://github.com/angular/angular.js/wiki/Understanding-Scopes#javascript-prototypal-inheritance).
  21822. * An important implication of this is if `ngModel` is used within `ngIf` to bind to
  21823. * a javascript primitive defined in the parent scope. In this case any modifications made to the
  21824. * variable within the child scope will override (hide) the value in the parent scope.
  21825. *
  21826. * Also, `ngIf` recreates elements using their compiled state. An example of this behavior
  21827. * is if an element's class attribute is directly modified after it's compiled, using something like
  21828. * jQuery's `.addClass()` method, and the element is later removed. When `ngIf` recreates the element
  21829. * the added class will be lost because the original compiled state is used to regenerate the element.
  21830. *
  21831. * Additionally, you can provide animations via the `ngAnimate` module to animate the `enter`
  21832. * and `leave` effects.
  21833. *
  21834. * @animations
  21835. * enter - happens just after the `ngIf` contents change and a new DOM element is created and injected into the `ngIf` container
  21836. * leave - happens just before the `ngIf` contents are removed from the DOM
  21837. *
  21838. * @element ANY
  21839. * @scope
  21840. * @priority 600
  21841. * @param {expression} ngIf If the {@link guide/expression expression} is falsy then
  21842. * the element is removed from the DOM tree. If it is truthy a copy of the compiled
  21843. * element is added to the DOM tree.
  21844. *
  21845. * @example
  21846. <example module="ngAnimate" deps="angular-animate.js" animations="true">
  21847. <file name="index.html">
  21848. <label>Click me: <input type="checkbox" ng-model="checked" ng-init="checked=true" /></label><br/>
  21849. Show when checked:
  21850. <span ng-if="checked" class="animate-if">
  21851. This is removed when the checkbox is unchecked.
  21852. </span>
  21853. </file>
  21854. <file name="animations.css">
  21855. .animate-if {
  21856. background:white;
  21857. border:1px solid black;
  21858. padding:10px;
  21859. }
  21860. .animate-if.ng-enter, .animate-if.ng-leave {
  21861. transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
  21862. }
  21863. .animate-if.ng-enter,
  21864. .animate-if.ng-leave.ng-leave-active {
  21865. opacity:0;
  21866. }
  21867. .animate-if.ng-leave,
  21868. .animate-if.ng-enter.ng-enter-active {
  21869. opacity:1;
  21870. }
  21871. </file>
  21872. </example>
  21873. */
  21874. var ngIfDirective = ['$animate', function($animate) {
  21875. return {
  21876. multiElement: true,
  21877. transclude: 'element',
  21878. priority: 600,
  21879. terminal: true,
  21880. restrict: 'A',
  21881. $$tlb: true,
  21882. link: function($scope, $element, $attr, ctrl, $transclude) {
  21883. var block, childScope, previousElements;
  21884. $scope.$watch($attr.ngIf, function ngIfWatchAction(value) {
  21885. if (value) {
  21886. if (!childScope) {
  21887. $transclude(function(clone, newScope) {
  21888. childScope = newScope;
  21889. clone[clone.length++] = document.createComment(' end ngIf: ' + $attr.ngIf + ' ');
  21890. // Note: We only need the first/last node of the cloned nodes.
  21891. // However, we need to keep the reference to the jqlite wrapper as it might be changed later
  21892. // by a directive with templateUrl when its template arrives.
  21893. block = {
  21894. clone: clone
  21895. };
  21896. $animate.enter(clone, $element.parent(), $element);
  21897. });
  21898. }
  21899. } else {
  21900. if (previousElements) {
  21901. previousElements.remove();
  21902. previousElements = null;
  21903. }
  21904. if (childScope) {
  21905. childScope.$destroy();
  21906. childScope = null;
  21907. }
  21908. if (block) {
  21909. previousElements = getBlockNodes(block.clone);
  21910. $animate.leave(previousElements).then(function() {
  21911. previousElements = null;
  21912. });
  21913. block = null;
  21914. }
  21915. }
  21916. });
  21917. }
  21918. };
  21919. }];
  21920. /**
  21921. * @ngdoc directive
  21922. * @name ngInclude
  21923. * @restrict ECA
  21924. *
  21925. * @description
  21926. * Fetches, compiles and includes an external HTML fragment.
  21927. *
  21928. * By default, the template URL is restricted to the same domain and protocol as the
  21929. * application document. This is done by calling {@link $sce#getTrustedResourceUrl
  21930. * $sce.getTrustedResourceUrl} on it. To load templates from other domains or protocols
  21931. * you may either {@link ng.$sceDelegateProvider#resourceUrlWhitelist whitelist them} or
  21932. * {@link $sce#trustAsResourceUrl wrap them} as trusted values. Refer to Angular's {@link
  21933. * ng.$sce Strict Contextual Escaping}.
  21934. *
  21935. * In addition, the browser's
  21936. * [Same Origin Policy](https://code.google.com/p/browsersec/wiki/Part2#Same-origin_policy_for_XMLHttpRequest)
  21937. * and [Cross-Origin Resource Sharing (CORS)](http://www.w3.org/TR/cors/)
  21938. * policy may further restrict whether the template is successfully loaded.
  21939. * For example, `ngInclude` won't work for cross-domain requests on all browsers and for `file://`
  21940. * access on some browsers.
  21941. *
  21942. * @animations
  21943. * enter - animation is used to bring new content into the browser.
  21944. * leave - animation is used to animate existing content away.
  21945. *
  21946. * The enter and leave animation occur concurrently.
  21947. *
  21948. * @scope
  21949. * @priority 400
  21950. *
  21951. * @param {string} ngInclude|src angular expression evaluating to URL. If the source is a string constant,
  21952. * make sure you wrap it in **single** quotes, e.g. `src="'myPartialTemplate.html'"`.
  21953. * @param {string=} onload Expression to evaluate when a new partial is loaded.
  21954. *
  21955. * @param {string=} autoscroll Whether `ngInclude` should call {@link ng.$anchorScroll
  21956. * $anchorScroll} to scroll the viewport after the content is loaded.
  21957. *
  21958. * - If the attribute is not set, disable scrolling.
  21959. * - If the attribute is set without value, enable scrolling.
  21960. * - Otherwise enable scrolling only if the expression evaluates to truthy value.
  21961. *
  21962. * @example
  21963. <example module="includeExample" deps="angular-animate.js" animations="true">
  21964. <file name="index.html">
  21965. <div ng-controller="ExampleController">
  21966. <select ng-model="template" ng-options="t.name for t in templates">
  21967. <option value="">(blank)</option>
  21968. </select>
  21969. url of the template: <code>{{template.url}}</code>
  21970. <hr/>
  21971. <div class="slide-animate-container">
  21972. <div class="slide-animate" ng-include="template.url"></div>
  21973. </div>
  21974. </div>
  21975. </file>
  21976. <file name="script.js">
  21977. angular.module('includeExample', ['ngAnimate'])
  21978. .controller('ExampleController', ['$scope', function($scope) {
  21979. $scope.templates =
  21980. [ { name: 'template1.html', url: 'template1.html'},
  21981. { name: 'template2.html', url: 'template2.html'} ];
  21982. $scope.template = $scope.templates[0];
  21983. }]);
  21984. </file>
  21985. <file name="template1.html">
  21986. Content of template1.html
  21987. </file>
  21988. <file name="template2.html">
  21989. Content of template2.html
  21990. </file>
  21991. <file name="animations.css">
  21992. .slide-animate-container {
  21993. position:relative;
  21994. background:white;
  21995. border:1px solid black;
  21996. height:40px;
  21997. overflow:hidden;
  21998. }
  21999. .slide-animate {
  22000. padding:10px;
  22001. }
  22002. .slide-animate.ng-enter, .slide-animate.ng-leave {
  22003. transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
  22004. position:absolute;
  22005. top:0;
  22006. left:0;
  22007. right:0;
  22008. bottom:0;
  22009. display:block;
  22010. padding:10px;
  22011. }
  22012. .slide-animate.ng-enter {
  22013. top:-50px;
  22014. }
  22015. .slide-animate.ng-enter.ng-enter-active {
  22016. top:0;
  22017. }
  22018. .slide-animate.ng-leave {
  22019. top:0;
  22020. }
  22021. .slide-animate.ng-leave.ng-leave-active {
  22022. top:50px;
  22023. }
  22024. </file>
  22025. <file name="protractor.js" type="protractor">
  22026. var templateSelect = element(by.model('template'));
  22027. var includeElem = element(by.css('[ng-include]'));
  22028. it('should load template1.html', function() {
  22029. expect(includeElem.getText()).toMatch(/Content of template1.html/);
  22030. });
  22031. it('should load template2.html', function() {
  22032. if (browser.params.browser == 'firefox') {
  22033. // Firefox can't handle using selects
  22034. // See https://github.com/angular/protractor/issues/480
  22035. return;
  22036. }
  22037. templateSelect.click();
  22038. templateSelect.all(by.css('option')).get(2).click();
  22039. expect(includeElem.getText()).toMatch(/Content of template2.html/);
  22040. });
  22041. it('should change to blank', function() {
  22042. if (browser.params.browser == 'firefox') {
  22043. // Firefox can't handle using selects
  22044. return;
  22045. }
  22046. templateSelect.click();
  22047. templateSelect.all(by.css('option')).get(0).click();
  22048. expect(includeElem.isPresent()).toBe(false);
  22049. });
  22050. </file>
  22051. </example>
  22052. */
  22053. /**
  22054. * @ngdoc event
  22055. * @name ngInclude#$includeContentRequested
  22056. * @eventType emit on the scope ngInclude was declared in
  22057. * @description
  22058. * Emitted every time the ngInclude content is requested.
  22059. *
  22060. * @param {Object} angularEvent Synthetic event object.
  22061. * @param {String} src URL of content to load.
  22062. */
  22063. /**
  22064. * @ngdoc event
  22065. * @name ngInclude#$includeContentLoaded
  22066. * @eventType emit on the current ngInclude scope
  22067. * @description
  22068. * Emitted every time the ngInclude content is reloaded.
  22069. *
  22070. * @param {Object} angularEvent Synthetic event object.
  22071. * @param {String} src URL of content to load.
  22072. */
  22073. /**
  22074. * @ngdoc event
  22075. * @name ngInclude#$includeContentError
  22076. * @eventType emit on the scope ngInclude was declared in
  22077. * @description
  22078. * Emitted when a template HTTP request yields an erroneous response (status < 200 || status > 299)
  22079. *
  22080. * @param {Object} angularEvent Synthetic event object.
  22081. * @param {String} src URL of content to load.
  22082. */
  22083. var ngIncludeDirective = ['$templateRequest', '$anchorScroll', '$animate',
  22084. function($templateRequest, $anchorScroll, $animate) {
  22085. return {
  22086. restrict: 'ECA',
  22087. priority: 400,
  22088. terminal: true,
  22089. transclude: 'element',
  22090. controller: angular.noop,
  22091. compile: function(element, attr) {
  22092. var srcExp = attr.ngInclude || attr.src,
  22093. onloadExp = attr.onload || '',
  22094. autoScrollExp = attr.autoscroll;
  22095. return function(scope, $element, $attr, ctrl, $transclude) {
  22096. var changeCounter = 0,
  22097. currentScope,
  22098. previousElement,
  22099. currentElement;
  22100. var cleanupLastIncludeContent = function() {
  22101. if (previousElement) {
  22102. previousElement.remove();
  22103. previousElement = null;
  22104. }
  22105. if (currentScope) {
  22106. currentScope.$destroy();
  22107. currentScope = null;
  22108. }
  22109. if (currentElement) {
  22110. $animate.leave(currentElement).then(function() {
  22111. previousElement = null;
  22112. });
  22113. previousElement = currentElement;
  22114. currentElement = null;
  22115. }
  22116. };
  22117. scope.$watch(srcExp, function ngIncludeWatchAction(src) {
  22118. var afterAnimation = function() {
  22119. if (isDefined(autoScrollExp) && (!autoScrollExp || scope.$eval(autoScrollExp))) {
  22120. $anchorScroll();
  22121. }
  22122. };
  22123. var thisChangeId = ++changeCounter;
  22124. if (src) {
  22125. //set the 2nd param to true to ignore the template request error so that the inner
  22126. //contents and scope can be cleaned up.
  22127. $templateRequest(src, true).then(function(response) {
  22128. if (thisChangeId !== changeCounter) return;
  22129. var newScope = scope.$new();
  22130. ctrl.template = response;
  22131. // Note: This will also link all children of ng-include that were contained in the original
  22132. // html. If that content contains controllers, ... they could pollute/change the scope.
  22133. // However, using ng-include on an element with additional content does not make sense...
  22134. // Note: We can't remove them in the cloneAttchFn of $transclude as that
  22135. // function is called before linking the content, which would apply child
  22136. // directives to non existing elements.
  22137. var clone = $transclude(newScope, function(clone) {
  22138. cleanupLastIncludeContent();
  22139. $animate.enter(clone, null, $element).then(afterAnimation);
  22140. });
  22141. currentScope = newScope;
  22142. currentElement = clone;
  22143. currentScope.$emit('$includeContentLoaded', src);
  22144. scope.$eval(onloadExp);
  22145. }, function() {
  22146. if (thisChangeId === changeCounter) {
  22147. cleanupLastIncludeContent();
  22148. scope.$emit('$includeContentError', src);
  22149. }
  22150. });
  22151. scope.$emit('$includeContentRequested', src);
  22152. } else {
  22153. cleanupLastIncludeContent();
  22154. ctrl.template = null;
  22155. }
  22156. });
  22157. };
  22158. }
  22159. };
  22160. }];
  22161. // This directive is called during the $transclude call of the first `ngInclude` directive.
  22162. // It will replace and compile the content of the element with the loaded template.
  22163. // We need this directive so that the element content is already filled when
  22164. // the link function of another directive on the same element as ngInclude
  22165. // is called.
  22166. var ngIncludeFillContentDirective = ['$compile',
  22167. function($compile) {
  22168. return {
  22169. restrict: 'ECA',
  22170. priority: -400,
  22171. require: 'ngInclude',
  22172. link: function(scope, $element, $attr, ctrl) {
  22173. if (/SVG/.test($element[0].toString())) {
  22174. // WebKit: https://bugs.webkit.org/show_bug.cgi?id=135698 --- SVG elements do not
  22175. // support innerHTML, so detect this here and try to generate the contents
  22176. // specially.
  22177. $element.empty();
  22178. $compile(jqLiteBuildFragment(ctrl.template, document).childNodes)(scope,
  22179. function namespaceAdaptedClone(clone) {
  22180. $element.append(clone);
  22181. }, {futureParentElement: $element});
  22182. return;
  22183. }
  22184. $element.html(ctrl.template);
  22185. $compile($element.contents())(scope);
  22186. }
  22187. };
  22188. }];
  22189. /**
  22190. * @ngdoc directive
  22191. * @name ngInit
  22192. * @restrict AC
  22193. *
  22194. * @description
  22195. * The `ngInit` directive allows you to evaluate an expression in the
  22196. * current scope.
  22197. *
  22198. * <div class="alert alert-danger">
  22199. * This directive can be abused to add unnecessary amounts of logic into your templates.
  22200. * There are only a few appropriate uses of `ngInit`, such as for aliasing special properties of
  22201. * {@link ng.directive:ngRepeat `ngRepeat`}, as seen in the demo below; and for injecting data via
  22202. * server side scripting. Besides these few cases, you should use {@link guide/controller controllers}
  22203. * rather than `ngInit` to initialize values on a scope.
  22204. * </div>
  22205. *
  22206. * <div class="alert alert-warning">
  22207. * **Note**: If you have assignment in `ngInit` along with a {@link ng.$filter `filter`}, make
  22208. * sure you have parentheses to ensure correct operator precedence:
  22209. * <pre class="prettyprint">
  22210. * `<div ng-init="test1 = ($index | toString)"></div>`
  22211. * </pre>
  22212. * </div>
  22213. *
  22214. * @priority 450
  22215. *
  22216. * @element ANY
  22217. * @param {expression} ngInit {@link guide/expression Expression} to eval.
  22218. *
  22219. * @example
  22220. <example module="initExample">
  22221. <file name="index.html">
  22222. <script>
  22223. angular.module('initExample', [])
  22224. .controller('ExampleController', ['$scope', function($scope) {
  22225. $scope.list = [['a', 'b'], ['c', 'd']];
  22226. }]);
  22227. </script>
  22228. <div ng-controller="ExampleController">
  22229. <div ng-repeat="innerList in list" ng-init="outerIndex = $index">
  22230. <div ng-repeat="value in innerList" ng-init="innerIndex = $index">
  22231. <span class="example-init">list[ {{outerIndex}} ][ {{innerIndex}} ] = {{value}};</span>
  22232. </div>
  22233. </div>
  22234. </div>
  22235. </file>
  22236. <file name="protractor.js" type="protractor">
  22237. it('should alias index positions', function() {
  22238. var elements = element.all(by.css('.example-init'));
  22239. expect(elements.get(0).getText()).toBe('list[ 0 ][ 0 ] = a;');
  22240. expect(elements.get(1).getText()).toBe('list[ 0 ][ 1 ] = b;');
  22241. expect(elements.get(2).getText()).toBe('list[ 1 ][ 0 ] = c;');
  22242. expect(elements.get(3).getText()).toBe('list[ 1 ][ 1 ] = d;');
  22243. });
  22244. </file>
  22245. </example>
  22246. */
  22247. var ngInitDirective = ngDirective({
  22248. priority: 450,
  22249. compile: function() {
  22250. return {
  22251. pre: function(scope, element, attrs) {
  22252. scope.$eval(attrs.ngInit);
  22253. }
  22254. };
  22255. }
  22256. });
  22257. /**
  22258. * @ngdoc directive
  22259. * @name ngList
  22260. *
  22261. * @description
  22262. * Text input that converts between a delimited string and an array of strings. The default
  22263. * delimiter is a comma followed by a space - equivalent to `ng-list=", "`. You can specify a custom
  22264. * delimiter as the value of the `ngList` attribute - for example, `ng-list=" | "`.
  22265. *
  22266. * The behaviour of the directive is affected by the use of the `ngTrim` attribute.
  22267. * * If `ngTrim` is set to `"false"` then whitespace around both the separator and each
  22268. * list item is respected. This implies that the user of the directive is responsible for
  22269. * dealing with whitespace but also allows you to use whitespace as a delimiter, such as a
  22270. * tab or newline character.
  22271. * * Otherwise whitespace around the delimiter is ignored when splitting (although it is respected
  22272. * when joining the list items back together) and whitespace around each list item is stripped
  22273. * before it is added to the model.
  22274. *
  22275. * ### Example with Validation
  22276. *
  22277. * <example name="ngList-directive" module="listExample">
  22278. * <file name="app.js">
  22279. * angular.module('listExample', [])
  22280. * .controller('ExampleController', ['$scope', function($scope) {
  22281. * $scope.names = ['morpheus', 'neo', 'trinity'];
  22282. * }]);
  22283. * </file>
  22284. * <file name="index.html">
  22285. * <form name="myForm" ng-controller="ExampleController">
  22286. * <label>List: <input name="namesInput" ng-model="names" ng-list required></label>
  22287. * <span role="alert">
  22288. * <span class="error" ng-show="myForm.namesInput.$error.required">
  22289. * Required!</span>
  22290. * </span>
  22291. * <br>
  22292. * <tt>names = {{names}}</tt><br/>
  22293. * <tt>myForm.namesInput.$valid = {{myForm.namesInput.$valid}}</tt><br/>
  22294. * <tt>myForm.namesInput.$error = {{myForm.namesInput.$error}}</tt><br/>
  22295. * <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  22296. * <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  22297. * </form>
  22298. * </file>
  22299. * <file name="protractor.js" type="protractor">
  22300. * var listInput = element(by.model('names'));
  22301. * var names = element(by.exactBinding('names'));
  22302. * var valid = element(by.binding('myForm.namesInput.$valid'));
  22303. * var error = element(by.css('span.error'));
  22304. *
  22305. * it('should initialize to model', function() {
  22306. * expect(names.getText()).toContain('["morpheus","neo","trinity"]');
  22307. * expect(valid.getText()).toContain('true');
  22308. * expect(error.getCssValue('display')).toBe('none');
  22309. * });
  22310. *
  22311. * it('should be invalid if empty', function() {
  22312. * listInput.clear();
  22313. * listInput.sendKeys('');
  22314. *
  22315. * expect(names.getText()).toContain('');
  22316. * expect(valid.getText()).toContain('false');
  22317. * expect(error.getCssValue('display')).not.toBe('none');
  22318. * });
  22319. * </file>
  22320. * </example>
  22321. *
  22322. * ### Example - splitting on whitespace
  22323. * <example name="ngList-directive-newlines">
  22324. * <file name="index.html">
  22325. * <textarea ng-model="list" ng-list="&#10;" ng-trim="false"></textarea>
  22326. * <pre>{{ list | json }}</pre>
  22327. * </file>
  22328. * <file name="protractor.js" type="protractor">
  22329. * it("should split the text by newlines", function() {
  22330. * var listInput = element(by.model('list'));
  22331. * var output = element(by.binding('list | json'));
  22332. * listInput.sendKeys('abc\ndef\nghi');
  22333. * expect(output.getText()).toContain('[\n "abc",\n "def",\n "ghi"\n]');
  22334. * });
  22335. * </file>
  22336. * </example>
  22337. *
  22338. * @element input
  22339. * @param {string=} ngList optional delimiter that should be used to split the value.
  22340. */
  22341. var ngListDirective = function() {
  22342. return {
  22343. restrict: 'A',
  22344. priority: 100,
  22345. require: 'ngModel',
  22346. link: function(scope, element, attr, ctrl) {
  22347. // We want to control whitespace trimming so we use this convoluted approach
  22348. // to access the ngList attribute, which doesn't pre-trim the attribute
  22349. var ngList = element.attr(attr.$attr.ngList) || ', ';
  22350. var trimValues = attr.ngTrim !== 'false';
  22351. var separator = trimValues ? trim(ngList) : ngList;
  22352. var parse = function(viewValue) {
  22353. // If the viewValue is invalid (say required but empty) it will be `undefined`
  22354. if (isUndefined(viewValue)) return;
  22355. var list = [];
  22356. if (viewValue) {
  22357. forEach(viewValue.split(separator), function(value) {
  22358. if (value) list.push(trimValues ? trim(value) : value);
  22359. });
  22360. }
  22361. return list;
  22362. };
  22363. ctrl.$parsers.push(parse);
  22364. ctrl.$formatters.push(function(value) {
  22365. if (isArray(value)) {
  22366. return value.join(ngList);
  22367. }
  22368. return undefined;
  22369. });
  22370. // Override the standard $isEmpty because an empty array means the input is empty.
  22371. ctrl.$isEmpty = function(value) {
  22372. return !value || !value.length;
  22373. };
  22374. }
  22375. };
  22376. };
  22377. /* global VALID_CLASS: true,
  22378. INVALID_CLASS: true,
  22379. PRISTINE_CLASS: true,
  22380. DIRTY_CLASS: true,
  22381. UNTOUCHED_CLASS: true,
  22382. TOUCHED_CLASS: true,
  22383. */
  22384. var VALID_CLASS = 'ng-valid',
  22385. INVALID_CLASS = 'ng-invalid',
  22386. PRISTINE_CLASS = 'ng-pristine',
  22387. DIRTY_CLASS = 'ng-dirty',
  22388. UNTOUCHED_CLASS = 'ng-untouched',
  22389. TOUCHED_CLASS = 'ng-touched',
  22390. PENDING_CLASS = 'ng-pending';
  22391. var ngModelMinErr = minErr('ngModel');
  22392. /**
  22393. * @ngdoc type
  22394. * @name ngModel.NgModelController
  22395. *
  22396. * @property {string} $viewValue Actual string value in the view.
  22397. * @property {*} $modelValue The value in the model that the control is bound to.
  22398. * @property {Array.<Function>} $parsers Array of functions to execute, as a pipeline, whenever
  22399. the control reads value from the DOM. The functions are called in array order, each passing
  22400. its return value through to the next. The last return value is forwarded to the
  22401. {@link ngModel.NgModelController#$validators `$validators`} collection.
  22402. Parsers are used to sanitize / convert the {@link ngModel.NgModelController#$viewValue
  22403. `$viewValue`}.
  22404. Returning `undefined` from a parser means a parse error occurred. In that case,
  22405. no {@link ngModel.NgModelController#$validators `$validators`} will run and the `ngModel`
  22406. will be set to `undefined` unless {@link ngModelOptions `ngModelOptions.allowInvalid`}
  22407. is set to `true`. The parse error is stored in `ngModel.$error.parse`.
  22408. *
  22409. * @property {Array.<Function>} $formatters Array of functions to execute, as a pipeline, whenever
  22410. the model value changes. The functions are called in reverse array order, each passing the value through to the
  22411. next. The last return value is used as the actual DOM value.
  22412. Used to format / convert values for display in the control.
  22413. * ```js
  22414. * function formatter(value) {
  22415. * if (value) {
  22416. * return value.toUpperCase();
  22417. * }
  22418. * }
  22419. * ngModel.$formatters.push(formatter);
  22420. * ```
  22421. *
  22422. * @property {Object.<string, function>} $validators A collection of validators that are applied
  22423. * whenever the model value changes. The key value within the object refers to the name of the
  22424. * validator while the function refers to the validation operation. The validation operation is
  22425. * provided with the model value as an argument and must return a true or false value depending
  22426. * on the response of that validation.
  22427. *
  22428. * ```js
  22429. * ngModel.$validators.validCharacters = function(modelValue, viewValue) {
  22430. * var value = modelValue || viewValue;
  22431. * return /[0-9]+/.test(value) &&
  22432. * /[a-z]+/.test(value) &&
  22433. * /[A-Z]+/.test(value) &&
  22434. * /\W+/.test(value);
  22435. * };
  22436. * ```
  22437. *
  22438. * @property {Object.<string, function>} $asyncValidators A collection of validations that are expected to
  22439. * perform an asynchronous validation (e.g. a HTTP request). The validation function that is provided
  22440. * is expected to return a promise when it is run during the model validation process. Once the promise
  22441. * is delivered then the validation status will be set to true when fulfilled and false when rejected.
  22442. * When the asynchronous validators are triggered, each of the validators will run in parallel and the model
  22443. * value will only be updated once all validators have been fulfilled. As long as an asynchronous validator
  22444. * is unfulfilled, its key will be added to the controllers `$pending` property. Also, all asynchronous validators
  22445. * will only run once all synchronous validators have passed.
  22446. *
  22447. * Please note that if $http is used then it is important that the server returns a success HTTP response code
  22448. * in order to fulfill the validation and a status level of `4xx` in order to reject the validation.
  22449. *
  22450. * ```js
  22451. * ngModel.$asyncValidators.uniqueUsername = function(modelValue, viewValue) {
  22452. * var value = modelValue || viewValue;
  22453. *
  22454. * // Lookup user by username
  22455. * return $http.get('/api/users/' + value).
  22456. * then(function resolved() {
  22457. * //username exists, this means validation fails
  22458. * return $q.reject('exists');
  22459. * }, function rejected() {
  22460. * //username does not exist, therefore this validation passes
  22461. * return true;
  22462. * });
  22463. * };
  22464. * ```
  22465. *
  22466. * @property {Array.<Function>} $viewChangeListeners Array of functions to execute whenever the
  22467. * view value has changed. It is called with no arguments, and its return value is ignored.
  22468. * This can be used in place of additional $watches against the model value.
  22469. *
  22470. * @property {Object} $error An object hash with all failing validator ids as keys.
  22471. * @property {Object} $pending An object hash with all pending validator ids as keys.
  22472. *
  22473. * @property {boolean} $untouched True if control has not lost focus yet.
  22474. * @property {boolean} $touched True if control has lost focus.
  22475. * @property {boolean} $pristine True if user has not interacted with the control yet.
  22476. * @property {boolean} $dirty True if user has already interacted with the control.
  22477. * @property {boolean} $valid True if there is no error.
  22478. * @property {boolean} $invalid True if at least one error on the control.
  22479. * @property {string} $name The name attribute of the control.
  22480. *
  22481. * @description
  22482. *
  22483. * `NgModelController` provides API for the {@link ngModel `ngModel`} directive.
  22484. * The controller contains services for data-binding, validation, CSS updates, and value formatting
  22485. * and parsing. It purposefully does not contain any logic which deals with DOM rendering or
  22486. * listening to DOM events.
  22487. * Such DOM related logic should be provided by other directives which make use of
  22488. * `NgModelController` for data-binding to control elements.
  22489. * Angular provides this DOM logic for most {@link input `input`} elements.
  22490. * At the end of this page you can find a {@link ngModel.NgModelController#custom-control-example
  22491. * custom control example} that uses `ngModelController` to bind to `contenteditable` elements.
  22492. *
  22493. * @example
  22494. * ### Custom Control Example
  22495. * This example shows how to use `NgModelController` with a custom control to achieve
  22496. * data-binding. Notice how different directives (`contenteditable`, `ng-model`, and `required`)
  22497. * collaborate together to achieve the desired result.
  22498. *
  22499. * `contenteditable` is an HTML5 attribute, which tells the browser to let the element
  22500. * contents be edited in place by the user.
  22501. *
  22502. * We are using the {@link ng.service:$sce $sce} service here and include the {@link ngSanitize $sanitize}
  22503. * module to automatically remove "bad" content like inline event listener (e.g. `<span onclick="...">`).
  22504. * However, as we are using `$sce` the model can still decide to provide unsafe content if it marks
  22505. * that content using the `$sce` service.
  22506. *
  22507. * <example name="NgModelController" module="customControl" deps="angular-sanitize.js">
  22508. <file name="style.css">
  22509. [contenteditable] {
  22510. border: 1px solid black;
  22511. background-color: white;
  22512. min-height: 20px;
  22513. }
  22514. .ng-invalid {
  22515. border: 1px solid red;
  22516. }
  22517. </file>
  22518. <file name="script.js">
  22519. angular.module('customControl', ['ngSanitize']).
  22520. directive('contenteditable', ['$sce', function($sce) {
  22521. return {
  22522. restrict: 'A', // only activate on element attribute
  22523. require: '?ngModel', // get a hold of NgModelController
  22524. link: function(scope, element, attrs, ngModel) {
  22525. if (!ngModel) return; // do nothing if no ng-model
  22526. // Specify how UI should be updated
  22527. ngModel.$render = function() {
  22528. element.html($sce.getTrustedHtml(ngModel.$viewValue || ''));
  22529. };
  22530. // Listen for change events to enable binding
  22531. element.on('blur keyup change', function() {
  22532. scope.$evalAsync(read);
  22533. });
  22534. read(); // initialize
  22535. // Write data to the model
  22536. function read() {
  22537. var html = element.html();
  22538. // When we clear the content editable the browser leaves a <br> behind
  22539. // If strip-br attribute is provided then we strip this out
  22540. if ( attrs.stripBr && html == '<br>' ) {
  22541. html = '';
  22542. }
  22543. ngModel.$setViewValue(html);
  22544. }
  22545. }
  22546. };
  22547. }]);
  22548. </file>
  22549. <file name="index.html">
  22550. <form name="myForm">
  22551. <div contenteditable
  22552. name="myWidget" ng-model="userContent"
  22553. strip-br="true"
  22554. required>Change me!</div>
  22555. <span ng-show="myForm.myWidget.$error.required">Required!</span>
  22556. <hr>
  22557. <textarea ng-model="userContent" aria-label="Dynamic textarea"></textarea>
  22558. </form>
  22559. </file>
  22560. <file name="protractor.js" type="protractor">
  22561. it('should data-bind and become invalid', function() {
  22562. if (browser.params.browser == 'safari' || browser.params.browser == 'firefox') {
  22563. // SafariDriver can't handle contenteditable
  22564. // and Firefox driver can't clear contenteditables very well
  22565. return;
  22566. }
  22567. var contentEditable = element(by.css('[contenteditable]'));
  22568. var content = 'Change me!';
  22569. expect(contentEditable.getText()).toEqual(content);
  22570. contentEditable.clear();
  22571. contentEditable.sendKeys(protractor.Key.BACK_SPACE);
  22572. expect(contentEditable.getText()).toEqual('');
  22573. expect(contentEditable.getAttribute('class')).toMatch(/ng-invalid-required/);
  22574. });
  22575. </file>
  22576. * </example>
  22577. *
  22578. *
  22579. */
  22580. var NgModelController = ['$scope', '$exceptionHandler', '$attrs', '$element', '$parse', '$animate', '$timeout', '$rootScope', '$q', '$interpolate',
  22581. function($scope, $exceptionHandler, $attr, $element, $parse, $animate, $timeout, $rootScope, $q, $interpolate) {
  22582. this.$viewValue = Number.NaN;
  22583. this.$modelValue = Number.NaN;
  22584. this.$$rawModelValue = undefined; // stores the parsed modelValue / model set from scope regardless of validity.
  22585. this.$validators = {};
  22586. this.$asyncValidators = {};
  22587. this.$parsers = [];
  22588. this.$formatters = [];
  22589. this.$viewChangeListeners = [];
  22590. this.$untouched = true;
  22591. this.$touched = false;
  22592. this.$pristine = true;
  22593. this.$dirty = false;
  22594. this.$valid = true;
  22595. this.$invalid = false;
  22596. this.$error = {}; // keep invalid keys here
  22597. this.$$success = {}; // keep valid keys here
  22598. this.$pending = undefined; // keep pending keys here
  22599. this.$name = $interpolate($attr.name || '', false)($scope);
  22600. this.$$parentForm = nullFormCtrl;
  22601. var parsedNgModel = $parse($attr.ngModel),
  22602. parsedNgModelAssign = parsedNgModel.assign,
  22603. ngModelGet = parsedNgModel,
  22604. ngModelSet = parsedNgModelAssign,
  22605. pendingDebounce = null,
  22606. parserValid,
  22607. ctrl = this;
  22608. this.$$setOptions = function(options) {
  22609. ctrl.$options = options;
  22610. if (options && options.getterSetter) {
  22611. var invokeModelGetter = $parse($attr.ngModel + '()'),
  22612. invokeModelSetter = $parse($attr.ngModel + '($$$p)');
  22613. ngModelGet = function($scope) {
  22614. var modelValue = parsedNgModel($scope);
  22615. if (isFunction(modelValue)) {
  22616. modelValue = invokeModelGetter($scope);
  22617. }
  22618. return modelValue;
  22619. };
  22620. ngModelSet = function($scope, newValue) {
  22621. if (isFunction(parsedNgModel($scope))) {
  22622. invokeModelSetter($scope, {$$$p: ctrl.$modelValue});
  22623. } else {
  22624. parsedNgModelAssign($scope, ctrl.$modelValue);
  22625. }
  22626. };
  22627. } else if (!parsedNgModel.assign) {
  22628. throw ngModelMinErr('nonassign', "Expression '{0}' is non-assignable. Element: {1}",
  22629. $attr.ngModel, startingTag($element));
  22630. }
  22631. };
  22632. /**
  22633. * @ngdoc method
  22634. * @name ngModel.NgModelController#$render
  22635. *
  22636. * @description
  22637. * Called when the view needs to be updated. It is expected that the user of the ng-model
  22638. * directive will implement this method.
  22639. *
  22640. * The `$render()` method is invoked in the following situations:
  22641. *
  22642. * * `$rollbackViewValue()` is called. If we are rolling back the view value to the last
  22643. * committed value then `$render()` is called to update the input control.
  22644. * * The value referenced by `ng-model` is changed programmatically and both the `$modelValue` and
  22645. * the `$viewValue` are different from last time.
  22646. *
  22647. * Since `ng-model` does not do a deep watch, `$render()` is only invoked if the values of
  22648. * `$modelValue` and `$viewValue` are actually different from their previous value. If `$modelValue`
  22649. * or `$viewValue` are objects (rather than a string or number) then `$render()` will not be
  22650. * invoked if you only change a property on the objects.
  22651. */
  22652. this.$render = noop;
  22653. /**
  22654. * @ngdoc method
  22655. * @name ngModel.NgModelController#$isEmpty
  22656. *
  22657. * @description
  22658. * This is called when we need to determine if the value of an input is empty.
  22659. *
  22660. * For instance, the required directive does this to work out if the input has data or not.
  22661. *
  22662. * The default `$isEmpty` function checks whether the value is `undefined`, `''`, `null` or `NaN`.
  22663. *
  22664. * You can override this for input directives whose concept of being empty is different from the
  22665. * default. The `checkboxInputType` directive does this because in its case a value of `false`
  22666. * implies empty.
  22667. *
  22668. * @param {*} value The value of the input to check for emptiness.
  22669. * @returns {boolean} True if `value` is "empty".
  22670. */
  22671. this.$isEmpty = function(value) {
  22672. return isUndefined(value) || value === '' || value === null || value !== value;
  22673. };
  22674. var currentValidationRunId = 0;
  22675. /**
  22676. * @ngdoc method
  22677. * @name ngModel.NgModelController#$setValidity
  22678. *
  22679. * @description
  22680. * Change the validity state, and notify the form.
  22681. *
  22682. * This method can be called within $parsers/$formatters or a custom validation implementation.
  22683. * However, in most cases it should be sufficient to use the `ngModel.$validators` and
  22684. * `ngModel.$asyncValidators` collections which will call `$setValidity` automatically.
  22685. *
  22686. * @param {string} validationErrorKey Name of the validator. The `validationErrorKey` will be assigned
  22687. * to either `$error[validationErrorKey]` or `$pending[validationErrorKey]`
  22688. * (for unfulfilled `$asyncValidators`), so that it is available for data-binding.
  22689. * The `validationErrorKey` should be in camelCase and will get converted into dash-case
  22690. * for class name. Example: `myError` will result in `ng-valid-my-error` and `ng-invalid-my-error`
  22691. * class and can be bound to as `{{someForm.someControl.$error.myError}}` .
  22692. * @param {boolean} isValid Whether the current state is valid (true), invalid (false), pending (undefined),
  22693. * or skipped (null). Pending is used for unfulfilled `$asyncValidators`.
  22694. * Skipped is used by Angular when validators do not run because of parse errors and
  22695. * when `$asyncValidators` do not run because any of the `$validators` failed.
  22696. */
  22697. addSetValidityMethod({
  22698. ctrl: this,
  22699. $element: $element,
  22700. set: function(object, property) {
  22701. object[property] = true;
  22702. },
  22703. unset: function(object, property) {
  22704. delete object[property];
  22705. },
  22706. $animate: $animate
  22707. });
  22708. /**
  22709. * @ngdoc method
  22710. * @name ngModel.NgModelController#$setPristine
  22711. *
  22712. * @description
  22713. * Sets the control to its pristine state.
  22714. *
  22715. * This method can be called to remove the `ng-dirty` class and set the control to its pristine
  22716. * state (`ng-pristine` class). A model is considered to be pristine when the control
  22717. * has not been changed from when first compiled.
  22718. */
  22719. this.$setPristine = function() {
  22720. ctrl.$dirty = false;
  22721. ctrl.$pristine = true;
  22722. $animate.removeClass($element, DIRTY_CLASS);
  22723. $animate.addClass($element, PRISTINE_CLASS);
  22724. };
  22725. /**
  22726. * @ngdoc method
  22727. * @name ngModel.NgModelController#$setDirty
  22728. *
  22729. * @description
  22730. * Sets the control to its dirty state.
  22731. *
  22732. * This method can be called to remove the `ng-pristine` class and set the control to its dirty
  22733. * state (`ng-dirty` class). A model is considered to be dirty when the control has been changed
  22734. * from when first compiled.
  22735. */
  22736. this.$setDirty = function() {
  22737. ctrl.$dirty = true;
  22738. ctrl.$pristine = false;
  22739. $animate.removeClass($element, PRISTINE_CLASS);
  22740. $animate.addClass($element, DIRTY_CLASS);
  22741. ctrl.$$parentForm.$setDirty();
  22742. };
  22743. /**
  22744. * @ngdoc method
  22745. * @name ngModel.NgModelController#$setUntouched
  22746. *
  22747. * @description
  22748. * Sets the control to its untouched state.
  22749. *
  22750. * This method can be called to remove the `ng-touched` class and set the control to its
  22751. * untouched state (`ng-untouched` class). Upon compilation, a model is set as untouched
  22752. * by default, however this function can be used to restore that state if the model has
  22753. * already been touched by the user.
  22754. */
  22755. this.$setUntouched = function() {
  22756. ctrl.$touched = false;
  22757. ctrl.$untouched = true;
  22758. $animate.setClass($element, UNTOUCHED_CLASS, TOUCHED_CLASS);
  22759. };
  22760. /**
  22761. * @ngdoc method
  22762. * @name ngModel.NgModelController#$setTouched
  22763. *
  22764. * @description
  22765. * Sets the control to its touched state.
  22766. *
  22767. * This method can be called to remove the `ng-untouched` class and set the control to its
  22768. * touched state (`ng-touched` class). A model is considered to be touched when the user has
  22769. * first focused the control element and then shifted focus away from the control (blur event).
  22770. */
  22771. this.$setTouched = function() {
  22772. ctrl.$touched = true;
  22773. ctrl.$untouched = false;
  22774. $animate.setClass($element, TOUCHED_CLASS, UNTOUCHED_CLASS);
  22775. };
  22776. /**
  22777. * @ngdoc method
  22778. * @name ngModel.NgModelController#$rollbackViewValue
  22779. *
  22780. * @description
  22781. * Cancel an update and reset the input element's value to prevent an update to the `$modelValue`,
  22782. * which may be caused by a pending debounced event or because the input is waiting for a some
  22783. * future event.
  22784. *
  22785. * If you have an input that uses `ng-model-options` to set up debounced events or events such
  22786. * as blur you can have a situation where there is a period when the `$viewValue`
  22787. * is out of synch with the ngModel's `$modelValue`.
  22788. *
  22789. * In this case, you can run into difficulties if you try to update the ngModel's `$modelValue`
  22790. * programmatically before these debounced/future events have resolved/occurred, because Angular's
  22791. * dirty checking mechanism is not able to tell whether the model has actually changed or not.
  22792. *
  22793. * The `$rollbackViewValue()` method should be called before programmatically changing the model of an
  22794. * input which may have such events pending. This is important in order to make sure that the
  22795. * input field will be updated with the new model value and any pending operations are cancelled.
  22796. *
  22797. * <example name="ng-model-cancel-update" module="cancel-update-example">
  22798. * <file name="app.js">
  22799. * angular.module('cancel-update-example', [])
  22800. *
  22801. * .controller('CancelUpdateController', ['$scope', function($scope) {
  22802. * $scope.resetWithCancel = function(e) {
  22803. * if (e.keyCode == 27) {
  22804. * $scope.myForm.myInput1.$rollbackViewValue();
  22805. * $scope.myValue = '';
  22806. * }
  22807. * };
  22808. * $scope.resetWithoutCancel = function(e) {
  22809. * if (e.keyCode == 27) {
  22810. * $scope.myValue = '';
  22811. * }
  22812. * };
  22813. * }]);
  22814. * </file>
  22815. * <file name="index.html">
  22816. * <div ng-controller="CancelUpdateController">
  22817. * <p>Try typing something in each input. See that the model only updates when you
  22818. * blur off the input.
  22819. * </p>
  22820. * <p>Now see what happens if you start typing then press the Escape key</p>
  22821. *
  22822. * <form name="myForm" ng-model-options="{ updateOn: 'blur' }">
  22823. * <p id="inputDescription1">With $rollbackViewValue()</p>
  22824. * <input name="myInput1" aria-describedby="inputDescription1" ng-model="myValue"
  22825. * ng-keydown="resetWithCancel($event)"><br/>
  22826. * myValue: "{{ myValue }}"
  22827. *
  22828. * <p id="inputDescription2">Without $rollbackViewValue()</p>
  22829. * <input name="myInput2" aria-describedby="inputDescription2" ng-model="myValue"
  22830. * ng-keydown="resetWithoutCancel($event)"><br/>
  22831. * myValue: "{{ myValue }}"
  22832. * </form>
  22833. * </div>
  22834. * </file>
  22835. * </example>
  22836. */
  22837. this.$rollbackViewValue = function() {
  22838. $timeout.cancel(pendingDebounce);
  22839. ctrl.$viewValue = ctrl.$$lastCommittedViewValue;
  22840. ctrl.$render();
  22841. };
  22842. /**
  22843. * @ngdoc method
  22844. * @name ngModel.NgModelController#$validate
  22845. *
  22846. * @description
  22847. * Runs each of the registered validators (first synchronous validators and then
  22848. * asynchronous validators).
  22849. * If the validity changes to invalid, the model will be set to `undefined`,
  22850. * unless {@link ngModelOptions `ngModelOptions.allowInvalid`} is `true`.
  22851. * If the validity changes to valid, it will set the model to the last available valid
  22852. * `$modelValue`, i.e. either the last parsed value or the last value set from the scope.
  22853. */
  22854. this.$validate = function() {
  22855. // ignore $validate before model is initialized
  22856. if (isNumber(ctrl.$modelValue) && isNaN(ctrl.$modelValue)) {
  22857. return;
  22858. }
  22859. var viewValue = ctrl.$$lastCommittedViewValue;
  22860. // Note: we use the $$rawModelValue as $modelValue might have been
  22861. // set to undefined during a view -> model update that found validation
  22862. // errors. We can't parse the view here, since that could change
  22863. // the model although neither viewValue nor the model on the scope changed
  22864. var modelValue = ctrl.$$rawModelValue;
  22865. var prevValid = ctrl.$valid;
  22866. var prevModelValue = ctrl.$modelValue;
  22867. var allowInvalid = ctrl.$options && ctrl.$options.allowInvalid;
  22868. ctrl.$$runValidators(modelValue, viewValue, function(allValid) {
  22869. // If there was no change in validity, don't update the model
  22870. // This prevents changing an invalid modelValue to undefined
  22871. if (!allowInvalid && prevValid !== allValid) {
  22872. // Note: Don't check ctrl.$valid here, as we could have
  22873. // external validators (e.g. calculated on the server),
  22874. // that just call $setValidity and need the model value
  22875. // to calculate their validity.
  22876. ctrl.$modelValue = allValid ? modelValue : undefined;
  22877. if (ctrl.$modelValue !== prevModelValue) {
  22878. ctrl.$$writeModelToScope();
  22879. }
  22880. }
  22881. });
  22882. };
  22883. this.$$runValidators = function(modelValue, viewValue, doneCallback) {
  22884. currentValidationRunId++;
  22885. var localValidationRunId = currentValidationRunId;
  22886. // check parser error
  22887. if (!processParseErrors()) {
  22888. validationDone(false);
  22889. return;
  22890. }
  22891. if (!processSyncValidators()) {
  22892. validationDone(false);
  22893. return;
  22894. }
  22895. processAsyncValidators();
  22896. function processParseErrors() {
  22897. var errorKey = ctrl.$$parserName || 'parse';
  22898. if (isUndefined(parserValid)) {
  22899. setValidity(errorKey, null);
  22900. } else {
  22901. if (!parserValid) {
  22902. forEach(ctrl.$validators, function(v, name) {
  22903. setValidity(name, null);
  22904. });
  22905. forEach(ctrl.$asyncValidators, function(v, name) {
  22906. setValidity(name, null);
  22907. });
  22908. }
  22909. // Set the parse error last, to prevent unsetting it, should a $validators key == parserName
  22910. setValidity(errorKey, parserValid);
  22911. return parserValid;
  22912. }
  22913. return true;
  22914. }
  22915. function processSyncValidators() {
  22916. var syncValidatorsValid = true;
  22917. forEach(ctrl.$validators, function(validator, name) {
  22918. var result = validator(modelValue, viewValue);
  22919. syncValidatorsValid = syncValidatorsValid && result;
  22920. setValidity(name, result);
  22921. });
  22922. if (!syncValidatorsValid) {
  22923. forEach(ctrl.$asyncValidators, function(v, name) {
  22924. setValidity(name, null);
  22925. });
  22926. return false;
  22927. }
  22928. return true;
  22929. }
  22930. function processAsyncValidators() {
  22931. var validatorPromises = [];
  22932. var allValid = true;
  22933. forEach(ctrl.$asyncValidators, function(validator, name) {
  22934. var promise = validator(modelValue, viewValue);
  22935. if (!isPromiseLike(promise)) {
  22936. throw ngModelMinErr("$asyncValidators",
  22937. "Expected asynchronous validator to return a promise but got '{0}' instead.", promise);
  22938. }
  22939. setValidity(name, undefined);
  22940. validatorPromises.push(promise.then(function() {
  22941. setValidity(name, true);
  22942. }, function(error) {
  22943. allValid = false;
  22944. setValidity(name, false);
  22945. }));
  22946. });
  22947. if (!validatorPromises.length) {
  22948. validationDone(true);
  22949. } else {
  22950. $q.all(validatorPromises).then(function() {
  22951. validationDone(allValid);
  22952. }, noop);
  22953. }
  22954. }
  22955. function setValidity(name, isValid) {
  22956. if (localValidationRunId === currentValidationRunId) {
  22957. ctrl.$setValidity(name, isValid);
  22958. }
  22959. }
  22960. function validationDone(allValid) {
  22961. if (localValidationRunId === currentValidationRunId) {
  22962. doneCallback(allValid);
  22963. }
  22964. }
  22965. };
  22966. /**
  22967. * @ngdoc method
  22968. * @name ngModel.NgModelController#$commitViewValue
  22969. *
  22970. * @description
  22971. * Commit a pending update to the `$modelValue`.
  22972. *
  22973. * Updates may be pending by a debounced event or because the input is waiting for a some future
  22974. * event defined in `ng-model-options`. this method is rarely needed as `NgModelController`
  22975. * usually handles calling this in response to input events.
  22976. */
  22977. this.$commitViewValue = function() {
  22978. var viewValue = ctrl.$viewValue;
  22979. $timeout.cancel(pendingDebounce);
  22980. // If the view value has not changed then we should just exit, except in the case where there is
  22981. // a native validator on the element. In this case the validation state may have changed even though
  22982. // the viewValue has stayed empty.
  22983. if (ctrl.$$lastCommittedViewValue === viewValue && (viewValue !== '' || !ctrl.$$hasNativeValidators)) {
  22984. return;
  22985. }
  22986. ctrl.$$lastCommittedViewValue = viewValue;
  22987. // change to dirty
  22988. if (ctrl.$pristine) {
  22989. this.$setDirty();
  22990. }
  22991. this.$$parseAndValidate();
  22992. };
  22993. this.$$parseAndValidate = function() {
  22994. var viewValue = ctrl.$$lastCommittedViewValue;
  22995. var modelValue = viewValue;
  22996. parserValid = isUndefined(modelValue) ? undefined : true;
  22997. if (parserValid) {
  22998. for (var i = 0; i < ctrl.$parsers.length; i++) {
  22999. modelValue = ctrl.$parsers[i](modelValue);
  23000. if (isUndefined(modelValue)) {
  23001. parserValid = false;
  23002. break;
  23003. }
  23004. }
  23005. }
  23006. if (isNumber(ctrl.$modelValue) && isNaN(ctrl.$modelValue)) {
  23007. // ctrl.$modelValue has not been touched yet...
  23008. ctrl.$modelValue = ngModelGet($scope);
  23009. }
  23010. var prevModelValue = ctrl.$modelValue;
  23011. var allowInvalid = ctrl.$options && ctrl.$options.allowInvalid;
  23012. ctrl.$$rawModelValue = modelValue;
  23013. if (allowInvalid) {
  23014. ctrl.$modelValue = modelValue;
  23015. writeToModelIfNeeded();
  23016. }
  23017. // Pass the $$lastCommittedViewValue here, because the cached viewValue might be out of date.
  23018. // This can happen if e.g. $setViewValue is called from inside a parser
  23019. ctrl.$$runValidators(modelValue, ctrl.$$lastCommittedViewValue, function(allValid) {
  23020. if (!allowInvalid) {
  23021. // Note: Don't check ctrl.$valid here, as we could have
  23022. // external validators (e.g. calculated on the server),
  23023. // that just call $setValidity and need the model value
  23024. // to calculate their validity.
  23025. ctrl.$modelValue = allValid ? modelValue : undefined;
  23026. writeToModelIfNeeded();
  23027. }
  23028. });
  23029. function writeToModelIfNeeded() {
  23030. if (ctrl.$modelValue !== prevModelValue) {
  23031. ctrl.$$writeModelToScope();
  23032. }
  23033. }
  23034. };
  23035. this.$$writeModelToScope = function() {
  23036. ngModelSet($scope, ctrl.$modelValue);
  23037. forEach(ctrl.$viewChangeListeners, function(listener) {
  23038. try {
  23039. listener();
  23040. } catch (e) {
  23041. $exceptionHandler(e);
  23042. }
  23043. });
  23044. };
  23045. /**
  23046. * @ngdoc method
  23047. * @name ngModel.NgModelController#$setViewValue
  23048. *
  23049. * @description
  23050. * Update the view value.
  23051. *
  23052. * This method should be called when a control wants to change the view value; typically,
  23053. * this is done from within a DOM event handler. For example, the {@link ng.directive:input input}
  23054. * directive calls it when the value of the input changes and {@link ng.directive:select select}
  23055. * calls it when an option is selected.
  23056. *
  23057. * When `$setViewValue` is called, the new `value` will be staged for committing through the `$parsers`
  23058. * and `$validators` pipelines. If there are no special {@link ngModelOptions} specified then the staged
  23059. * value sent directly for processing, finally to be applied to `$modelValue` and then the
  23060. * **expression** specified in the `ng-model` attribute. Lastly, all the registered change listeners,
  23061. * in the `$viewChangeListeners` list, are called.
  23062. *
  23063. * In case the {@link ng.directive:ngModelOptions ngModelOptions} directive is used with `updateOn`
  23064. * and the `default` trigger is not listed, all those actions will remain pending until one of the
  23065. * `updateOn` events is triggered on the DOM element.
  23066. * All these actions will be debounced if the {@link ng.directive:ngModelOptions ngModelOptions}
  23067. * directive is used with a custom debounce for this particular event.
  23068. * Note that a `$digest` is only triggered once the `updateOn` events are fired, or if `debounce`
  23069. * is specified, once the timer runs out.
  23070. *
  23071. * When used with standard inputs, the view value will always be a string (which is in some cases
  23072. * parsed into another type, such as a `Date` object for `input[date]`.)
  23073. * However, custom controls might also pass objects to this method. In this case, we should make
  23074. * a copy of the object before passing it to `$setViewValue`. This is because `ngModel` does not
  23075. * perform a deep watch of objects, it only looks for a change of identity. If you only change
  23076. * the property of the object then ngModel will not realise that the object has changed and
  23077. * will not invoke the `$parsers` and `$validators` pipelines. For this reason, you should
  23078. * not change properties of the copy once it has been passed to `$setViewValue`.
  23079. * Otherwise you may cause the model value on the scope to change incorrectly.
  23080. *
  23081. * <div class="alert alert-info">
  23082. * In any case, the value passed to the method should always reflect the current value
  23083. * of the control. For example, if you are calling `$setViewValue` for an input element,
  23084. * you should pass the input DOM value. Otherwise, the control and the scope model become
  23085. * out of sync. It's also important to note that `$setViewValue` does not call `$render` or change
  23086. * the control's DOM value in any way. If we want to change the control's DOM value
  23087. * programmatically, we should update the `ngModel` scope expression. Its new value will be
  23088. * picked up by the model controller, which will run it through the `$formatters`, `$render` it
  23089. * to update the DOM, and finally call `$validate` on it.
  23090. * </div>
  23091. *
  23092. * @param {*} value value from the view.
  23093. * @param {string} trigger Event that triggered the update.
  23094. */
  23095. this.$setViewValue = function(value, trigger) {
  23096. ctrl.$viewValue = value;
  23097. if (!ctrl.$options || ctrl.$options.updateOnDefault) {
  23098. ctrl.$$debounceViewValueCommit(trigger);
  23099. }
  23100. };
  23101. this.$$debounceViewValueCommit = function(trigger) {
  23102. var debounceDelay = 0,
  23103. options = ctrl.$options,
  23104. debounce;
  23105. if (options && isDefined(options.debounce)) {
  23106. debounce = options.debounce;
  23107. if (isNumber(debounce)) {
  23108. debounceDelay = debounce;
  23109. } else if (isNumber(debounce[trigger])) {
  23110. debounceDelay = debounce[trigger];
  23111. } else if (isNumber(debounce['default'])) {
  23112. debounceDelay = debounce['default'];
  23113. }
  23114. }
  23115. $timeout.cancel(pendingDebounce);
  23116. if (debounceDelay) {
  23117. pendingDebounce = $timeout(function() {
  23118. ctrl.$commitViewValue();
  23119. }, debounceDelay);
  23120. } else if ($rootScope.$$phase) {
  23121. ctrl.$commitViewValue();
  23122. } else {
  23123. $scope.$apply(function() {
  23124. ctrl.$commitViewValue();
  23125. });
  23126. }
  23127. };
  23128. // model -> value
  23129. // Note: we cannot use a normal scope.$watch as we want to detect the following:
  23130. // 1. scope value is 'a'
  23131. // 2. user enters 'b'
  23132. // 3. ng-change kicks in and reverts scope value to 'a'
  23133. // -> scope value did not change since the last digest as
  23134. // ng-change executes in apply phase
  23135. // 4. view should be changed back to 'a'
  23136. $scope.$watch(function ngModelWatch() {
  23137. var modelValue = ngModelGet($scope);
  23138. // if scope model value and ngModel value are out of sync
  23139. // TODO(perf): why not move this to the action fn?
  23140. if (modelValue !== ctrl.$modelValue &&
  23141. // checks for NaN is needed to allow setting the model to NaN when there's an asyncValidator
  23142. (ctrl.$modelValue === ctrl.$modelValue || modelValue === modelValue)
  23143. ) {
  23144. ctrl.$modelValue = ctrl.$$rawModelValue = modelValue;
  23145. parserValid = undefined;
  23146. var formatters = ctrl.$formatters,
  23147. idx = formatters.length;
  23148. var viewValue = modelValue;
  23149. while (idx--) {
  23150. viewValue = formatters[idx](viewValue);
  23151. }
  23152. if (ctrl.$viewValue !== viewValue) {
  23153. ctrl.$viewValue = ctrl.$$lastCommittedViewValue = viewValue;
  23154. ctrl.$render();
  23155. ctrl.$$runValidators(modelValue, viewValue, noop);
  23156. }
  23157. }
  23158. return modelValue;
  23159. });
  23160. }];
  23161. /**
  23162. * @ngdoc directive
  23163. * @name ngModel
  23164. *
  23165. * @element input
  23166. * @priority 1
  23167. *
  23168. * @description
  23169. * The `ngModel` directive binds an `input`,`select`, `textarea` (or custom form control) to a
  23170. * property on the scope using {@link ngModel.NgModelController NgModelController},
  23171. * which is created and exposed by this directive.
  23172. *
  23173. * `ngModel` is responsible for:
  23174. *
  23175. * - Binding the view into the model, which other directives such as `input`, `textarea` or `select`
  23176. * require.
  23177. * - Providing validation behavior (i.e. required, number, email, url).
  23178. * - Keeping the state of the control (valid/invalid, dirty/pristine, touched/untouched, validation errors).
  23179. * - Setting related css classes on the element (`ng-valid`, `ng-invalid`, `ng-dirty`, `ng-pristine`, `ng-touched`, `ng-untouched`) including animations.
  23180. * - Registering the control with its parent {@link ng.directive:form form}.
  23181. *
  23182. * Note: `ngModel` will try to bind to the property given by evaluating the expression on the
  23183. * current scope. If the property doesn't already exist on this scope, it will be created
  23184. * implicitly and added to the scope.
  23185. *
  23186. * For best practices on using `ngModel`, see:
  23187. *
  23188. * - [Understanding Scopes](https://github.com/angular/angular.js/wiki/Understanding-Scopes)
  23189. *
  23190. * For basic examples, how to use `ngModel`, see:
  23191. *
  23192. * - {@link ng.directive:input input}
  23193. * - {@link input[text] text}
  23194. * - {@link input[checkbox] checkbox}
  23195. * - {@link input[radio] radio}
  23196. * - {@link input[number] number}
  23197. * - {@link input[email] email}
  23198. * - {@link input[url] url}
  23199. * - {@link input[date] date}
  23200. * - {@link input[datetime-local] datetime-local}
  23201. * - {@link input[time] time}
  23202. * - {@link input[month] month}
  23203. * - {@link input[week] week}
  23204. * - {@link ng.directive:select select}
  23205. * - {@link ng.directive:textarea textarea}
  23206. *
  23207. * # CSS classes
  23208. * The following CSS classes are added and removed on the associated input/select/textarea element
  23209. * depending on the validity of the model.
  23210. *
  23211. * - `ng-valid`: the model is valid
  23212. * - `ng-invalid`: the model is invalid
  23213. * - `ng-valid-[key]`: for each valid key added by `$setValidity`
  23214. * - `ng-invalid-[key]`: for each invalid key added by `$setValidity`
  23215. * - `ng-pristine`: the control hasn't been interacted with yet
  23216. * - `ng-dirty`: the control has been interacted with
  23217. * - `ng-touched`: the control has been blurred
  23218. * - `ng-untouched`: the control hasn't been blurred
  23219. * - `ng-pending`: any `$asyncValidators` are unfulfilled
  23220. *
  23221. * Keep in mind that ngAnimate can detect each of these classes when added and removed.
  23222. *
  23223. * ## Animation Hooks
  23224. *
  23225. * Animations within models are triggered when any of the associated CSS classes are added and removed
  23226. * on the input element which is attached to the model. These classes are: `.ng-pristine`, `.ng-dirty`,
  23227. * `.ng-invalid` and `.ng-valid` as well as any other validations that are performed on the model itself.
  23228. * The animations that are triggered within ngModel are similar to how they work in ngClass and
  23229. * animations can be hooked into using CSS transitions, keyframes as well as JS animations.
  23230. *
  23231. * The following example shows a simple way to utilize CSS transitions to style an input element
  23232. * that has been rendered as invalid after it has been validated:
  23233. *
  23234. * <pre>
  23235. * //be sure to include ngAnimate as a module to hook into more
  23236. * //advanced animations
  23237. * .my-input {
  23238. * transition:0.5s linear all;
  23239. * background: white;
  23240. * }
  23241. * .my-input.ng-invalid {
  23242. * background: red;
  23243. * color:white;
  23244. * }
  23245. * </pre>
  23246. *
  23247. * @example
  23248. * <example deps="angular-animate.js" animations="true" fixBase="true" module="inputExample">
  23249. <file name="index.html">
  23250. <script>
  23251. angular.module('inputExample', [])
  23252. .controller('ExampleController', ['$scope', function($scope) {
  23253. $scope.val = '1';
  23254. }]);
  23255. </script>
  23256. <style>
  23257. .my-input {
  23258. transition:all linear 0.5s;
  23259. background: transparent;
  23260. }
  23261. .my-input.ng-invalid {
  23262. color:white;
  23263. background: red;
  23264. }
  23265. </style>
  23266. <p id="inputDescription">
  23267. Update input to see transitions when valid/invalid.
  23268. Integer is a valid value.
  23269. </p>
  23270. <form name="testForm" ng-controller="ExampleController">
  23271. <input ng-model="val" ng-pattern="/^\d+$/" name="anim" class="my-input"
  23272. aria-describedby="inputDescription" />
  23273. </form>
  23274. </file>
  23275. * </example>
  23276. *
  23277. * ## Binding to a getter/setter
  23278. *
  23279. * Sometimes it's helpful to bind `ngModel` to a getter/setter function. A getter/setter is a
  23280. * function that returns a representation of the model when called with zero arguments, and sets
  23281. * the internal state of a model when called with an argument. It's sometimes useful to use this
  23282. * for models that have an internal representation that's different from what the model exposes
  23283. * to the view.
  23284. *
  23285. * <div class="alert alert-success">
  23286. * **Best Practice:** It's best to keep getters fast because Angular is likely to call them more
  23287. * frequently than other parts of your code.
  23288. * </div>
  23289. *
  23290. * You use this behavior by adding `ng-model-options="{ getterSetter: true }"` to an element that
  23291. * has `ng-model` attached to it. You can also add `ng-model-options="{ getterSetter: true }"` to
  23292. * a `<form>`, which will enable this behavior for all `<input>`s within it. See
  23293. * {@link ng.directive:ngModelOptions `ngModelOptions`} for more.
  23294. *
  23295. * The following example shows how to use `ngModel` with a getter/setter:
  23296. *
  23297. * @example
  23298. * <example name="ngModel-getter-setter" module="getterSetterExample">
  23299. <file name="index.html">
  23300. <div ng-controller="ExampleController">
  23301. <form name="userForm">
  23302. <label>Name:
  23303. <input type="text" name="userName"
  23304. ng-model="user.name"
  23305. ng-model-options="{ getterSetter: true }" />
  23306. </label>
  23307. </form>
  23308. <pre>user.name = <span ng-bind="user.name()"></span></pre>
  23309. </div>
  23310. </file>
  23311. <file name="app.js">
  23312. angular.module('getterSetterExample', [])
  23313. .controller('ExampleController', ['$scope', function($scope) {
  23314. var _name = 'Brian';
  23315. $scope.user = {
  23316. name: function(newName) {
  23317. // Note that newName can be undefined for two reasons:
  23318. // 1. Because it is called as a getter and thus called with no arguments
  23319. // 2. Because the property should actually be set to undefined. This happens e.g. if the
  23320. // input is invalid
  23321. return arguments.length ? (_name = newName) : _name;
  23322. }
  23323. };
  23324. }]);
  23325. </file>
  23326. * </example>
  23327. */
  23328. var ngModelDirective = ['$rootScope', function($rootScope) {
  23329. return {
  23330. restrict: 'A',
  23331. require: ['ngModel', '^?form', '^?ngModelOptions'],
  23332. controller: NgModelController,
  23333. // Prelink needs to run before any input directive
  23334. // so that we can set the NgModelOptions in NgModelController
  23335. // before anyone else uses it.
  23336. priority: 1,
  23337. compile: function ngModelCompile(element) {
  23338. // Setup initial state of the control
  23339. element.addClass(PRISTINE_CLASS).addClass(UNTOUCHED_CLASS).addClass(VALID_CLASS);
  23340. return {
  23341. pre: function ngModelPreLink(scope, element, attr, ctrls) {
  23342. var modelCtrl = ctrls[0],
  23343. formCtrl = ctrls[1] || modelCtrl.$$parentForm;
  23344. modelCtrl.$$setOptions(ctrls[2] && ctrls[2].$options);
  23345. // notify others, especially parent forms
  23346. formCtrl.$addControl(modelCtrl);
  23347. attr.$observe('name', function(newValue) {
  23348. if (modelCtrl.$name !== newValue) {
  23349. modelCtrl.$$parentForm.$$renameControl(modelCtrl, newValue);
  23350. }
  23351. });
  23352. scope.$on('$destroy', function() {
  23353. modelCtrl.$$parentForm.$removeControl(modelCtrl);
  23354. });
  23355. },
  23356. post: function ngModelPostLink(scope, element, attr, ctrls) {
  23357. var modelCtrl = ctrls[0];
  23358. if (modelCtrl.$options && modelCtrl.$options.updateOn) {
  23359. element.on(modelCtrl.$options.updateOn, function(ev) {
  23360. modelCtrl.$$debounceViewValueCommit(ev && ev.type);
  23361. });
  23362. }
  23363. element.on('blur', function(ev) {
  23364. if (modelCtrl.$touched) return;
  23365. if ($rootScope.$$phase) {
  23366. scope.$evalAsync(modelCtrl.$setTouched);
  23367. } else {
  23368. scope.$apply(modelCtrl.$setTouched);
  23369. }
  23370. });
  23371. }
  23372. };
  23373. }
  23374. };
  23375. }];
  23376. var DEFAULT_REGEXP = /(\s+|^)default(\s+|$)/;
  23377. /**
  23378. * @ngdoc directive
  23379. * @name ngModelOptions
  23380. *
  23381. * @description
  23382. * Allows tuning how model updates are done. Using `ngModelOptions` you can specify a custom list of
  23383. * events that will trigger a model update and/or a debouncing delay so that the actual update only
  23384. * takes place when a timer expires; this timer will be reset after another change takes place.
  23385. *
  23386. * Given the nature of `ngModelOptions`, the value displayed inside input fields in the view might
  23387. * be different from the value in the actual model. This means that if you update the model you
  23388. * should also invoke {@link ngModel.NgModelController `$rollbackViewValue`} on the relevant input field in
  23389. * order to make sure it is synchronized with the model and that any debounced action is canceled.
  23390. *
  23391. * The easiest way to reference the control's {@link ngModel.NgModelController `$rollbackViewValue`}
  23392. * method is by making sure the input is placed inside a form that has a `name` attribute. This is
  23393. * important because `form` controllers are published to the related scope under the name in their
  23394. * `name` attribute.
  23395. *
  23396. * Any pending changes will take place immediately when an enclosing form is submitted via the
  23397. * `submit` event. Note that `ngClick` events will occur before the model is updated. Use `ngSubmit`
  23398. * to have access to the updated model.
  23399. *
  23400. * `ngModelOptions` has an effect on the element it's declared on and its descendants.
  23401. *
  23402. * @param {Object} ngModelOptions options to apply to the current model. Valid keys are:
  23403. * - `updateOn`: string specifying which event should the input be bound to. You can set several
  23404. * events using an space delimited list. There is a special event called `default` that
  23405. * matches the default events belonging of the control.
  23406. * - `debounce`: integer value which contains the debounce model update value in milliseconds. A
  23407. * value of 0 triggers an immediate update. If an object is supplied instead, you can specify a
  23408. * custom value for each event. For example:
  23409. * `ng-model-options="{ updateOn: 'default blur', debounce: { 'default': 500, 'blur': 0 } }"`
  23410. * - `allowInvalid`: boolean value which indicates that the model can be set with values that did
  23411. * not validate correctly instead of the default behavior of setting the model to undefined.
  23412. * - `getterSetter`: boolean value which determines whether or not to treat functions bound to
  23413. `ngModel` as getters/setters.
  23414. * - `timezone`: Defines the timezone to be used to read/write the `Date` instance in the model for
  23415. * `<input type="date">`, `<input type="time">`, ... . It understands UTC/GMT and the
  23416. * continental US time zone abbreviations, but for general use, use a time zone offset, for
  23417. * example, `'+0430'` (4 hours, 30 minutes east of the Greenwich meridian)
  23418. * If not specified, the timezone of the browser will be used.
  23419. *
  23420. * @example
  23421. The following example shows how to override immediate updates. Changes on the inputs within the
  23422. form will update the model only when the control loses focus (blur event). If `escape` key is
  23423. pressed while the input field is focused, the value is reset to the value in the current model.
  23424. <example name="ngModelOptions-directive-blur" module="optionsExample">
  23425. <file name="index.html">
  23426. <div ng-controller="ExampleController">
  23427. <form name="userForm">
  23428. <label>Name:
  23429. <input type="text" name="userName"
  23430. ng-model="user.name"
  23431. ng-model-options="{ updateOn: 'blur' }"
  23432. ng-keyup="cancel($event)" />
  23433. </label><br />
  23434. <label>Other data:
  23435. <input type="text" ng-model="user.data" />
  23436. </label><br />
  23437. </form>
  23438. <pre>user.name = <span ng-bind="user.name"></span></pre>
  23439. </div>
  23440. </file>
  23441. <file name="app.js">
  23442. angular.module('optionsExample', [])
  23443. .controller('ExampleController', ['$scope', function($scope) {
  23444. $scope.user = { name: 'say', data: '' };
  23445. $scope.cancel = function(e) {
  23446. if (e.keyCode == 27) {
  23447. $scope.userForm.userName.$rollbackViewValue();
  23448. }
  23449. };
  23450. }]);
  23451. </file>
  23452. <file name="protractor.js" type="protractor">
  23453. var model = element(by.binding('user.name'));
  23454. var input = element(by.model('user.name'));
  23455. var other = element(by.model('user.data'));
  23456. it('should allow custom events', function() {
  23457. input.sendKeys(' hello');
  23458. input.click();
  23459. expect(model.getText()).toEqual('say');
  23460. other.click();
  23461. expect(model.getText()).toEqual('say hello');
  23462. });
  23463. it('should $rollbackViewValue when model changes', function() {
  23464. input.sendKeys(' hello');
  23465. expect(input.getAttribute('value')).toEqual('say hello');
  23466. input.sendKeys(protractor.Key.ESCAPE);
  23467. expect(input.getAttribute('value')).toEqual('say');
  23468. other.click();
  23469. expect(model.getText()).toEqual('say');
  23470. });
  23471. </file>
  23472. </example>
  23473. This one shows how to debounce model changes. Model will be updated only 1 sec after last change.
  23474. If the `Clear` button is pressed, any debounced action is canceled and the value becomes empty.
  23475. <example name="ngModelOptions-directive-debounce" module="optionsExample">
  23476. <file name="index.html">
  23477. <div ng-controller="ExampleController">
  23478. <form name="userForm">
  23479. <label>Name:
  23480. <input type="text" name="userName"
  23481. ng-model="user.name"
  23482. ng-model-options="{ debounce: 1000 }" />
  23483. </label>
  23484. <button ng-click="userForm.userName.$rollbackViewValue(); user.name=''">Clear</button>
  23485. <br />
  23486. </form>
  23487. <pre>user.name = <span ng-bind="user.name"></span></pre>
  23488. </div>
  23489. </file>
  23490. <file name="app.js">
  23491. angular.module('optionsExample', [])
  23492. .controller('ExampleController', ['$scope', function($scope) {
  23493. $scope.user = { name: 'say' };
  23494. }]);
  23495. </file>
  23496. </example>
  23497. This one shows how to bind to getter/setters:
  23498. <example name="ngModelOptions-directive-getter-setter" module="getterSetterExample">
  23499. <file name="index.html">
  23500. <div ng-controller="ExampleController">
  23501. <form name="userForm">
  23502. <label>Name:
  23503. <input type="text" name="userName"
  23504. ng-model="user.name"
  23505. ng-model-options="{ getterSetter: true }" />
  23506. </label>
  23507. </form>
  23508. <pre>user.name = <span ng-bind="user.name()"></span></pre>
  23509. </div>
  23510. </file>
  23511. <file name="app.js">
  23512. angular.module('getterSetterExample', [])
  23513. .controller('ExampleController', ['$scope', function($scope) {
  23514. var _name = 'Brian';
  23515. $scope.user = {
  23516. name: function(newName) {
  23517. // Note that newName can be undefined for two reasons:
  23518. // 1. Because it is called as a getter and thus called with no arguments
  23519. // 2. Because the property should actually be set to undefined. This happens e.g. if the
  23520. // input is invalid
  23521. return arguments.length ? (_name = newName) : _name;
  23522. }
  23523. };
  23524. }]);
  23525. </file>
  23526. </example>
  23527. */
  23528. var ngModelOptionsDirective = function() {
  23529. return {
  23530. restrict: 'A',
  23531. controller: ['$scope', '$attrs', function($scope, $attrs) {
  23532. var that = this;
  23533. this.$options = copy($scope.$eval($attrs.ngModelOptions));
  23534. // Allow adding/overriding bound events
  23535. if (isDefined(this.$options.updateOn)) {
  23536. this.$options.updateOnDefault = false;
  23537. // extract "default" pseudo-event from list of events that can trigger a model update
  23538. this.$options.updateOn = trim(this.$options.updateOn.replace(DEFAULT_REGEXP, function() {
  23539. that.$options.updateOnDefault = true;
  23540. return ' ';
  23541. }));
  23542. } else {
  23543. this.$options.updateOnDefault = true;
  23544. }
  23545. }]
  23546. };
  23547. };
  23548. // helper methods
  23549. function addSetValidityMethod(context) {
  23550. var ctrl = context.ctrl,
  23551. $element = context.$element,
  23552. classCache = {},
  23553. set = context.set,
  23554. unset = context.unset,
  23555. $animate = context.$animate;
  23556. classCache[INVALID_CLASS] = !(classCache[VALID_CLASS] = $element.hasClass(VALID_CLASS));
  23557. ctrl.$setValidity = setValidity;
  23558. function setValidity(validationErrorKey, state, controller) {
  23559. if (isUndefined(state)) {
  23560. createAndSet('$pending', validationErrorKey, controller);
  23561. } else {
  23562. unsetAndCleanup('$pending', validationErrorKey, controller);
  23563. }
  23564. if (!isBoolean(state)) {
  23565. unset(ctrl.$error, validationErrorKey, controller);
  23566. unset(ctrl.$$success, validationErrorKey, controller);
  23567. } else {
  23568. if (state) {
  23569. unset(ctrl.$error, validationErrorKey, controller);
  23570. set(ctrl.$$success, validationErrorKey, controller);
  23571. } else {
  23572. set(ctrl.$error, validationErrorKey, controller);
  23573. unset(ctrl.$$success, validationErrorKey, controller);
  23574. }
  23575. }
  23576. if (ctrl.$pending) {
  23577. cachedToggleClass(PENDING_CLASS, true);
  23578. ctrl.$valid = ctrl.$invalid = undefined;
  23579. toggleValidationCss('', null);
  23580. } else {
  23581. cachedToggleClass(PENDING_CLASS, false);
  23582. ctrl.$valid = isObjectEmpty(ctrl.$error);
  23583. ctrl.$invalid = !ctrl.$valid;
  23584. toggleValidationCss('', ctrl.$valid);
  23585. }
  23586. // re-read the state as the set/unset methods could have
  23587. // combined state in ctrl.$error[validationError] (used for forms),
  23588. // where setting/unsetting only increments/decrements the value,
  23589. // and does not replace it.
  23590. var combinedState;
  23591. if (ctrl.$pending && ctrl.$pending[validationErrorKey]) {
  23592. combinedState = undefined;
  23593. } else if (ctrl.$error[validationErrorKey]) {
  23594. combinedState = false;
  23595. } else if (ctrl.$$success[validationErrorKey]) {
  23596. combinedState = true;
  23597. } else {
  23598. combinedState = null;
  23599. }
  23600. toggleValidationCss(validationErrorKey, combinedState);
  23601. ctrl.$$parentForm.$setValidity(validationErrorKey, combinedState, ctrl);
  23602. }
  23603. function createAndSet(name, value, controller) {
  23604. if (!ctrl[name]) {
  23605. ctrl[name] = {};
  23606. }
  23607. set(ctrl[name], value, controller);
  23608. }
  23609. function unsetAndCleanup(name, value, controller) {
  23610. if (ctrl[name]) {
  23611. unset(ctrl[name], value, controller);
  23612. }
  23613. if (isObjectEmpty(ctrl[name])) {
  23614. ctrl[name] = undefined;
  23615. }
  23616. }
  23617. function cachedToggleClass(className, switchValue) {
  23618. if (switchValue && !classCache[className]) {
  23619. $animate.addClass($element, className);
  23620. classCache[className] = true;
  23621. } else if (!switchValue && classCache[className]) {
  23622. $animate.removeClass($element, className);
  23623. classCache[className] = false;
  23624. }
  23625. }
  23626. function toggleValidationCss(validationErrorKey, isValid) {
  23627. validationErrorKey = validationErrorKey ? '-' + snake_case(validationErrorKey, '-') : '';
  23628. cachedToggleClass(VALID_CLASS + validationErrorKey, isValid === true);
  23629. cachedToggleClass(INVALID_CLASS + validationErrorKey, isValid === false);
  23630. }
  23631. }
  23632. function isObjectEmpty(obj) {
  23633. if (obj) {
  23634. for (var prop in obj) {
  23635. if (obj.hasOwnProperty(prop)) {
  23636. return false;
  23637. }
  23638. }
  23639. }
  23640. return true;
  23641. }
  23642. /**
  23643. * @ngdoc directive
  23644. * @name ngNonBindable
  23645. * @restrict AC
  23646. * @priority 1000
  23647. *
  23648. * @description
  23649. * The `ngNonBindable` directive tells Angular not to compile or bind the contents of the current
  23650. * DOM element. This is useful if the element contains what appears to be Angular directives and
  23651. * bindings but which should be ignored by Angular. This could be the case if you have a site that
  23652. * displays snippets of code, for instance.
  23653. *
  23654. * @element ANY
  23655. *
  23656. * @example
  23657. * In this example there are two locations where a simple interpolation binding (`{{}}`) is present,
  23658. * but the one wrapped in `ngNonBindable` is left alone.
  23659. *
  23660. * @example
  23661. <example>
  23662. <file name="index.html">
  23663. <div>Normal: {{1 + 2}}</div>
  23664. <div ng-non-bindable>Ignored: {{1 + 2}}</div>
  23665. </file>
  23666. <file name="protractor.js" type="protractor">
  23667. it('should check ng-non-bindable', function() {
  23668. expect(element(by.binding('1 + 2')).getText()).toContain('3');
  23669. expect(element.all(by.css('div')).last().getText()).toMatch(/1 \+ 2/);
  23670. });
  23671. </file>
  23672. </example>
  23673. */
  23674. var ngNonBindableDirective = ngDirective({ terminal: true, priority: 1000 });
  23675. /* global jqLiteRemove */
  23676. var ngOptionsMinErr = minErr('ngOptions');
  23677. /**
  23678. * @ngdoc directive
  23679. * @name ngOptions
  23680. * @restrict A
  23681. *
  23682. * @description
  23683. *
  23684. * The `ngOptions` attribute can be used to dynamically generate a list of `<option>`
  23685. * elements for the `<select>` element using the array or object obtained by evaluating the
  23686. * `ngOptions` comprehension expression.
  23687. *
  23688. * In many cases, `ngRepeat` can be used on `<option>` elements instead of `ngOptions` to achieve a
  23689. * similar result. However, `ngOptions` provides some benefits such as reducing memory and
  23690. * increasing speed by not creating a new scope for each repeated instance, as well as providing
  23691. * more flexibility in how the `<select>`'s model is assigned via the `select` **`as`** part of the
  23692. * comprehension expression. `ngOptions` should be used when the `<select>` model needs to be bound
  23693. * to a non-string value. This is because an option element can only be bound to string values at
  23694. * present.
  23695. *
  23696. * When an item in the `<select>` menu is selected, the array element or object property
  23697. * represented by the selected option will be bound to the model identified by the `ngModel`
  23698. * directive.
  23699. *
  23700. * Optionally, a single hard-coded `<option>` element, with the value set to an empty string, can
  23701. * be nested into the `<select>` element. This element will then represent the `null` or "not selected"
  23702. * option. See example below for demonstration.
  23703. *
  23704. * ## Complex Models (objects or collections)
  23705. *
  23706. * **Note:** By default, `ngModel` watches the model by reference, not value. This is important when
  23707. * binding any input directive to a model that is an object or a collection.
  23708. *
  23709. * Since this is a common situation for `ngOptions` the directive additionally watches the model using
  23710. * `$watchCollection` when the select has the `multiple` attribute or when there is a `track by` clause in
  23711. * the options expression. This allows ngOptions to trigger a re-rendering of the options even if the actual
  23712. * object/collection has not changed identity but only a property on the object or an item in the collection
  23713. * changes.
  23714. *
  23715. * Note that `$watchCollection` does a shallow comparison of the properties of the object (or the items in the collection
  23716. * if the model is an array). This means that changing a property deeper inside the object/collection that the
  23717. * first level will not trigger a re-rendering.
  23718. *
  23719. *
  23720. * ## `select` **`as`**
  23721. *
  23722. * Using `select` **`as`** will bind the result of the `select` expression to the model, but
  23723. * the value of the `<select>` and `<option>` html elements will be either the index (for array data sources)
  23724. * or property name (for object data sources) of the value within the collection. If a **`track by`** expression
  23725. * is used, the result of that expression will be set as the value of the `option` and `select` elements.
  23726. *
  23727. *
  23728. * ### `select` **`as`** and **`track by`**
  23729. *
  23730. * <div class="alert alert-warning">
  23731. * Do not use `select` **`as`** and **`track by`** in the same expression. They are not designed to work together.
  23732. * </div>
  23733. *
  23734. * Consider the following example:
  23735. *
  23736. * ```html
  23737. * <select ng-options="item.subItem as item.label for item in values track by item.id" ng-model="selected"></select>
  23738. * ```
  23739. *
  23740. * ```js
  23741. * $scope.values = [{
  23742. * id: 1,
  23743. * label: 'aLabel',
  23744. * subItem: { name: 'aSubItem' }
  23745. * }, {
  23746. * id: 2,
  23747. * label: 'bLabel',
  23748. * subItem: { name: 'bSubItem' }
  23749. * }];
  23750. *
  23751. * $scope.selected = { name: 'aSubItem' };
  23752. * ```
  23753. *
  23754. * With the purpose of preserving the selection, the **`track by`** expression is always applied to the element
  23755. * of the data source (to `item` in this example). To calculate whether an element is selected, we do the
  23756. * following:
  23757. *
  23758. * 1. Apply **`track by`** to the elements in the array. In the example: `[1, 2]`
  23759. * 2. Apply **`track by`** to the already selected value in `ngModel`.
  23760. * In the example: this is not possible as **`track by`** refers to `item.id`, but the selected
  23761. * value from `ngModel` is `{name: 'aSubItem'}`, so the **`track by`** expression is applied to
  23762. * a wrong object, the selected element can't be found, `<select>` is always reset to the "not
  23763. * selected" option.
  23764. *
  23765. *
  23766. * @param {string} ngModel Assignable angular expression to data-bind to.
  23767. * @param {string=} name Property name of the form under which the control is published.
  23768. * @param {string=} required The control is considered valid only if value is entered.
  23769. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  23770. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  23771. * `required` when you want to data-bind to the `required` attribute.
  23772. * @param {comprehension_expression=} ngOptions in one of the following forms:
  23773. *
  23774. * * for array data sources:
  23775. * * `label` **`for`** `value` **`in`** `array`
  23776. * * `select` **`as`** `label` **`for`** `value` **`in`** `array`
  23777. * * `label` **`group by`** `group` **`for`** `value` **`in`** `array`
  23778. * * `label` **`disable when`** `disable` **`for`** `value` **`in`** `array`
  23779. * * `label` **`group by`** `group` **`for`** `value` **`in`** `array` **`track by`** `trackexpr`
  23780. * * `label` **`disable when`** `disable` **`for`** `value` **`in`** `array` **`track by`** `trackexpr`
  23781. * * `label` **`for`** `value` **`in`** `array` | orderBy:`orderexpr` **`track by`** `trackexpr`
  23782. * (for including a filter with `track by`)
  23783. * * for object data sources:
  23784. * * `label` **`for (`**`key` **`,`** `value`**`) in`** `object`
  23785. * * `select` **`as`** `label` **`for (`**`key` **`,`** `value`**`) in`** `object`
  23786. * * `label` **`group by`** `group` **`for (`**`key`**`,`** `value`**`) in`** `object`
  23787. * * `label` **`disable when`** `disable` **`for (`**`key`**`,`** `value`**`) in`** `object`
  23788. * * `select` **`as`** `label` **`group by`** `group`
  23789. * **`for` `(`**`key`**`,`** `value`**`) in`** `object`
  23790. * * `select` **`as`** `label` **`disable when`** `disable`
  23791. * **`for` `(`**`key`**`,`** `value`**`) in`** `object`
  23792. *
  23793. * Where:
  23794. *
  23795. * * `array` / `object`: an expression which evaluates to an array / object to iterate over.
  23796. * * `value`: local variable which will refer to each item in the `array` or each property value
  23797. * of `object` during iteration.
  23798. * * `key`: local variable which will refer to a property name in `object` during iteration.
  23799. * * `label`: The result of this expression will be the label for `<option>` element. The
  23800. * `expression` will most likely refer to the `value` variable (e.g. `value.propertyName`).
  23801. * * `select`: The result of this expression will be bound to the model of the parent `<select>`
  23802. * element. If not specified, `select` expression will default to `value`.
  23803. * * `group`: The result of this expression will be used to group options using the `<optgroup>`
  23804. * DOM element.
  23805. * * `disable`: The result of this expression will be used to disable the rendered `<option>`
  23806. * element. Return `true` to disable.
  23807. * * `trackexpr`: Used when working with an array of objects. The result of this expression will be
  23808. * used to identify the objects in the array. The `trackexpr` will most likely refer to the
  23809. * `value` variable (e.g. `value.propertyName`). With this the selection is preserved
  23810. * even when the options are recreated (e.g. reloaded from the server).
  23811. *
  23812. * @example
  23813. <example module="selectExample">
  23814. <file name="index.html">
  23815. <script>
  23816. angular.module('selectExample', [])
  23817. .controller('ExampleController', ['$scope', function($scope) {
  23818. $scope.colors = [
  23819. {name:'black', shade:'dark'},
  23820. {name:'white', shade:'light', notAnOption: true},
  23821. {name:'red', shade:'dark'},
  23822. {name:'blue', shade:'dark', notAnOption: true},
  23823. {name:'yellow', shade:'light', notAnOption: false}
  23824. ];
  23825. $scope.myColor = $scope.colors[2]; // red
  23826. }]);
  23827. </script>
  23828. <div ng-controller="ExampleController">
  23829. <ul>
  23830. <li ng-repeat="color in colors">
  23831. <label>Name: <input ng-model="color.name"></label>
  23832. <label><input type="checkbox" ng-model="color.notAnOption"> Disabled?</label>
  23833. <button ng-click="colors.splice($index, 1)" aria-label="Remove">X</button>
  23834. </li>
  23835. <li>
  23836. <button ng-click="colors.push({})">add</button>
  23837. </li>
  23838. </ul>
  23839. <hr/>
  23840. <label>Color (null not allowed):
  23841. <select ng-model="myColor" ng-options="color.name for color in colors"></select>
  23842. </label><br/>
  23843. <label>Color (null allowed):
  23844. <span class="nullable">
  23845. <select ng-model="myColor" ng-options="color.name for color in colors">
  23846. <option value="">-- choose color --</option>
  23847. </select>
  23848. </span></label><br/>
  23849. <label>Color grouped by shade:
  23850. <select ng-model="myColor" ng-options="color.name group by color.shade for color in colors">
  23851. </select>
  23852. </label><br/>
  23853. <label>Color grouped by shade, with some disabled:
  23854. <select ng-model="myColor"
  23855. ng-options="color.name group by color.shade disable when color.notAnOption for color in colors">
  23856. </select>
  23857. </label><br/>
  23858. Select <button ng-click="myColor = { name:'not in list', shade: 'other' }">bogus</button>.
  23859. <br/>
  23860. <hr/>
  23861. Currently selected: {{ {selected_color:myColor} }}
  23862. <div style="border:solid 1px black; height:20px"
  23863. ng-style="{'background-color':myColor.name}">
  23864. </div>
  23865. </div>
  23866. </file>
  23867. <file name="protractor.js" type="protractor">
  23868. it('should check ng-options', function() {
  23869. expect(element(by.binding('{selected_color:myColor}')).getText()).toMatch('red');
  23870. element.all(by.model('myColor')).first().click();
  23871. element.all(by.css('select[ng-model="myColor"] option')).first().click();
  23872. expect(element(by.binding('{selected_color:myColor}')).getText()).toMatch('black');
  23873. element(by.css('.nullable select[ng-model="myColor"]')).click();
  23874. element.all(by.css('.nullable select[ng-model="myColor"] option')).first().click();
  23875. expect(element(by.binding('{selected_color:myColor}')).getText()).toMatch('null');
  23876. });
  23877. </file>
  23878. </example>
  23879. */
  23880. // jshint maxlen: false
  23881. // //00001111111111000000000002222222222000000000000000000000333333333300000000000000000000000004444444444400000000000005555555555555550000000006666666666666660000000777777777777777000000000000000888888888800000000000000000009999999999
  23882. var NG_OPTIONS_REGEXP = /^\s*([\s\S]+?)(?:\s+as\s+([\s\S]+?))?(?:\s+group\s+by\s+([\s\S]+?))?(?:\s+disable\s+when\s+([\s\S]+?))?\s+for\s+(?:([\$\w][\$\w]*)|(?:\(\s*([\$\w][\$\w]*)\s*,\s*([\$\w][\$\w]*)\s*\)))\s+in\s+([\s\S]+?)(?:\s+track\s+by\s+([\s\S]+?))?$/;
  23883. // 1: value expression (valueFn)
  23884. // 2: label expression (displayFn)
  23885. // 3: group by expression (groupByFn)
  23886. // 4: disable when expression (disableWhenFn)
  23887. // 5: array item variable name
  23888. // 6: object item key variable name
  23889. // 7: object item value variable name
  23890. // 8: collection expression
  23891. // 9: track by expression
  23892. // jshint maxlen: 100
  23893. var ngOptionsDirective = ['$compile', '$parse', function($compile, $parse) {
  23894. function parseOptionsExpression(optionsExp, selectElement, scope) {
  23895. var match = optionsExp.match(NG_OPTIONS_REGEXP);
  23896. if (!(match)) {
  23897. throw ngOptionsMinErr('iexp',
  23898. "Expected expression in form of " +
  23899. "'_select_ (as _label_)? for (_key_,)?_value_ in _collection_'" +
  23900. " but got '{0}'. Element: {1}",
  23901. optionsExp, startingTag(selectElement));
  23902. }
  23903. // Extract the parts from the ngOptions expression
  23904. // The variable name for the value of the item in the collection
  23905. var valueName = match[5] || match[7];
  23906. // The variable name for the key of the item in the collection
  23907. var keyName = match[6];
  23908. // An expression that generates the viewValue for an option if there is a label expression
  23909. var selectAs = / as /.test(match[0]) && match[1];
  23910. // An expression that is used to track the id of each object in the options collection
  23911. var trackBy = match[9];
  23912. // An expression that generates the viewValue for an option if there is no label expression
  23913. var valueFn = $parse(match[2] ? match[1] : valueName);
  23914. var selectAsFn = selectAs && $parse(selectAs);
  23915. var viewValueFn = selectAsFn || valueFn;
  23916. var trackByFn = trackBy && $parse(trackBy);
  23917. // Get the value by which we are going to track the option
  23918. // if we have a trackFn then use that (passing scope and locals)
  23919. // otherwise just hash the given viewValue
  23920. var getTrackByValueFn = trackBy ?
  23921. function(value, locals) { return trackByFn(scope, locals); } :
  23922. function getHashOfValue(value) { return hashKey(value); };
  23923. var getTrackByValue = function(value, key) {
  23924. return getTrackByValueFn(value, getLocals(value, key));
  23925. };
  23926. var displayFn = $parse(match[2] || match[1]);
  23927. var groupByFn = $parse(match[3] || '');
  23928. var disableWhenFn = $parse(match[4] || '');
  23929. var valuesFn = $parse(match[8]);
  23930. var locals = {};
  23931. var getLocals = keyName ? function(value, key) {
  23932. locals[keyName] = key;
  23933. locals[valueName] = value;
  23934. return locals;
  23935. } : function(value) {
  23936. locals[valueName] = value;
  23937. return locals;
  23938. };
  23939. function Option(selectValue, viewValue, label, group, disabled) {
  23940. this.selectValue = selectValue;
  23941. this.viewValue = viewValue;
  23942. this.label = label;
  23943. this.group = group;
  23944. this.disabled = disabled;
  23945. }
  23946. function getOptionValuesKeys(optionValues) {
  23947. var optionValuesKeys;
  23948. if (!keyName && isArrayLike(optionValues)) {
  23949. optionValuesKeys = optionValues;
  23950. } else {
  23951. // if object, extract keys, in enumeration order, unsorted
  23952. optionValuesKeys = [];
  23953. for (var itemKey in optionValues) {
  23954. if (optionValues.hasOwnProperty(itemKey) && itemKey.charAt(0) !== '$') {
  23955. optionValuesKeys.push(itemKey);
  23956. }
  23957. }
  23958. }
  23959. return optionValuesKeys;
  23960. }
  23961. return {
  23962. trackBy: trackBy,
  23963. getTrackByValue: getTrackByValue,
  23964. getWatchables: $parse(valuesFn, function(optionValues) {
  23965. // Create a collection of things that we would like to watch (watchedArray)
  23966. // so that they can all be watched using a single $watchCollection
  23967. // that only runs the handler once if anything changes
  23968. var watchedArray = [];
  23969. optionValues = optionValues || [];
  23970. var optionValuesKeys = getOptionValuesKeys(optionValues);
  23971. var optionValuesLength = optionValuesKeys.length;
  23972. for (var index = 0; index < optionValuesLength; index++) {
  23973. var key = (optionValues === optionValuesKeys) ? index : optionValuesKeys[index];
  23974. var value = optionValues[key];
  23975. var locals = getLocals(optionValues[key], key);
  23976. var selectValue = getTrackByValueFn(optionValues[key], locals);
  23977. watchedArray.push(selectValue);
  23978. // Only need to watch the displayFn if there is a specific label expression
  23979. if (match[2] || match[1]) {
  23980. var label = displayFn(scope, locals);
  23981. watchedArray.push(label);
  23982. }
  23983. // Only need to watch the disableWhenFn if there is a specific disable expression
  23984. if (match[4]) {
  23985. var disableWhen = disableWhenFn(scope, locals);
  23986. watchedArray.push(disableWhen);
  23987. }
  23988. }
  23989. return watchedArray;
  23990. }),
  23991. getOptions: function() {
  23992. var optionItems = [];
  23993. var selectValueMap = {};
  23994. // The option values were already computed in the `getWatchables` fn,
  23995. // which must have been called to trigger `getOptions`
  23996. var optionValues = valuesFn(scope) || [];
  23997. var optionValuesKeys = getOptionValuesKeys(optionValues);
  23998. var optionValuesLength = optionValuesKeys.length;
  23999. for (var index = 0; index < optionValuesLength; index++) {
  24000. var key = (optionValues === optionValuesKeys) ? index : optionValuesKeys[index];
  24001. var value = optionValues[key];
  24002. var locals = getLocals(value, key);
  24003. var viewValue = viewValueFn(scope, locals);
  24004. var selectValue = getTrackByValueFn(viewValue, locals);
  24005. var label = displayFn(scope, locals);
  24006. var group = groupByFn(scope, locals);
  24007. var disabled = disableWhenFn(scope, locals);
  24008. var optionItem = new Option(selectValue, viewValue, label, group, disabled);
  24009. optionItems.push(optionItem);
  24010. selectValueMap[selectValue] = optionItem;
  24011. }
  24012. return {
  24013. items: optionItems,
  24014. selectValueMap: selectValueMap,
  24015. getOptionFromViewValue: function(value) {
  24016. return selectValueMap[getTrackByValue(value)];
  24017. },
  24018. getViewValueFromOption: function(option) {
  24019. // If the viewValue could be an object that may be mutated by the application,
  24020. // we need to make a copy and not return the reference to the value on the option.
  24021. return trackBy ? angular.copy(option.viewValue) : option.viewValue;
  24022. }
  24023. };
  24024. }
  24025. };
  24026. }
  24027. // we can't just jqLite('<option>') since jqLite is not smart enough
  24028. // to create it in <select> and IE barfs otherwise.
  24029. var optionTemplate = document.createElement('option'),
  24030. optGroupTemplate = document.createElement('optgroup');
  24031. return {
  24032. restrict: 'A',
  24033. terminal: true,
  24034. require: ['select', '?ngModel'],
  24035. link: function(scope, selectElement, attr, ctrls) {
  24036. // if ngModel is not defined, we don't need to do anything
  24037. var ngModelCtrl = ctrls[1];
  24038. if (!ngModelCtrl) return;
  24039. var selectCtrl = ctrls[0];
  24040. var multiple = attr.multiple;
  24041. // The emptyOption allows the application developer to provide their own custom "empty"
  24042. // option when the viewValue does not match any of the option values.
  24043. var emptyOption;
  24044. for (var i = 0, children = selectElement.children(), ii = children.length; i < ii; i++) {
  24045. if (children[i].value === '') {
  24046. emptyOption = children.eq(i);
  24047. break;
  24048. }
  24049. }
  24050. var providedEmptyOption = !!emptyOption;
  24051. var unknownOption = jqLite(optionTemplate.cloneNode(false));
  24052. unknownOption.val('?');
  24053. var options;
  24054. var ngOptions = parseOptionsExpression(attr.ngOptions, selectElement, scope);
  24055. var renderEmptyOption = function() {
  24056. if (!providedEmptyOption) {
  24057. selectElement.prepend(emptyOption);
  24058. }
  24059. selectElement.val('');
  24060. emptyOption.prop('selected', true); // needed for IE
  24061. emptyOption.attr('selected', true);
  24062. };
  24063. var removeEmptyOption = function() {
  24064. if (!providedEmptyOption) {
  24065. emptyOption.remove();
  24066. }
  24067. };
  24068. var renderUnknownOption = function() {
  24069. selectElement.prepend(unknownOption);
  24070. selectElement.val('?');
  24071. unknownOption.prop('selected', true); // needed for IE
  24072. unknownOption.attr('selected', true);
  24073. };
  24074. var removeUnknownOption = function() {
  24075. unknownOption.remove();
  24076. };
  24077. // Update the controller methods for multiple selectable options
  24078. if (!multiple) {
  24079. selectCtrl.writeValue = function writeNgOptionsValue(value) {
  24080. var option = options.getOptionFromViewValue(value);
  24081. if (option && !option.disabled) {
  24082. if (selectElement[0].value !== option.selectValue) {
  24083. removeUnknownOption();
  24084. removeEmptyOption();
  24085. selectElement[0].value = option.selectValue;
  24086. option.element.selected = true;
  24087. option.element.setAttribute('selected', 'selected');
  24088. }
  24089. } else {
  24090. if (value === null || providedEmptyOption) {
  24091. removeUnknownOption();
  24092. renderEmptyOption();
  24093. } else {
  24094. removeEmptyOption();
  24095. renderUnknownOption();
  24096. }
  24097. }
  24098. };
  24099. selectCtrl.readValue = function readNgOptionsValue() {
  24100. var selectedOption = options.selectValueMap[selectElement.val()];
  24101. if (selectedOption && !selectedOption.disabled) {
  24102. removeEmptyOption();
  24103. removeUnknownOption();
  24104. return options.getViewValueFromOption(selectedOption);
  24105. }
  24106. return null;
  24107. };
  24108. // If we are using `track by` then we must watch the tracked value on the model
  24109. // since ngModel only watches for object identity change
  24110. if (ngOptions.trackBy) {
  24111. scope.$watch(
  24112. function() { return ngOptions.getTrackByValue(ngModelCtrl.$viewValue); },
  24113. function() { ngModelCtrl.$render(); }
  24114. );
  24115. }
  24116. } else {
  24117. ngModelCtrl.$isEmpty = function(value) {
  24118. return !value || value.length === 0;
  24119. };
  24120. selectCtrl.writeValue = function writeNgOptionsMultiple(value) {
  24121. options.items.forEach(function(option) {
  24122. option.element.selected = false;
  24123. });
  24124. if (value) {
  24125. value.forEach(function(item) {
  24126. var option = options.getOptionFromViewValue(item);
  24127. if (option && !option.disabled) option.element.selected = true;
  24128. });
  24129. }
  24130. };
  24131. selectCtrl.readValue = function readNgOptionsMultiple() {
  24132. var selectedValues = selectElement.val() || [],
  24133. selections = [];
  24134. forEach(selectedValues, function(value) {
  24135. var option = options.selectValueMap[value];
  24136. if (option && !option.disabled) selections.push(options.getViewValueFromOption(option));
  24137. });
  24138. return selections;
  24139. };
  24140. // If we are using `track by` then we must watch these tracked values on the model
  24141. // since ngModel only watches for object identity change
  24142. if (ngOptions.trackBy) {
  24143. scope.$watchCollection(function() {
  24144. if (isArray(ngModelCtrl.$viewValue)) {
  24145. return ngModelCtrl.$viewValue.map(function(value) {
  24146. return ngOptions.getTrackByValue(value);
  24147. });
  24148. }
  24149. }, function() {
  24150. ngModelCtrl.$render();
  24151. });
  24152. }
  24153. }
  24154. if (providedEmptyOption) {
  24155. // we need to remove it before calling selectElement.empty() because otherwise IE will
  24156. // remove the label from the element. wtf?
  24157. emptyOption.remove();
  24158. // compile the element since there might be bindings in it
  24159. $compile(emptyOption)(scope);
  24160. // remove the class, which is added automatically because we recompile the element and it
  24161. // becomes the compilation root
  24162. emptyOption.removeClass('ng-scope');
  24163. } else {
  24164. emptyOption = jqLite(optionTemplate.cloneNode(false));
  24165. }
  24166. // We need to do this here to ensure that the options object is defined
  24167. // when we first hit it in writeNgOptionsValue
  24168. updateOptions();
  24169. // We will re-render the option elements if the option values or labels change
  24170. scope.$watchCollection(ngOptions.getWatchables, updateOptions);
  24171. // ------------------------------------------------------------------ //
  24172. function updateOptionElement(option, element) {
  24173. option.element = element;
  24174. element.disabled = option.disabled;
  24175. if (option.value !== element.value) element.value = option.selectValue;
  24176. if (option.label !== element.label) {
  24177. element.label = option.label;
  24178. element.textContent = option.label;
  24179. }
  24180. }
  24181. function addOrReuseElement(parent, current, type, templateElement) {
  24182. var element;
  24183. // Check whether we can reuse the next element
  24184. if (current && lowercase(current.nodeName) === type) {
  24185. // The next element is the right type so reuse it
  24186. element = current;
  24187. } else {
  24188. // The next element is not the right type so create a new one
  24189. element = templateElement.cloneNode(false);
  24190. if (!current) {
  24191. // There are no more elements so just append it to the select
  24192. parent.appendChild(element);
  24193. } else {
  24194. // The next element is not a group so insert the new one
  24195. parent.insertBefore(element, current);
  24196. }
  24197. }
  24198. return element;
  24199. }
  24200. function removeExcessElements(current) {
  24201. var next;
  24202. while (current) {
  24203. next = current.nextSibling;
  24204. jqLiteRemove(current);
  24205. current = next;
  24206. }
  24207. }
  24208. function skipEmptyAndUnknownOptions(current) {
  24209. var emptyOption_ = emptyOption && emptyOption[0];
  24210. var unknownOption_ = unknownOption && unknownOption[0];
  24211. if (emptyOption_ || unknownOption_) {
  24212. while (current &&
  24213. (current === emptyOption_ ||
  24214. current === unknownOption_)) {
  24215. current = current.nextSibling;
  24216. }
  24217. }
  24218. return current;
  24219. }
  24220. function updateOptions() {
  24221. var previousValue = options && selectCtrl.readValue();
  24222. options = ngOptions.getOptions();
  24223. var groupMap = {};
  24224. var currentElement = selectElement[0].firstChild;
  24225. // Ensure that the empty option is always there if it was explicitly provided
  24226. if (providedEmptyOption) {
  24227. selectElement.prepend(emptyOption);
  24228. }
  24229. currentElement = skipEmptyAndUnknownOptions(currentElement);
  24230. options.items.forEach(function updateOption(option) {
  24231. var group;
  24232. var groupElement;
  24233. var optionElement;
  24234. if (option.group) {
  24235. // This option is to live in a group
  24236. // See if we have already created this group
  24237. group = groupMap[option.group];
  24238. if (!group) {
  24239. // We have not already created this group
  24240. groupElement = addOrReuseElement(selectElement[0],
  24241. currentElement,
  24242. 'optgroup',
  24243. optGroupTemplate);
  24244. // Move to the next element
  24245. currentElement = groupElement.nextSibling;
  24246. // Update the label on the group element
  24247. groupElement.label = option.group;
  24248. // Store it for use later
  24249. group = groupMap[option.group] = {
  24250. groupElement: groupElement,
  24251. currentOptionElement: groupElement.firstChild
  24252. };
  24253. }
  24254. // So now we have a group for this option we add the option to the group
  24255. optionElement = addOrReuseElement(group.groupElement,
  24256. group.currentOptionElement,
  24257. 'option',
  24258. optionTemplate);
  24259. updateOptionElement(option, optionElement);
  24260. // Move to the next element
  24261. group.currentOptionElement = optionElement.nextSibling;
  24262. } else {
  24263. // This option is not in a group
  24264. optionElement = addOrReuseElement(selectElement[0],
  24265. currentElement,
  24266. 'option',
  24267. optionTemplate);
  24268. updateOptionElement(option, optionElement);
  24269. // Move to the next element
  24270. currentElement = optionElement.nextSibling;
  24271. }
  24272. });
  24273. // Now remove all excess options and group
  24274. Object.keys(groupMap).forEach(function(key) {
  24275. removeExcessElements(groupMap[key].currentOptionElement);
  24276. });
  24277. removeExcessElements(currentElement);
  24278. ngModelCtrl.$render();
  24279. // Check to see if the value has changed due to the update to the options
  24280. if (!ngModelCtrl.$isEmpty(previousValue)) {
  24281. var nextValue = selectCtrl.readValue();
  24282. if (ngOptions.trackBy ? !equals(previousValue, nextValue) : previousValue !== nextValue) {
  24283. ngModelCtrl.$setViewValue(nextValue);
  24284. ngModelCtrl.$render();
  24285. }
  24286. }
  24287. }
  24288. }
  24289. };
  24290. }];
  24291. /**
  24292. * @ngdoc directive
  24293. * @name ngPluralize
  24294. * @restrict EA
  24295. *
  24296. * @description
  24297. * `ngPluralize` is a directive that displays messages according to en-US localization rules.
  24298. * These rules are bundled with angular.js, but can be overridden
  24299. * (see {@link guide/i18n Angular i18n} dev guide). You configure ngPluralize directive
  24300. * by specifying the mappings between
  24301. * [plural categories](http://unicode.org/repos/cldr-tmp/trunk/diff/supplemental/language_plural_rules.html)
  24302. * and the strings to be displayed.
  24303. *
  24304. * # Plural categories and explicit number rules
  24305. * There are two
  24306. * [plural categories](http://unicode.org/repos/cldr-tmp/trunk/diff/supplemental/language_plural_rules.html)
  24307. * in Angular's default en-US locale: "one" and "other".
  24308. *
  24309. * While a plural category may match many numbers (for example, in en-US locale, "other" can match
  24310. * any number that is not 1), an explicit number rule can only match one number. For example, the
  24311. * explicit number rule for "3" matches the number 3. There are examples of plural categories
  24312. * and explicit number rules throughout the rest of this documentation.
  24313. *
  24314. * # Configuring ngPluralize
  24315. * You configure ngPluralize by providing 2 attributes: `count` and `when`.
  24316. * You can also provide an optional attribute, `offset`.
  24317. *
  24318. * The value of the `count` attribute can be either a string or an {@link guide/expression
  24319. * Angular expression}; these are evaluated on the current scope for its bound value.
  24320. *
  24321. * The `when` attribute specifies the mappings between plural categories and the actual
  24322. * string to be displayed. The value of the attribute should be a JSON object.
  24323. *
  24324. * The following example shows how to configure ngPluralize:
  24325. *
  24326. * ```html
  24327. * <ng-pluralize count="personCount"
  24328. when="{'0': 'Nobody is viewing.',
  24329. * 'one': '1 person is viewing.',
  24330. * 'other': '{} people are viewing.'}">
  24331. * </ng-pluralize>
  24332. *```
  24333. *
  24334. * In the example, `"0: Nobody is viewing."` is an explicit number rule. If you did not
  24335. * specify this rule, 0 would be matched to the "other" category and "0 people are viewing"
  24336. * would be shown instead of "Nobody is viewing". You can specify an explicit number rule for
  24337. * other numbers, for example 12, so that instead of showing "12 people are viewing", you can
  24338. * show "a dozen people are viewing".
  24339. *
  24340. * You can use a set of closed braces (`{}`) as a placeholder for the number that you want substituted
  24341. * into pluralized strings. In the previous example, Angular will replace `{}` with
  24342. * <span ng-non-bindable>`{{personCount}}`</span>. The closed braces `{}` is a placeholder
  24343. * for <span ng-non-bindable>{{numberExpression}}</span>.
  24344. *
  24345. * If no rule is defined for a category, then an empty string is displayed and a warning is generated.
  24346. * Note that some locales define more categories than `one` and `other`. For example, fr-fr defines `few` and `many`.
  24347. *
  24348. * # Configuring ngPluralize with offset
  24349. * The `offset` attribute allows further customization of pluralized text, which can result in
  24350. * a better user experience. For example, instead of the message "4 people are viewing this document",
  24351. * you might display "John, Kate and 2 others are viewing this document".
  24352. * The offset attribute allows you to offset a number by any desired value.
  24353. * Let's take a look at an example:
  24354. *
  24355. * ```html
  24356. * <ng-pluralize count="personCount" offset=2
  24357. * when="{'0': 'Nobody is viewing.',
  24358. * '1': '{{person1}} is viewing.',
  24359. * '2': '{{person1}} and {{person2}} are viewing.',
  24360. * 'one': '{{person1}}, {{person2}} and one other person are viewing.',
  24361. * 'other': '{{person1}}, {{person2}} and {} other people are viewing.'}">
  24362. * </ng-pluralize>
  24363. * ```
  24364. *
  24365. * Notice that we are still using two plural categories(one, other), but we added
  24366. * three explicit number rules 0, 1 and 2.
  24367. * When one person, perhaps John, views the document, "John is viewing" will be shown.
  24368. * When three people view the document, no explicit number rule is found, so
  24369. * an offset of 2 is taken off 3, and Angular uses 1 to decide the plural category.
  24370. * In this case, plural category 'one' is matched and "John, Mary and one other person are viewing"
  24371. * is shown.
  24372. *
  24373. * Note that when you specify offsets, you must provide explicit number rules for
  24374. * numbers from 0 up to and including the offset. If you use an offset of 3, for example,
  24375. * you must provide explicit number rules for 0, 1, 2 and 3. You must also provide plural strings for
  24376. * plural categories "one" and "other".
  24377. *
  24378. * @param {string|expression} count The variable to be bound to.
  24379. * @param {string} when The mapping between plural category to its corresponding strings.
  24380. * @param {number=} offset Offset to deduct from the total number.
  24381. *
  24382. * @example
  24383. <example module="pluralizeExample">
  24384. <file name="index.html">
  24385. <script>
  24386. angular.module('pluralizeExample', [])
  24387. .controller('ExampleController', ['$scope', function($scope) {
  24388. $scope.person1 = 'Igor';
  24389. $scope.person2 = 'Misko';
  24390. $scope.personCount = 1;
  24391. }]);
  24392. </script>
  24393. <div ng-controller="ExampleController">
  24394. <label>Person 1:<input type="text" ng-model="person1" value="Igor" /></label><br/>
  24395. <label>Person 2:<input type="text" ng-model="person2" value="Misko" /></label><br/>
  24396. <label>Number of People:<input type="text" ng-model="personCount" value="1" /></label><br/>
  24397. <!--- Example with simple pluralization rules for en locale --->
  24398. Without Offset:
  24399. <ng-pluralize count="personCount"
  24400. when="{'0': 'Nobody is viewing.',
  24401. 'one': '1 person is viewing.',
  24402. 'other': '{} people are viewing.'}">
  24403. </ng-pluralize><br>
  24404. <!--- Example with offset --->
  24405. With Offset(2):
  24406. <ng-pluralize count="personCount" offset=2
  24407. when="{'0': 'Nobody is viewing.',
  24408. '1': '{{person1}} is viewing.',
  24409. '2': '{{person1}} and {{person2}} are viewing.',
  24410. 'one': '{{person1}}, {{person2}} and one other person are viewing.',
  24411. 'other': '{{person1}}, {{person2}} and {} other people are viewing.'}">
  24412. </ng-pluralize>
  24413. </div>
  24414. </file>
  24415. <file name="protractor.js" type="protractor">
  24416. it('should show correct pluralized string', function() {
  24417. var withoutOffset = element.all(by.css('ng-pluralize')).get(0);
  24418. var withOffset = element.all(by.css('ng-pluralize')).get(1);
  24419. var countInput = element(by.model('personCount'));
  24420. expect(withoutOffset.getText()).toEqual('1 person is viewing.');
  24421. expect(withOffset.getText()).toEqual('Igor is viewing.');
  24422. countInput.clear();
  24423. countInput.sendKeys('0');
  24424. expect(withoutOffset.getText()).toEqual('Nobody is viewing.');
  24425. expect(withOffset.getText()).toEqual('Nobody is viewing.');
  24426. countInput.clear();
  24427. countInput.sendKeys('2');
  24428. expect(withoutOffset.getText()).toEqual('2 people are viewing.');
  24429. expect(withOffset.getText()).toEqual('Igor and Misko are viewing.');
  24430. countInput.clear();
  24431. countInput.sendKeys('3');
  24432. expect(withoutOffset.getText()).toEqual('3 people are viewing.');
  24433. expect(withOffset.getText()).toEqual('Igor, Misko and one other person are viewing.');
  24434. countInput.clear();
  24435. countInput.sendKeys('4');
  24436. expect(withoutOffset.getText()).toEqual('4 people are viewing.');
  24437. expect(withOffset.getText()).toEqual('Igor, Misko and 2 other people are viewing.');
  24438. });
  24439. it('should show data-bound names', function() {
  24440. var withOffset = element.all(by.css('ng-pluralize')).get(1);
  24441. var personCount = element(by.model('personCount'));
  24442. var person1 = element(by.model('person1'));
  24443. var person2 = element(by.model('person2'));
  24444. personCount.clear();
  24445. personCount.sendKeys('4');
  24446. person1.clear();
  24447. person1.sendKeys('Di');
  24448. person2.clear();
  24449. person2.sendKeys('Vojta');
  24450. expect(withOffset.getText()).toEqual('Di, Vojta and 2 other people are viewing.');
  24451. });
  24452. </file>
  24453. </example>
  24454. */
  24455. var ngPluralizeDirective = ['$locale', '$interpolate', '$log', function($locale, $interpolate, $log) {
  24456. var BRACE = /{}/g,
  24457. IS_WHEN = /^when(Minus)?(.+)$/;
  24458. return {
  24459. link: function(scope, element, attr) {
  24460. var numberExp = attr.count,
  24461. whenExp = attr.$attr.when && element.attr(attr.$attr.when), // we have {{}} in attrs
  24462. offset = attr.offset || 0,
  24463. whens = scope.$eval(whenExp) || {},
  24464. whensExpFns = {},
  24465. startSymbol = $interpolate.startSymbol(),
  24466. endSymbol = $interpolate.endSymbol(),
  24467. braceReplacement = startSymbol + numberExp + '-' + offset + endSymbol,
  24468. watchRemover = angular.noop,
  24469. lastCount;
  24470. forEach(attr, function(expression, attributeName) {
  24471. var tmpMatch = IS_WHEN.exec(attributeName);
  24472. if (tmpMatch) {
  24473. var whenKey = (tmpMatch[1] ? '-' : '') + lowercase(tmpMatch[2]);
  24474. whens[whenKey] = element.attr(attr.$attr[attributeName]);
  24475. }
  24476. });
  24477. forEach(whens, function(expression, key) {
  24478. whensExpFns[key] = $interpolate(expression.replace(BRACE, braceReplacement));
  24479. });
  24480. scope.$watch(numberExp, function ngPluralizeWatchAction(newVal) {
  24481. var count = parseFloat(newVal);
  24482. var countIsNaN = isNaN(count);
  24483. if (!countIsNaN && !(count in whens)) {
  24484. // If an explicit number rule such as 1, 2, 3... is defined, just use it.
  24485. // Otherwise, check it against pluralization rules in $locale service.
  24486. count = $locale.pluralCat(count - offset);
  24487. }
  24488. // If both `count` and `lastCount` are NaN, we don't need to re-register a watch.
  24489. // In JS `NaN !== NaN`, so we have to exlicitly check.
  24490. if ((count !== lastCount) && !(countIsNaN && isNumber(lastCount) && isNaN(lastCount))) {
  24491. watchRemover();
  24492. var whenExpFn = whensExpFns[count];
  24493. if (isUndefined(whenExpFn)) {
  24494. if (newVal != null) {
  24495. $log.debug("ngPluralize: no rule defined for '" + count + "' in " + whenExp);
  24496. }
  24497. watchRemover = noop;
  24498. updateElementText();
  24499. } else {
  24500. watchRemover = scope.$watch(whenExpFn, updateElementText);
  24501. }
  24502. lastCount = count;
  24503. }
  24504. });
  24505. function updateElementText(newText) {
  24506. element.text(newText || '');
  24507. }
  24508. }
  24509. };
  24510. }];
  24511. /**
  24512. * @ngdoc directive
  24513. * @name ngRepeat
  24514. * @multiElement
  24515. *
  24516. * @description
  24517. * The `ngRepeat` directive instantiates a template once per item from a collection. Each template
  24518. * instance gets its own scope, where the given loop variable is set to the current collection item,
  24519. * and `$index` is set to the item index or key.
  24520. *
  24521. * Special properties are exposed on the local scope of each template instance, including:
  24522. *
  24523. * | Variable | Type | Details |
  24524. * |-----------|-----------------|-----------------------------------------------------------------------------|
  24525. * | `$index` | {@type number} | iterator offset of the repeated element (0..length-1) |
  24526. * | `$first` | {@type boolean} | true if the repeated element is first in the iterator. |
  24527. * | `$middle` | {@type boolean} | true if the repeated element is between the first and last in the iterator. |
  24528. * | `$last` | {@type boolean} | true if the repeated element is last in the iterator. |
  24529. * | `$even` | {@type boolean} | true if the iterator position `$index` is even (otherwise false). |
  24530. * | `$odd` | {@type boolean} | true if the iterator position `$index` is odd (otherwise false). |
  24531. *
  24532. * <div class="alert alert-info">
  24533. * Creating aliases for these properties is possible with {@link ng.directive:ngInit `ngInit`}.
  24534. * This may be useful when, for instance, nesting ngRepeats.
  24535. * </div>
  24536. *
  24537. *
  24538. * # Iterating over object properties
  24539. *
  24540. * It is possible to get `ngRepeat` to iterate over the properties of an object using the following
  24541. * syntax:
  24542. *
  24543. * ```js
  24544. * <div ng-repeat="(key, value) in myObj"> ... </div>
  24545. * ```
  24546. *
  24547. * You need to be aware that the JavaScript specification does not define the order of keys
  24548. * returned for an object. (To mitigate this in Angular 1.3 the `ngRepeat` directive
  24549. * used to sort the keys alphabetically.)
  24550. *
  24551. * Version 1.4 removed the alphabetic sorting. We now rely on the order returned by the browser
  24552. * when running `for key in myObj`. It seems that browsers generally follow the strategy of providing
  24553. * keys in the order in which they were defined, although there are exceptions when keys are deleted
  24554. * and reinstated. See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/delete#Cross-browser_issues
  24555. *
  24556. * If this is not desired, the recommended workaround is to convert your object into an array
  24557. * that is sorted into the order that you prefer before providing it to `ngRepeat`. You could
  24558. * do this with a filter such as [toArrayFilter](http://ngmodules.org/modules/angular-toArrayFilter)
  24559. * or implement a `$watch` on the object yourself.
  24560. *
  24561. *
  24562. * # Tracking and Duplicates
  24563. *
  24564. * When the contents of the collection change, `ngRepeat` makes the corresponding changes to the DOM:
  24565. *
  24566. * * When an item is added, a new instance of the template is added to the DOM.
  24567. * * When an item is removed, its template instance is removed from the DOM.
  24568. * * When items are reordered, their respective templates are reordered in the DOM.
  24569. *
  24570. * By default, `ngRepeat` does not allow duplicate items in arrays. This is because when
  24571. * there are duplicates, it is not possible to maintain a one-to-one mapping between collection
  24572. * items and DOM elements.
  24573. *
  24574. * If you do need to repeat duplicate items, you can substitute the default tracking behavior
  24575. * with your own using the `track by` expression.
  24576. *
  24577. * For example, you may track items by the index of each item in the collection, using the
  24578. * special scope property `$index`:
  24579. * ```html
  24580. * <div ng-repeat="n in [42, 42, 43, 43] track by $index">
  24581. * {{n}}
  24582. * </div>
  24583. * ```
  24584. *
  24585. * You may use arbitrary expressions in `track by`, including references to custom functions
  24586. * on the scope:
  24587. * ```html
  24588. * <div ng-repeat="n in [42, 42, 43, 43] track by myTrackingFunction(n)">
  24589. * {{n}}
  24590. * </div>
  24591. * ```
  24592. *
  24593. * If you are working with objects that have an identifier property, you can track
  24594. * by the identifier instead of the whole object. Should you reload your data later, `ngRepeat`
  24595. * will not have to rebuild the DOM elements for items it has already rendered, even if the
  24596. * JavaScript objects in the collection have been substituted for new ones:
  24597. * ```html
  24598. * <div ng-repeat="model in collection track by model.id">
  24599. * {{model.name}}
  24600. * </div>
  24601. * ```
  24602. *
  24603. * When no `track by` expression is provided, it is equivalent to tracking by the built-in
  24604. * `$id` function, which tracks items by their identity:
  24605. * ```html
  24606. * <div ng-repeat="obj in collection track by $id(obj)">
  24607. * {{obj.prop}}
  24608. * </div>
  24609. * ```
  24610. *
  24611. * <div class="alert alert-warning">
  24612. * **Note:** `track by` must always be the last expression:
  24613. * </div>
  24614. * ```
  24615. * <div ng-repeat="model in collection | orderBy: 'id' as filtered_result track by model.id">
  24616. * {{model.name}}
  24617. * </div>
  24618. * ```
  24619. *
  24620. * # Special repeat start and end points
  24621. * To repeat a series of elements instead of just one parent element, ngRepeat (as well as other ng directives) supports extending
  24622. * the range of the repeater by defining explicit start and end points by using **ng-repeat-start** and **ng-repeat-end** respectively.
  24623. * The **ng-repeat-start** directive works the same as **ng-repeat**, but will repeat all the HTML code (including the tag it's defined on)
  24624. * up to and including the ending HTML tag where **ng-repeat-end** is placed.
  24625. *
  24626. * The example below makes use of this feature:
  24627. * ```html
  24628. * <header ng-repeat-start="item in items">
  24629. * Header {{ item }}
  24630. * </header>
  24631. * <div class="body">
  24632. * Body {{ item }}
  24633. * </div>
  24634. * <footer ng-repeat-end>
  24635. * Footer {{ item }}
  24636. * </footer>
  24637. * ```
  24638. *
  24639. * And with an input of {@type ['A','B']} for the items variable in the example above, the output will evaluate to:
  24640. * ```html
  24641. * <header>
  24642. * Header A
  24643. * </header>
  24644. * <div class="body">
  24645. * Body A
  24646. * </div>
  24647. * <footer>
  24648. * Footer A
  24649. * </footer>
  24650. * <header>
  24651. * Header B
  24652. * </header>
  24653. * <div class="body">
  24654. * Body B
  24655. * </div>
  24656. * <footer>
  24657. * Footer B
  24658. * </footer>
  24659. * ```
  24660. *
  24661. * The custom start and end points for ngRepeat also support all other HTML directive syntax flavors provided in AngularJS (such
  24662. * as **data-ng-repeat-start**, **x-ng-repeat-start** and **ng:repeat-start**).
  24663. *
  24664. * @animations
  24665. * **.enter** - when a new item is added to the list or when an item is revealed after a filter
  24666. *
  24667. * **.leave** - when an item is removed from the list or when an item is filtered out
  24668. *
  24669. * **.move** - when an adjacent item is filtered out causing a reorder or when the item contents are reordered
  24670. *
  24671. * @element ANY
  24672. * @scope
  24673. * @priority 1000
  24674. * @param {repeat_expression} ngRepeat The expression indicating how to enumerate a collection. These
  24675. * formats are currently supported:
  24676. *
  24677. * * `variable in expression` – where variable is the user defined loop variable and `expression`
  24678. * is a scope expression giving the collection to enumerate.
  24679. *
  24680. * For example: `album in artist.albums`.
  24681. *
  24682. * * `(key, value) in expression` – where `key` and `value` can be any user defined identifiers,
  24683. * and `expression` is the scope expression giving the collection to enumerate.
  24684. *
  24685. * For example: `(name, age) in {'adam':10, 'amalie':12}`.
  24686. *
  24687. * * `variable in expression track by tracking_expression` – You can also provide an optional tracking expression
  24688. * which can be used to associate the objects in the collection with the DOM elements. If no tracking expression
  24689. * is specified, ng-repeat associates elements by identity. It is an error to have
  24690. * more than one tracking expression value resolve to the same key. (This would mean that two distinct objects are
  24691. * mapped to the same DOM element, which is not possible.)
  24692. *
  24693. * Note that the tracking expression must come last, after any filters, and the alias expression.
  24694. *
  24695. * For example: `item in items` is equivalent to `item in items track by $id(item)`. This implies that the DOM elements
  24696. * will be associated by item identity in the array.
  24697. *
  24698. * For example: `item in items track by $id(item)`. A built in `$id()` function can be used to assign a unique
  24699. * `$$hashKey` property to each item in the array. This property is then used as a key to associated DOM elements
  24700. * with the corresponding item in the array by identity. Moving the same object in array would move the DOM
  24701. * element in the same way in the DOM.
  24702. *
  24703. * For example: `item in items track by item.id` is a typical pattern when the items come from the database. In this
  24704. * case the object identity does not matter. Two objects are considered equivalent as long as their `id`
  24705. * property is same.
  24706. *
  24707. * For example: `item in items | filter:searchText track by item.id` is a pattern that might be used to apply a filter
  24708. * to items in conjunction with a tracking expression.
  24709. *
  24710. * * `variable in expression as alias_expression` – You can also provide an optional alias expression which will then store the
  24711. * intermediate results of the repeater after the filters have been applied. Typically this is used to render a special message
  24712. * when a filter is active on the repeater, but the filtered result set is empty.
  24713. *
  24714. * For example: `item in items | filter:x as results` will store the fragment of the repeated items as `results`, but only after
  24715. * the items have been processed through the filter.
  24716. *
  24717. * Please note that `as [variable name] is not an operator but rather a part of ngRepeat micro-syntax so it can be used only at the end
  24718. * (and not as operator, inside an expression).
  24719. *
  24720. * For example: `item in items | filter : x | orderBy : order | limitTo : limit as results` .
  24721. *
  24722. * @example
  24723. * This example initializes the scope to a list of names and
  24724. * then uses `ngRepeat` to display every person:
  24725. <example module="ngAnimate" deps="angular-animate.js" animations="true">
  24726. <file name="index.html">
  24727. <div ng-init="friends = [
  24728. {name:'John', age:25, gender:'boy'},
  24729. {name:'Jessie', age:30, gender:'girl'},
  24730. {name:'Johanna', age:28, gender:'girl'},
  24731. {name:'Joy', age:15, gender:'girl'},
  24732. {name:'Mary', age:28, gender:'girl'},
  24733. {name:'Peter', age:95, gender:'boy'},
  24734. {name:'Sebastian', age:50, gender:'boy'},
  24735. {name:'Erika', age:27, gender:'girl'},
  24736. {name:'Patrick', age:40, gender:'boy'},
  24737. {name:'Samantha', age:60, gender:'girl'}
  24738. ]">
  24739. I have {{friends.length}} friends. They are:
  24740. <input type="search" ng-model="q" placeholder="filter friends..." aria-label="filter friends" />
  24741. <ul class="example-animate-container">
  24742. <li class="animate-repeat" ng-repeat="friend in friends | filter:q as results">
  24743. [{{$index + 1}}] {{friend.name}} who is {{friend.age}} years old.
  24744. </li>
  24745. <li class="animate-repeat" ng-if="results.length == 0">
  24746. <strong>No results found...</strong>
  24747. </li>
  24748. </ul>
  24749. </div>
  24750. </file>
  24751. <file name="animations.css">
  24752. .example-animate-container {
  24753. background:white;
  24754. border:1px solid black;
  24755. list-style:none;
  24756. margin:0;
  24757. padding:0 10px;
  24758. }
  24759. .animate-repeat {
  24760. line-height:40px;
  24761. list-style:none;
  24762. box-sizing:border-box;
  24763. }
  24764. .animate-repeat.ng-move,
  24765. .animate-repeat.ng-enter,
  24766. .animate-repeat.ng-leave {
  24767. transition:all linear 0.5s;
  24768. }
  24769. .animate-repeat.ng-leave.ng-leave-active,
  24770. .animate-repeat.ng-move,
  24771. .animate-repeat.ng-enter {
  24772. opacity:0;
  24773. max-height:0;
  24774. }
  24775. .animate-repeat.ng-leave,
  24776. .animate-repeat.ng-move.ng-move-active,
  24777. .animate-repeat.ng-enter.ng-enter-active {
  24778. opacity:1;
  24779. max-height:40px;
  24780. }
  24781. </file>
  24782. <file name="protractor.js" type="protractor">
  24783. var friends = element.all(by.repeater('friend in friends'));
  24784. it('should render initial data set', function() {
  24785. expect(friends.count()).toBe(10);
  24786. expect(friends.get(0).getText()).toEqual('[1] John who is 25 years old.');
  24787. expect(friends.get(1).getText()).toEqual('[2] Jessie who is 30 years old.');
  24788. expect(friends.last().getText()).toEqual('[10] Samantha who is 60 years old.');
  24789. expect(element(by.binding('friends.length')).getText())
  24790. .toMatch("I have 10 friends. They are:");
  24791. });
  24792. it('should update repeater when filter predicate changes', function() {
  24793. expect(friends.count()).toBe(10);
  24794. element(by.model('q')).sendKeys('ma');
  24795. expect(friends.count()).toBe(2);
  24796. expect(friends.get(0).getText()).toEqual('[1] Mary who is 28 years old.');
  24797. expect(friends.last().getText()).toEqual('[2] Samantha who is 60 years old.');
  24798. });
  24799. </file>
  24800. </example>
  24801. */
  24802. var ngRepeatDirective = ['$parse', '$animate', function($parse, $animate) {
  24803. var NG_REMOVED = '$$NG_REMOVED';
  24804. var ngRepeatMinErr = minErr('ngRepeat');
  24805. var updateScope = function(scope, index, valueIdentifier, value, keyIdentifier, key, arrayLength) {
  24806. // TODO(perf): generate setters to shave off ~40ms or 1-1.5%
  24807. scope[valueIdentifier] = value;
  24808. if (keyIdentifier) scope[keyIdentifier] = key;
  24809. scope.$index = index;
  24810. scope.$first = (index === 0);
  24811. scope.$last = (index === (arrayLength - 1));
  24812. scope.$middle = !(scope.$first || scope.$last);
  24813. // jshint bitwise: false
  24814. scope.$odd = !(scope.$even = (index&1) === 0);
  24815. // jshint bitwise: true
  24816. };
  24817. var getBlockStart = function(block) {
  24818. return block.clone[0];
  24819. };
  24820. var getBlockEnd = function(block) {
  24821. return block.clone[block.clone.length - 1];
  24822. };
  24823. return {
  24824. restrict: 'A',
  24825. multiElement: true,
  24826. transclude: 'element',
  24827. priority: 1000,
  24828. terminal: true,
  24829. $$tlb: true,
  24830. compile: function ngRepeatCompile($element, $attr) {
  24831. var expression = $attr.ngRepeat;
  24832. var ngRepeatEndComment = document.createComment(' end ngRepeat: ' + expression + ' ');
  24833. var match = expression.match(/^\s*([\s\S]+?)\s+in\s+([\s\S]+?)(?:\s+as\s+([\s\S]+?))?(?:\s+track\s+by\s+([\s\S]+?))?\s*$/);
  24834. if (!match) {
  24835. throw ngRepeatMinErr('iexp', "Expected expression in form of '_item_ in _collection_[ track by _id_]' but got '{0}'.",
  24836. expression);
  24837. }
  24838. var lhs = match[1];
  24839. var rhs = match[2];
  24840. var aliasAs = match[3];
  24841. var trackByExp = match[4];
  24842. match = lhs.match(/^(?:(\s*[\$\w]+)|\(\s*([\$\w]+)\s*,\s*([\$\w]+)\s*\))$/);
  24843. if (!match) {
  24844. throw ngRepeatMinErr('iidexp', "'_item_' in '_item_ in _collection_' should be an identifier or '(_key_, _value_)' expression, but got '{0}'.",
  24845. lhs);
  24846. }
  24847. var valueIdentifier = match[3] || match[1];
  24848. var keyIdentifier = match[2];
  24849. if (aliasAs && (!/^[$a-zA-Z_][$a-zA-Z0-9_]*$/.test(aliasAs) ||
  24850. /^(null|undefined|this|\$index|\$first|\$middle|\$last|\$even|\$odd|\$parent|\$root|\$id)$/.test(aliasAs))) {
  24851. throw ngRepeatMinErr('badident', "alias '{0}' is invalid --- must be a valid JS identifier which is not a reserved name.",
  24852. aliasAs);
  24853. }
  24854. var trackByExpGetter, trackByIdExpFn, trackByIdArrayFn, trackByIdObjFn;
  24855. var hashFnLocals = {$id: hashKey};
  24856. if (trackByExp) {
  24857. trackByExpGetter = $parse(trackByExp);
  24858. } else {
  24859. trackByIdArrayFn = function(key, value) {
  24860. return hashKey(value);
  24861. };
  24862. trackByIdObjFn = function(key) {
  24863. return key;
  24864. };
  24865. }
  24866. return function ngRepeatLink($scope, $element, $attr, ctrl, $transclude) {
  24867. if (trackByExpGetter) {
  24868. trackByIdExpFn = function(key, value, index) {
  24869. // assign key, value, and $index to the locals so that they can be used in hash functions
  24870. if (keyIdentifier) hashFnLocals[keyIdentifier] = key;
  24871. hashFnLocals[valueIdentifier] = value;
  24872. hashFnLocals.$index = index;
  24873. return trackByExpGetter($scope, hashFnLocals);
  24874. };
  24875. }
  24876. // Store a list of elements from previous run. This is a hash where key is the item from the
  24877. // iterator, and the value is objects with following properties.
  24878. // - scope: bound scope
  24879. // - element: previous element.
  24880. // - index: position
  24881. //
  24882. // We are using no-proto object so that we don't need to guard against inherited props via
  24883. // hasOwnProperty.
  24884. var lastBlockMap = createMap();
  24885. //watch props
  24886. $scope.$watchCollection(rhs, function ngRepeatAction(collection) {
  24887. var index, length,
  24888. previousNode = $element[0], // node that cloned nodes should be inserted after
  24889. // initialized to the comment node anchor
  24890. nextNode,
  24891. // Same as lastBlockMap but it has the current state. It will become the
  24892. // lastBlockMap on the next iteration.
  24893. nextBlockMap = createMap(),
  24894. collectionLength,
  24895. key, value, // key/value of iteration
  24896. trackById,
  24897. trackByIdFn,
  24898. collectionKeys,
  24899. block, // last object information {scope, element, id}
  24900. nextBlockOrder,
  24901. elementsToRemove;
  24902. if (aliasAs) {
  24903. $scope[aliasAs] = collection;
  24904. }
  24905. if (isArrayLike(collection)) {
  24906. collectionKeys = collection;
  24907. trackByIdFn = trackByIdExpFn || trackByIdArrayFn;
  24908. } else {
  24909. trackByIdFn = trackByIdExpFn || trackByIdObjFn;
  24910. // if object, extract keys, in enumeration order, unsorted
  24911. collectionKeys = [];
  24912. for (var itemKey in collection) {
  24913. if (hasOwnProperty.call(collection, itemKey) && itemKey.charAt(0) !== '$') {
  24914. collectionKeys.push(itemKey);
  24915. }
  24916. }
  24917. }
  24918. collectionLength = collectionKeys.length;
  24919. nextBlockOrder = new Array(collectionLength);
  24920. // locate existing items
  24921. for (index = 0; index < collectionLength; index++) {
  24922. key = (collection === collectionKeys) ? index : collectionKeys[index];
  24923. value = collection[key];
  24924. trackById = trackByIdFn(key, value, index);
  24925. if (lastBlockMap[trackById]) {
  24926. // found previously seen block
  24927. block = lastBlockMap[trackById];
  24928. delete lastBlockMap[trackById];
  24929. nextBlockMap[trackById] = block;
  24930. nextBlockOrder[index] = block;
  24931. } else if (nextBlockMap[trackById]) {
  24932. // if collision detected. restore lastBlockMap and throw an error
  24933. forEach(nextBlockOrder, function(block) {
  24934. if (block && block.scope) lastBlockMap[block.id] = block;
  24935. });
  24936. throw ngRepeatMinErr('dupes',
  24937. "Duplicates in a repeater are not allowed. Use 'track by' expression to specify unique keys. Repeater: {0}, Duplicate key: {1}, Duplicate value: {2}",
  24938. expression, trackById, value);
  24939. } else {
  24940. // new never before seen block
  24941. nextBlockOrder[index] = {id: trackById, scope: undefined, clone: undefined};
  24942. nextBlockMap[trackById] = true;
  24943. }
  24944. }
  24945. // remove leftover items
  24946. for (var blockKey in lastBlockMap) {
  24947. block = lastBlockMap[blockKey];
  24948. elementsToRemove = getBlockNodes(block.clone);
  24949. $animate.leave(elementsToRemove);
  24950. if (elementsToRemove[0].parentNode) {
  24951. // if the element was not removed yet because of pending animation, mark it as deleted
  24952. // so that we can ignore it later
  24953. for (index = 0, length = elementsToRemove.length; index < length; index++) {
  24954. elementsToRemove[index][NG_REMOVED] = true;
  24955. }
  24956. }
  24957. block.scope.$destroy();
  24958. }
  24959. // we are not using forEach for perf reasons (trying to avoid #call)
  24960. for (index = 0; index < collectionLength; index++) {
  24961. key = (collection === collectionKeys) ? index : collectionKeys[index];
  24962. value = collection[key];
  24963. block = nextBlockOrder[index];
  24964. if (block.scope) {
  24965. // if we have already seen this object, then we need to reuse the
  24966. // associated scope/element
  24967. nextNode = previousNode;
  24968. // skip nodes that are already pending removal via leave animation
  24969. do {
  24970. nextNode = nextNode.nextSibling;
  24971. } while (nextNode && nextNode[NG_REMOVED]);
  24972. if (getBlockStart(block) != nextNode) {
  24973. // existing item which got moved
  24974. $animate.move(getBlockNodes(block.clone), null, jqLite(previousNode));
  24975. }
  24976. previousNode = getBlockEnd(block);
  24977. updateScope(block.scope, index, valueIdentifier, value, keyIdentifier, key, collectionLength);
  24978. } else {
  24979. // new item which we don't know about
  24980. $transclude(function ngRepeatTransclude(clone, scope) {
  24981. block.scope = scope;
  24982. // http://jsperf.com/clone-vs-createcomment
  24983. var endNode = ngRepeatEndComment.cloneNode(false);
  24984. clone[clone.length++] = endNode;
  24985. // TODO(perf): support naked previousNode in `enter` to avoid creation of jqLite wrapper?
  24986. $animate.enter(clone, null, jqLite(previousNode));
  24987. previousNode = endNode;
  24988. // Note: We only need the first/last node of the cloned nodes.
  24989. // However, we need to keep the reference to the jqlite wrapper as it might be changed later
  24990. // by a directive with templateUrl when its template arrives.
  24991. block.clone = clone;
  24992. nextBlockMap[block.id] = block;
  24993. updateScope(block.scope, index, valueIdentifier, value, keyIdentifier, key, collectionLength);
  24994. });
  24995. }
  24996. }
  24997. lastBlockMap = nextBlockMap;
  24998. });
  24999. };
  25000. }
  25001. };
  25002. }];
  25003. var NG_HIDE_CLASS = 'ng-hide';
  25004. var NG_HIDE_IN_PROGRESS_CLASS = 'ng-hide-animate';
  25005. /**
  25006. * @ngdoc directive
  25007. * @name ngShow
  25008. * @multiElement
  25009. *
  25010. * @description
  25011. * The `ngShow` directive shows or hides the given HTML element based on the expression
  25012. * provided to the `ngShow` attribute. The element is shown or hidden by removing or adding
  25013. * the `.ng-hide` CSS class onto the element. The `.ng-hide` CSS class is predefined
  25014. * in AngularJS and sets the display style to none (using an !important flag).
  25015. * For CSP mode please add `angular-csp.css` to your html file (see {@link ng.directive:ngCsp ngCsp}).
  25016. *
  25017. * ```html
  25018. * <!-- when $scope.myValue is truthy (element is visible) -->
  25019. * <div ng-show="myValue"></div>
  25020. *
  25021. * <!-- when $scope.myValue is falsy (element is hidden) -->
  25022. * <div ng-show="myValue" class="ng-hide"></div>
  25023. * ```
  25024. *
  25025. * When the `ngShow` expression evaluates to a falsy value then the `.ng-hide` CSS class is added to the class
  25026. * attribute on the element causing it to become hidden. When truthy, the `.ng-hide` CSS class is removed
  25027. * from the element causing the element not to appear hidden.
  25028. *
  25029. * ## Why is !important used?
  25030. *
  25031. * You may be wondering why !important is used for the `.ng-hide` CSS class. This is because the `.ng-hide` selector
  25032. * can be easily overridden by heavier selectors. For example, something as simple
  25033. * as changing the display style on a HTML list item would make hidden elements appear visible.
  25034. * This also becomes a bigger issue when dealing with CSS frameworks.
  25035. *
  25036. * By using !important, the show and hide behavior will work as expected despite any clash between CSS selector
  25037. * specificity (when !important isn't used with any conflicting styles). If a developer chooses to override the
  25038. * styling to change how to hide an element then it is just a matter of using !important in their own CSS code.
  25039. *
  25040. * ### Overriding `.ng-hide`
  25041. *
  25042. * By default, the `.ng-hide` class will style the element with `display: none!important`. If you wish to change
  25043. * the hide behavior with ngShow/ngHide then this can be achieved by restating the styles for the `.ng-hide`
  25044. * class CSS. Note that the selector that needs to be used is actually `.ng-hide:not(.ng-hide-animate)` to cope
  25045. * with extra animation classes that can be added.
  25046. *
  25047. * ```css
  25048. * .ng-hide:not(.ng-hide-animate) {
  25049. * /&#42; this is just another form of hiding an element &#42;/
  25050. * display: block!important;
  25051. * position: absolute;
  25052. * top: -9999px;
  25053. * left: -9999px;
  25054. * }
  25055. * ```
  25056. *
  25057. * By default you don't need to override in CSS anything and the animations will work around the display style.
  25058. *
  25059. * ## A note about animations with `ngShow`
  25060. *
  25061. * Animations in ngShow/ngHide work with the show and hide events that are triggered when the directive expression
  25062. * is true and false. This system works like the animation system present with ngClass except that
  25063. * you must also include the !important flag to override the display property
  25064. * so that you can perform an animation when the element is hidden during the time of the animation.
  25065. *
  25066. * ```css
  25067. * //
  25068. * //a working example can be found at the bottom of this page
  25069. * //
  25070. * .my-element.ng-hide-add, .my-element.ng-hide-remove {
  25071. * /&#42; this is required as of 1.3x to properly
  25072. * apply all styling in a show/hide animation &#42;/
  25073. * transition: 0s linear all;
  25074. * }
  25075. *
  25076. * .my-element.ng-hide-add-active,
  25077. * .my-element.ng-hide-remove-active {
  25078. * /&#42; the transition is defined in the active class &#42;/
  25079. * transition: 1s linear all;
  25080. * }
  25081. *
  25082. * .my-element.ng-hide-add { ... }
  25083. * .my-element.ng-hide-add.ng-hide-add-active { ... }
  25084. * .my-element.ng-hide-remove { ... }
  25085. * .my-element.ng-hide-remove.ng-hide-remove-active { ... }
  25086. * ```
  25087. *
  25088. * Keep in mind that, as of AngularJS version 1.3.0-beta.11, there is no need to change the display
  25089. * property to block during animation states--ngAnimate will handle the style toggling automatically for you.
  25090. *
  25091. * @animations
  25092. * addClass: `.ng-hide` - happens after the `ngShow` expression evaluates to a truthy value and the just before contents are set to visible
  25093. * removeClass: `.ng-hide` - happens after the `ngShow` expression evaluates to a non truthy value and just before the contents are set to hidden
  25094. *
  25095. * @element ANY
  25096. * @param {expression} ngShow If the {@link guide/expression expression} is truthy
  25097. * then the element is shown or hidden respectively.
  25098. *
  25099. * @example
  25100. <example module="ngAnimate" deps="angular-animate.js" animations="true">
  25101. <file name="index.html">
  25102. Click me: <input type="checkbox" ng-model="checked" aria-label="Toggle ngHide"><br/>
  25103. <div>
  25104. Show:
  25105. <div class="check-element animate-show" ng-show="checked">
  25106. <span class="glyphicon glyphicon-thumbs-up"></span> I show up when your checkbox is checked.
  25107. </div>
  25108. </div>
  25109. <div>
  25110. Hide:
  25111. <div class="check-element animate-show" ng-hide="checked">
  25112. <span class="glyphicon glyphicon-thumbs-down"></span> I hide when your checkbox is checked.
  25113. </div>
  25114. </div>
  25115. </file>
  25116. <file name="glyphicons.css">
  25117. @import url(../../components/bootstrap-3.1.1/css/bootstrap.css);
  25118. </file>
  25119. <file name="animations.css">
  25120. .animate-show {
  25121. line-height: 20px;
  25122. opacity: 1;
  25123. padding: 10px;
  25124. border: 1px solid black;
  25125. background: white;
  25126. }
  25127. .animate-show.ng-hide-add, .animate-show.ng-hide-remove {
  25128. transition: all linear 0.5s;
  25129. }
  25130. .animate-show.ng-hide {
  25131. line-height: 0;
  25132. opacity: 0;
  25133. padding: 0 10px;
  25134. }
  25135. .check-element {
  25136. padding: 10px;
  25137. border: 1px solid black;
  25138. background: white;
  25139. }
  25140. </file>
  25141. <file name="protractor.js" type="protractor">
  25142. var thumbsUp = element(by.css('span.glyphicon-thumbs-up'));
  25143. var thumbsDown = element(by.css('span.glyphicon-thumbs-down'));
  25144. it('should check ng-show / ng-hide', function() {
  25145. expect(thumbsUp.isDisplayed()).toBeFalsy();
  25146. expect(thumbsDown.isDisplayed()).toBeTruthy();
  25147. element(by.model('checked')).click();
  25148. expect(thumbsUp.isDisplayed()).toBeTruthy();
  25149. expect(thumbsDown.isDisplayed()).toBeFalsy();
  25150. });
  25151. </file>
  25152. </example>
  25153. */
  25154. var ngShowDirective = ['$animate', function($animate) {
  25155. return {
  25156. restrict: 'A',
  25157. multiElement: true,
  25158. link: function(scope, element, attr) {
  25159. scope.$watch(attr.ngShow, function ngShowWatchAction(value) {
  25160. // we're adding a temporary, animation-specific class for ng-hide since this way
  25161. // we can control when the element is actually displayed on screen without having
  25162. // to have a global/greedy CSS selector that breaks when other animations are run.
  25163. // Read: https://github.com/angular/angular.js/issues/9103#issuecomment-58335845
  25164. $animate[value ? 'removeClass' : 'addClass'](element, NG_HIDE_CLASS, {
  25165. tempClasses: NG_HIDE_IN_PROGRESS_CLASS
  25166. });
  25167. });
  25168. }
  25169. };
  25170. }];
  25171. /**
  25172. * @ngdoc directive
  25173. * @name ngHide
  25174. * @multiElement
  25175. *
  25176. * @description
  25177. * The `ngHide` directive shows or hides the given HTML element based on the expression
  25178. * provided to the `ngHide` attribute. The element is shown or hidden by removing or adding
  25179. * the `ng-hide` CSS class onto the element. The `.ng-hide` CSS class is predefined
  25180. * in AngularJS and sets the display style to none (using an !important flag).
  25181. * For CSP mode please add `angular-csp.css` to your html file (see {@link ng.directive:ngCsp ngCsp}).
  25182. *
  25183. * ```html
  25184. * <!-- when $scope.myValue is truthy (element is hidden) -->
  25185. * <div ng-hide="myValue" class="ng-hide"></div>
  25186. *
  25187. * <!-- when $scope.myValue is falsy (element is visible) -->
  25188. * <div ng-hide="myValue"></div>
  25189. * ```
  25190. *
  25191. * When the `ngHide` expression evaluates to a truthy value then the `.ng-hide` CSS class is added to the class
  25192. * attribute on the element causing it to become hidden. When falsy, the `.ng-hide` CSS class is removed
  25193. * from the element causing the element not to appear hidden.
  25194. *
  25195. * ## Why is !important used?
  25196. *
  25197. * You may be wondering why !important is used for the `.ng-hide` CSS class. This is because the `.ng-hide` selector
  25198. * can be easily overridden by heavier selectors. For example, something as simple
  25199. * as changing the display style on a HTML list item would make hidden elements appear visible.
  25200. * This also becomes a bigger issue when dealing with CSS frameworks.
  25201. *
  25202. * By using !important, the show and hide behavior will work as expected despite any clash between CSS selector
  25203. * specificity (when !important isn't used with any conflicting styles). If a developer chooses to override the
  25204. * styling to change how to hide an element then it is just a matter of using !important in their own CSS code.
  25205. *
  25206. * ### Overriding `.ng-hide`
  25207. *
  25208. * By default, the `.ng-hide` class will style the element with `display: none!important`. If you wish to change
  25209. * the hide behavior with ngShow/ngHide then this can be achieved by restating the styles for the `.ng-hide`
  25210. * class in CSS:
  25211. *
  25212. * ```css
  25213. * .ng-hide {
  25214. * /&#42; this is just another form of hiding an element &#42;/
  25215. * display: block!important;
  25216. * position: absolute;
  25217. * top: -9999px;
  25218. * left: -9999px;
  25219. * }
  25220. * ```
  25221. *
  25222. * By default you don't need to override in CSS anything and the animations will work around the display style.
  25223. *
  25224. * ## A note about animations with `ngHide`
  25225. *
  25226. * Animations in ngShow/ngHide work with the show and hide events that are triggered when the directive expression
  25227. * is true and false. This system works like the animation system present with ngClass, except that the `.ng-hide`
  25228. * CSS class is added and removed for you instead of your own CSS class.
  25229. *
  25230. * ```css
  25231. * //
  25232. * //a working example can be found at the bottom of this page
  25233. * //
  25234. * .my-element.ng-hide-add, .my-element.ng-hide-remove {
  25235. * transition: 0.5s linear all;
  25236. * }
  25237. *
  25238. * .my-element.ng-hide-add { ... }
  25239. * .my-element.ng-hide-add.ng-hide-add-active { ... }
  25240. * .my-element.ng-hide-remove { ... }
  25241. * .my-element.ng-hide-remove.ng-hide-remove-active { ... }
  25242. * ```
  25243. *
  25244. * Keep in mind that, as of AngularJS version 1.3.0-beta.11, there is no need to change the display
  25245. * property to block during animation states--ngAnimate will handle the style toggling automatically for you.
  25246. *
  25247. * @animations
  25248. * removeClass: `.ng-hide` - happens after the `ngHide` expression evaluates to a truthy value and just before the contents are set to hidden
  25249. * addClass: `.ng-hide` - happens after the `ngHide` expression evaluates to a non truthy value and just before the contents are set to visible
  25250. *
  25251. * @element ANY
  25252. * @param {expression} ngHide If the {@link guide/expression expression} is truthy then
  25253. * the element is shown or hidden respectively.
  25254. *
  25255. * @example
  25256. <example module="ngAnimate" deps="angular-animate.js" animations="true">
  25257. <file name="index.html">
  25258. Click me: <input type="checkbox" ng-model="checked" aria-label="Toggle ngShow"><br/>
  25259. <div>
  25260. Show:
  25261. <div class="check-element animate-hide" ng-show="checked">
  25262. <span class="glyphicon glyphicon-thumbs-up"></span> I show up when your checkbox is checked.
  25263. </div>
  25264. </div>
  25265. <div>
  25266. Hide:
  25267. <div class="check-element animate-hide" ng-hide="checked">
  25268. <span class="glyphicon glyphicon-thumbs-down"></span> I hide when your checkbox is checked.
  25269. </div>
  25270. </div>
  25271. </file>
  25272. <file name="glyphicons.css">
  25273. @import url(../../components/bootstrap-3.1.1/css/bootstrap.css);
  25274. </file>
  25275. <file name="animations.css">
  25276. .animate-hide {
  25277. transition: all linear 0.5s;
  25278. line-height: 20px;
  25279. opacity: 1;
  25280. padding: 10px;
  25281. border: 1px solid black;
  25282. background: white;
  25283. }
  25284. .animate-hide.ng-hide {
  25285. line-height: 0;
  25286. opacity: 0;
  25287. padding: 0 10px;
  25288. }
  25289. .check-element {
  25290. padding: 10px;
  25291. border: 1px solid black;
  25292. background: white;
  25293. }
  25294. </file>
  25295. <file name="protractor.js" type="protractor">
  25296. var thumbsUp = element(by.css('span.glyphicon-thumbs-up'));
  25297. var thumbsDown = element(by.css('span.glyphicon-thumbs-down'));
  25298. it('should check ng-show / ng-hide', function() {
  25299. expect(thumbsUp.isDisplayed()).toBeFalsy();
  25300. expect(thumbsDown.isDisplayed()).toBeTruthy();
  25301. element(by.model('checked')).click();
  25302. expect(thumbsUp.isDisplayed()).toBeTruthy();
  25303. expect(thumbsDown.isDisplayed()).toBeFalsy();
  25304. });
  25305. </file>
  25306. </example>
  25307. */
  25308. var ngHideDirective = ['$animate', function($animate) {
  25309. return {
  25310. restrict: 'A',
  25311. multiElement: true,
  25312. link: function(scope, element, attr) {
  25313. scope.$watch(attr.ngHide, function ngHideWatchAction(value) {
  25314. // The comment inside of the ngShowDirective explains why we add and
  25315. // remove a temporary class for the show/hide animation
  25316. $animate[value ? 'addClass' : 'removeClass'](element,NG_HIDE_CLASS, {
  25317. tempClasses: NG_HIDE_IN_PROGRESS_CLASS
  25318. });
  25319. });
  25320. }
  25321. };
  25322. }];
  25323. /**
  25324. * @ngdoc directive
  25325. * @name ngStyle
  25326. * @restrict AC
  25327. *
  25328. * @description
  25329. * The `ngStyle` directive allows you to set CSS style on an HTML element conditionally.
  25330. *
  25331. * @element ANY
  25332. * @param {expression} ngStyle
  25333. *
  25334. * {@link guide/expression Expression} which evals to an
  25335. * object whose keys are CSS style names and values are corresponding values for those CSS
  25336. * keys.
  25337. *
  25338. * Since some CSS style names are not valid keys for an object, they must be quoted.
  25339. * See the 'background-color' style in the example below.
  25340. *
  25341. * @example
  25342. <example>
  25343. <file name="index.html">
  25344. <input type="button" value="set color" ng-click="myStyle={color:'red'}">
  25345. <input type="button" value="set background" ng-click="myStyle={'background-color':'blue'}">
  25346. <input type="button" value="clear" ng-click="myStyle={}">
  25347. <br/>
  25348. <span ng-style="myStyle">Sample Text</span>
  25349. <pre>myStyle={{myStyle}}</pre>
  25350. </file>
  25351. <file name="style.css">
  25352. span {
  25353. color: black;
  25354. }
  25355. </file>
  25356. <file name="protractor.js" type="protractor">
  25357. var colorSpan = element(by.css('span'));
  25358. it('should check ng-style', function() {
  25359. expect(colorSpan.getCssValue('color')).toBe('rgba(0, 0, 0, 1)');
  25360. element(by.css('input[value=\'set color\']')).click();
  25361. expect(colorSpan.getCssValue('color')).toBe('rgba(255, 0, 0, 1)');
  25362. element(by.css('input[value=clear]')).click();
  25363. expect(colorSpan.getCssValue('color')).toBe('rgba(0, 0, 0, 1)');
  25364. });
  25365. </file>
  25366. </example>
  25367. */
  25368. var ngStyleDirective = ngDirective(function(scope, element, attr) {
  25369. scope.$watch(attr.ngStyle, function ngStyleWatchAction(newStyles, oldStyles) {
  25370. if (oldStyles && (newStyles !== oldStyles)) {
  25371. forEach(oldStyles, function(val, style) { element.css(style, '');});
  25372. }
  25373. if (newStyles) element.css(newStyles);
  25374. }, true);
  25375. });
  25376. /**
  25377. * @ngdoc directive
  25378. * @name ngSwitch
  25379. * @restrict EA
  25380. *
  25381. * @description
  25382. * The `ngSwitch` directive is used to conditionally swap DOM structure on your template based on a scope expression.
  25383. * Elements within `ngSwitch` but without `ngSwitchWhen` or `ngSwitchDefault` directives will be preserved at the location
  25384. * as specified in the template.
  25385. *
  25386. * The directive itself works similar to ngInclude, however, instead of downloading template code (or loading it
  25387. * from the template cache), `ngSwitch` simply chooses one of the nested elements and makes it visible based on which element
  25388. * matches the value obtained from the evaluated expression. In other words, you define a container element
  25389. * (where you place the directive), place an expression on the **`on="..."` attribute**
  25390. * (or the **`ng-switch="..."` attribute**), define any inner elements inside of the directive and place
  25391. * a when attribute per element. The when attribute is used to inform ngSwitch which element to display when the on
  25392. * expression is evaluated. If a matching expression is not found via a when attribute then an element with the default
  25393. * attribute is displayed.
  25394. *
  25395. * <div class="alert alert-info">
  25396. * Be aware that the attribute values to match against cannot be expressions. They are interpreted
  25397. * as literal string values to match against.
  25398. * For example, **`ng-switch-when="someVal"`** will match against the string `"someVal"` not against the
  25399. * value of the expression `$scope.someVal`.
  25400. * </div>
  25401. * @animations
  25402. * enter - happens after the ngSwitch contents change and the matched child element is placed inside the container
  25403. * leave - happens just after the ngSwitch contents change and just before the former contents are removed from the DOM
  25404. *
  25405. * @usage
  25406. *
  25407. * ```
  25408. * <ANY ng-switch="expression">
  25409. * <ANY ng-switch-when="matchValue1">...</ANY>
  25410. * <ANY ng-switch-when="matchValue2">...</ANY>
  25411. * <ANY ng-switch-default>...</ANY>
  25412. * </ANY>
  25413. * ```
  25414. *
  25415. *
  25416. * @scope
  25417. * @priority 1200
  25418. * @param {*} ngSwitch|on expression to match against <code>ng-switch-when</code>.
  25419. * On child elements add:
  25420. *
  25421. * * `ngSwitchWhen`: the case statement to match against. If match then this
  25422. * case will be displayed. If the same match appears multiple times, all the
  25423. * elements will be displayed.
  25424. * * `ngSwitchDefault`: the default case when no other case match. If there
  25425. * are multiple default cases, all of them will be displayed when no other
  25426. * case match.
  25427. *
  25428. *
  25429. * @example
  25430. <example module="switchExample" deps="angular-animate.js" animations="true">
  25431. <file name="index.html">
  25432. <div ng-controller="ExampleController">
  25433. <select ng-model="selection" ng-options="item for item in items">
  25434. </select>
  25435. <code>selection={{selection}}</code>
  25436. <hr/>
  25437. <div class="animate-switch-container"
  25438. ng-switch on="selection">
  25439. <div class="animate-switch" ng-switch-when="settings">Settings Div</div>
  25440. <div class="animate-switch" ng-switch-when="home">Home Span</div>
  25441. <div class="animate-switch" ng-switch-default>default</div>
  25442. </div>
  25443. </div>
  25444. </file>
  25445. <file name="script.js">
  25446. angular.module('switchExample', ['ngAnimate'])
  25447. .controller('ExampleController', ['$scope', function($scope) {
  25448. $scope.items = ['settings', 'home', 'other'];
  25449. $scope.selection = $scope.items[0];
  25450. }]);
  25451. </file>
  25452. <file name="animations.css">
  25453. .animate-switch-container {
  25454. position:relative;
  25455. background:white;
  25456. border:1px solid black;
  25457. height:40px;
  25458. overflow:hidden;
  25459. }
  25460. .animate-switch {
  25461. padding:10px;
  25462. }
  25463. .animate-switch.ng-animate {
  25464. transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
  25465. position:absolute;
  25466. top:0;
  25467. left:0;
  25468. right:0;
  25469. bottom:0;
  25470. }
  25471. .animate-switch.ng-leave.ng-leave-active,
  25472. .animate-switch.ng-enter {
  25473. top:-50px;
  25474. }
  25475. .animate-switch.ng-leave,
  25476. .animate-switch.ng-enter.ng-enter-active {
  25477. top:0;
  25478. }
  25479. </file>
  25480. <file name="protractor.js" type="protractor">
  25481. var switchElem = element(by.css('[ng-switch]'));
  25482. var select = element(by.model('selection'));
  25483. it('should start in settings', function() {
  25484. expect(switchElem.getText()).toMatch(/Settings Div/);
  25485. });
  25486. it('should change to home', function() {
  25487. select.all(by.css('option')).get(1).click();
  25488. expect(switchElem.getText()).toMatch(/Home Span/);
  25489. });
  25490. it('should select default', function() {
  25491. select.all(by.css('option')).get(2).click();
  25492. expect(switchElem.getText()).toMatch(/default/);
  25493. });
  25494. </file>
  25495. </example>
  25496. */
  25497. var ngSwitchDirective = ['$animate', function($animate) {
  25498. return {
  25499. require: 'ngSwitch',
  25500. // asks for $scope to fool the BC controller module
  25501. controller: ['$scope', function ngSwitchController() {
  25502. this.cases = {};
  25503. }],
  25504. link: function(scope, element, attr, ngSwitchController) {
  25505. var watchExpr = attr.ngSwitch || attr.on,
  25506. selectedTranscludes = [],
  25507. selectedElements = [],
  25508. previousLeaveAnimations = [],
  25509. selectedScopes = [];
  25510. var spliceFactory = function(array, index) {
  25511. return function() { array.splice(index, 1); };
  25512. };
  25513. scope.$watch(watchExpr, function ngSwitchWatchAction(value) {
  25514. var i, ii;
  25515. for (i = 0, ii = previousLeaveAnimations.length; i < ii; ++i) {
  25516. $animate.cancel(previousLeaveAnimations[i]);
  25517. }
  25518. previousLeaveAnimations.length = 0;
  25519. for (i = 0, ii = selectedScopes.length; i < ii; ++i) {
  25520. var selected = getBlockNodes(selectedElements[i].clone);
  25521. selectedScopes[i].$destroy();
  25522. var promise = previousLeaveAnimations[i] = $animate.leave(selected);
  25523. promise.then(spliceFactory(previousLeaveAnimations, i));
  25524. }
  25525. selectedElements.length = 0;
  25526. selectedScopes.length = 0;
  25527. if ((selectedTranscludes = ngSwitchController.cases['!' + value] || ngSwitchController.cases['?'])) {
  25528. forEach(selectedTranscludes, function(selectedTransclude) {
  25529. selectedTransclude.transclude(function(caseElement, selectedScope) {
  25530. selectedScopes.push(selectedScope);
  25531. var anchor = selectedTransclude.element;
  25532. caseElement[caseElement.length++] = document.createComment(' end ngSwitchWhen: ');
  25533. var block = { clone: caseElement };
  25534. selectedElements.push(block);
  25535. $animate.enter(caseElement, anchor.parent(), anchor);
  25536. });
  25537. });
  25538. }
  25539. });
  25540. }
  25541. };
  25542. }];
  25543. var ngSwitchWhenDirective = ngDirective({
  25544. transclude: 'element',
  25545. priority: 1200,
  25546. require: '^ngSwitch',
  25547. multiElement: true,
  25548. link: function(scope, element, attrs, ctrl, $transclude) {
  25549. ctrl.cases['!' + attrs.ngSwitchWhen] = (ctrl.cases['!' + attrs.ngSwitchWhen] || []);
  25550. ctrl.cases['!' + attrs.ngSwitchWhen].push({ transclude: $transclude, element: element });
  25551. }
  25552. });
  25553. var ngSwitchDefaultDirective = ngDirective({
  25554. transclude: 'element',
  25555. priority: 1200,
  25556. require: '^ngSwitch',
  25557. multiElement: true,
  25558. link: function(scope, element, attr, ctrl, $transclude) {
  25559. ctrl.cases['?'] = (ctrl.cases['?'] || []);
  25560. ctrl.cases['?'].push({ transclude: $transclude, element: element });
  25561. }
  25562. });
  25563. /**
  25564. * @ngdoc directive
  25565. * @name ngTransclude
  25566. * @restrict EAC
  25567. *
  25568. * @description
  25569. * Directive that marks the insertion point for the transcluded DOM of the nearest parent directive that uses transclusion.
  25570. *
  25571. * Any existing content of the element that this directive is placed on will be removed before the transcluded content is inserted.
  25572. *
  25573. * @element ANY
  25574. *
  25575. * @example
  25576. <example module="transcludeExample">
  25577. <file name="index.html">
  25578. <script>
  25579. angular.module('transcludeExample', [])
  25580. .directive('pane', function(){
  25581. return {
  25582. restrict: 'E',
  25583. transclude: true,
  25584. scope: { title:'@' },
  25585. template: '<div style="border: 1px solid black;">' +
  25586. '<div style="background-color: gray">{{title}}</div>' +
  25587. '<ng-transclude></ng-transclude>' +
  25588. '</div>'
  25589. };
  25590. })
  25591. .controller('ExampleController', ['$scope', function($scope) {
  25592. $scope.title = 'Lorem Ipsum';
  25593. $scope.text = 'Neque porro quisquam est qui dolorem ipsum quia dolor...';
  25594. }]);
  25595. </script>
  25596. <div ng-controller="ExampleController">
  25597. <input ng-model="title" aria-label="title"> <br/>
  25598. <textarea ng-model="text" aria-label="text"></textarea> <br/>
  25599. <pane title="{{title}}">{{text}}</pane>
  25600. </div>
  25601. </file>
  25602. <file name="protractor.js" type="protractor">
  25603. it('should have transcluded', function() {
  25604. var titleElement = element(by.model('title'));
  25605. titleElement.clear();
  25606. titleElement.sendKeys('TITLE');
  25607. var textElement = element(by.model('text'));
  25608. textElement.clear();
  25609. textElement.sendKeys('TEXT');
  25610. expect(element(by.binding('title')).getText()).toEqual('TITLE');
  25611. expect(element(by.binding('text')).getText()).toEqual('TEXT');
  25612. });
  25613. </file>
  25614. </example>
  25615. *
  25616. */
  25617. var ngTranscludeDirective = ngDirective({
  25618. restrict: 'EAC',
  25619. link: function($scope, $element, $attrs, controller, $transclude) {
  25620. if (!$transclude) {
  25621. throw minErr('ngTransclude')('orphan',
  25622. 'Illegal use of ngTransclude directive in the template! ' +
  25623. 'No parent directive that requires a transclusion found. ' +
  25624. 'Element: {0}',
  25625. startingTag($element));
  25626. }
  25627. $transclude(function(clone) {
  25628. $element.empty();
  25629. $element.append(clone);
  25630. });
  25631. }
  25632. });
  25633. /**
  25634. * @ngdoc directive
  25635. * @name script
  25636. * @restrict E
  25637. *
  25638. * @description
  25639. * Load the content of a `<script>` element into {@link ng.$templateCache `$templateCache`}, so that the
  25640. * template can be used by {@link ng.directive:ngInclude `ngInclude`},
  25641. * {@link ngRoute.directive:ngView `ngView`}, or {@link guide/directive directives}. The type of the
  25642. * `<script>` element must be specified as `text/ng-template`, and a cache name for the template must be
  25643. * assigned through the element's `id`, which can then be used as a directive's `templateUrl`.
  25644. *
  25645. * @param {string} type Must be set to `'text/ng-template'`.
  25646. * @param {string} id Cache name of the template.
  25647. *
  25648. * @example
  25649. <example>
  25650. <file name="index.html">
  25651. <script type="text/ng-template" id="/tpl.html">
  25652. Content of the template.
  25653. </script>
  25654. <a ng-click="currentTpl='/tpl.html'" id="tpl-link">Load inlined template</a>
  25655. <div id="tpl-content" ng-include src="currentTpl"></div>
  25656. </file>
  25657. <file name="protractor.js" type="protractor">
  25658. it('should load template defined inside script tag', function() {
  25659. element(by.css('#tpl-link')).click();
  25660. expect(element(by.css('#tpl-content')).getText()).toMatch(/Content of the template/);
  25661. });
  25662. </file>
  25663. </example>
  25664. */
  25665. var scriptDirective = ['$templateCache', function($templateCache) {
  25666. return {
  25667. restrict: 'E',
  25668. terminal: true,
  25669. compile: function(element, attr) {
  25670. if (attr.type == 'text/ng-template') {
  25671. var templateUrl = attr.id,
  25672. text = element[0].text;
  25673. $templateCache.put(templateUrl, text);
  25674. }
  25675. }
  25676. };
  25677. }];
  25678. var noopNgModelController = { $setViewValue: noop, $render: noop };
  25679. /**
  25680. * @ngdoc type
  25681. * @name select.SelectController
  25682. * @description
  25683. * The controller for the `<select>` directive. This provides support for reading
  25684. * and writing the selected value(s) of the control and also coordinates dynamically
  25685. * added `<option>` elements, perhaps by an `ngRepeat` directive.
  25686. */
  25687. var SelectController =
  25688. ['$element', '$scope', '$attrs', function($element, $scope, $attrs) {
  25689. var self = this,
  25690. optionsMap = new HashMap();
  25691. // If the ngModel doesn't get provided then provide a dummy noop version to prevent errors
  25692. self.ngModelCtrl = noopNgModelController;
  25693. // The "unknown" option is one that is prepended to the list if the viewValue
  25694. // does not match any of the options. When it is rendered the value of the unknown
  25695. // option is '? XXX ?' where XXX is the hashKey of the value that is not known.
  25696. //
  25697. // We can't just jqLite('<option>') since jqLite is not smart enough
  25698. // to create it in <select> and IE barfs otherwise.
  25699. self.unknownOption = jqLite(document.createElement('option'));
  25700. self.renderUnknownOption = function(val) {
  25701. var unknownVal = '? ' + hashKey(val) + ' ?';
  25702. self.unknownOption.val(unknownVal);
  25703. $element.prepend(self.unknownOption);
  25704. $element.val(unknownVal);
  25705. };
  25706. $scope.$on('$destroy', function() {
  25707. // disable unknown option so that we don't do work when the whole select is being destroyed
  25708. self.renderUnknownOption = noop;
  25709. });
  25710. self.removeUnknownOption = function() {
  25711. if (self.unknownOption.parent()) self.unknownOption.remove();
  25712. };
  25713. // Read the value of the select control, the implementation of this changes depending
  25714. // upon whether the select can have multiple values and whether ngOptions is at work.
  25715. self.readValue = function readSingleValue() {
  25716. self.removeUnknownOption();
  25717. return $element.val();
  25718. };
  25719. // Write the value to the select control, the implementation of this changes depending
  25720. // upon whether the select can have multiple values and whether ngOptions is at work.
  25721. self.writeValue = function writeSingleValue(value) {
  25722. if (self.hasOption(value)) {
  25723. self.removeUnknownOption();
  25724. $element.val(value);
  25725. if (value === '') self.emptyOption.prop('selected', true); // to make IE9 happy
  25726. } else {
  25727. if (value == null && self.emptyOption) {
  25728. self.removeUnknownOption();
  25729. $element.val('');
  25730. } else {
  25731. self.renderUnknownOption(value);
  25732. }
  25733. }
  25734. };
  25735. // Tell the select control that an option, with the given value, has been added
  25736. self.addOption = function(value, element) {
  25737. assertNotHasOwnProperty(value, '"option value"');
  25738. if (value === '') {
  25739. self.emptyOption = element;
  25740. }
  25741. var count = optionsMap.get(value) || 0;
  25742. optionsMap.put(value, count + 1);
  25743. };
  25744. // Tell the select control that an option, with the given value, has been removed
  25745. self.removeOption = function(value) {
  25746. var count = optionsMap.get(value);
  25747. if (count) {
  25748. if (count === 1) {
  25749. optionsMap.remove(value);
  25750. if (value === '') {
  25751. self.emptyOption = undefined;
  25752. }
  25753. } else {
  25754. optionsMap.put(value, count - 1);
  25755. }
  25756. }
  25757. };
  25758. // Check whether the select control has an option matching the given value
  25759. self.hasOption = function(value) {
  25760. return !!optionsMap.get(value);
  25761. };
  25762. }];
  25763. /**
  25764. * @ngdoc directive
  25765. * @name select
  25766. * @restrict E
  25767. *
  25768. * @description
  25769. * HTML `SELECT` element with angular data-binding.
  25770. *
  25771. * The `select` directive is used together with {@link ngModel `ngModel`} to provide data-binding
  25772. * between the scope and the `<select>` control (including setting default values).
  25773. * Ìt also handles dynamic `<option>` elements, which can be added using the {@link ngRepeat `ngRepeat}` or
  25774. * {@link ngOptions `ngOptions`} directives.
  25775. *
  25776. * When an item in the `<select>` menu is selected, the value of the selected option will be bound
  25777. * to the model identified by the `ngModel` directive. With static or repeated options, this is
  25778. * the content of the `value` attribute or the textContent of the `<option>`, if the value attribute is missing.
  25779. * If you want dynamic value attributes, you can use interpolation inside the value attribute.
  25780. *
  25781. * <div class="alert alert-warning">
  25782. * Note that the value of a `select` directive used without `ngOptions` is always a string.
  25783. * When the model needs to be bound to a non-string value, you must either explictly convert it
  25784. * using a directive (see example below) or use `ngOptions` to specify the set of options.
  25785. * This is because an option element can only be bound to string values at present.
  25786. * </div>
  25787. *
  25788. * If the viewValue of `ngModel` does not match any of the options, then the control
  25789. * will automatically add an "unknown" option, which it then removes when the mismatch is resolved.
  25790. *
  25791. * Optionally, a single hard-coded `<option>` element, with the value set to an empty string, can
  25792. * be nested into the `<select>` element. This element will then represent the `null` or "not selected"
  25793. * option. See example below for demonstration.
  25794. *
  25795. * <div class="alert alert-info">
  25796. * In many cases, `ngRepeat` can be used on `<option>` elements instead of {@link ng.directive:ngOptions
  25797. * ngOptions} to achieve a similar result. However, `ngOptions` provides some benefits, such as
  25798. * more flexibility in how the `<select>`'s model is assigned via the `select` **`as`** part of the
  25799. * comprehension expression, and additionally in reducing memory and increasing speed by not creating
  25800. * a new scope for each repeated instance.
  25801. * </div>
  25802. *
  25803. *
  25804. * @param {string} ngModel Assignable angular expression to data-bind to.
  25805. * @param {string=} name Property name of the form under which the control is published.
  25806. * @param {string=} required Sets `required` validation error key if the value is not entered.
  25807. * @param {string=} ngRequired Adds required attribute and required validation constraint to
  25808. * the element when the ngRequired expression evaluates to true. Use ngRequired instead of required
  25809. * when you want to data-bind to the required attribute.
  25810. * @param {string=} ngChange Angular expression to be executed when selected option(s) changes due to user
  25811. * interaction with the select element.
  25812. * @param {string=} ngOptions sets the options that the select is populated with and defines what is
  25813. * set on the model on selection. See {@link ngOptions `ngOptions`}.
  25814. *
  25815. * @example
  25816. * ### Simple `select` elements with static options
  25817. *
  25818. * <example name="static-select" module="staticSelect">
  25819. * <file name="index.html">
  25820. * <div ng-controller="ExampleController">
  25821. * <form name="myForm">
  25822. * <label for="singleSelect"> Single select: </label><br>
  25823. * <select name="singleSelect" ng-model="data.singleSelect">
  25824. * <option value="option-1">Option 1</option>
  25825. * <option value="option-2">Option 2</option>
  25826. * </select><br>
  25827. *
  25828. * <label for="singleSelect"> Single select with "not selected" option and dynamic option values: </label><br>
  25829. * <select name="singleSelect" ng-model="data.singleSelect">
  25830. * <option value="">---Please select---</option> <!-- not selected / blank option -->
  25831. * <option value="{{data.option1}}">Option 1</option> <!-- interpolation -->
  25832. * <option value="option-2">Option 2</option>
  25833. * </select><br>
  25834. * <button ng-click="forceUnknownOption()">Force unknown option</button><br>
  25835. * <tt>singleSelect = {{data.singleSelect}}</tt>
  25836. *
  25837. * <hr>
  25838. * <label for="multipleSelect"> Multiple select: </label><br>
  25839. * <select name="multipleSelect" id="multipleSelect" ng-model="data.multipleSelect" multiple>
  25840. * <option value="option-1">Option 1</option>
  25841. * <option value="option-2">Option 2</option>
  25842. * <option value="option-3">Option 3</option>
  25843. * </select><br>
  25844. * <tt>multipleSelect = {{data.multipleSelect}}</tt><br/>
  25845. * </form>
  25846. * </div>
  25847. * </file>
  25848. * <file name="app.js">
  25849. * angular.module('staticSelect', [])
  25850. * .controller('ExampleController', ['$scope', function($scope) {
  25851. * $scope.data = {
  25852. * singleSelect: null,
  25853. * multipleSelect: [],
  25854. * option1: 'option-1',
  25855. * };
  25856. *
  25857. * $scope.forceUnknownOption = function() {
  25858. * $scope.data.singleSelect = 'nonsense';
  25859. * };
  25860. * }]);
  25861. * </file>
  25862. *</example>
  25863. *
  25864. * ### Using `ngRepeat` to generate `select` options
  25865. * <example name="ngrepeat-select" module="ngrepeatSelect">
  25866. * <file name="index.html">
  25867. * <div ng-controller="ExampleController">
  25868. * <form name="myForm">
  25869. * <label for="repeatSelect"> Repeat select: </label>
  25870. * <select name="repeatSelect" ng-model="data.repeatSelect">
  25871. * <option ng-repeat="option in data.availableOptions" value="{{option.id}}">{{option.name}}</option>
  25872. * </select>
  25873. * </form>
  25874. * <hr>
  25875. * <tt>repeatSelect = {{data.repeatSelect}}</tt><br/>
  25876. * </div>
  25877. * </file>
  25878. * <file name="app.js">
  25879. * angular.module('ngrepeatSelect', [])
  25880. * .controller('ExampleController', ['$scope', function($scope) {
  25881. * $scope.data = {
  25882. * singleSelect: null,
  25883. * availableOptions: [
  25884. * {id: '1', name: 'Option A'},
  25885. * {id: '2', name: 'Option B'},
  25886. * {id: '3', name: 'Option C'}
  25887. * ],
  25888. * };
  25889. * }]);
  25890. * </file>
  25891. *</example>
  25892. *
  25893. *
  25894. * ### Using `select` with `ngOptions` and setting a default value
  25895. * See the {@link ngOptions ngOptions documentation} for more `ngOptions` usage examples.
  25896. *
  25897. * <example name="select-with-default-values" module="defaultValueSelect">
  25898. * <file name="index.html">
  25899. * <div ng-controller="ExampleController">
  25900. * <form name="myForm">
  25901. * <label for="mySelect">Make a choice:</label>
  25902. * <select name="mySelect" id="mySelect"
  25903. * ng-options="option.name for option in data.availableOptions track by option.id"
  25904. * ng-model="data.selectedOption"></select>
  25905. * </form>
  25906. * <hr>
  25907. * <tt>option = {{data.selectedOption}}</tt><br/>
  25908. * </div>
  25909. * </file>
  25910. * <file name="app.js">
  25911. * angular.module('defaultValueSelect', [])
  25912. * .controller('ExampleController', ['$scope', function($scope) {
  25913. * $scope.data = {
  25914. * availableOptions: [
  25915. * {id: '1', name: 'Option A'},
  25916. * {id: '2', name: 'Option B'},
  25917. * {id: '3', name: 'Option C'}
  25918. * ],
  25919. * selectedOption: {id: '3', name: 'Option C'} //This sets the default value of the select in the ui
  25920. * };
  25921. * }]);
  25922. * </file>
  25923. *</example>
  25924. *
  25925. *
  25926. * ### Binding `select` to a non-string value via `ngModel` parsing / formatting
  25927. *
  25928. * <example name="select-with-non-string-options" module="nonStringSelect">
  25929. * <file name="index.html">
  25930. * <select ng-model="model.id" convert-to-number>
  25931. * <option value="0">Zero</option>
  25932. * <option value="1">One</option>
  25933. * <option value="2">Two</option>
  25934. * </select>
  25935. * {{ model }}
  25936. * </file>
  25937. * <file name="app.js">
  25938. * angular.module('nonStringSelect', [])
  25939. * .run(function($rootScope) {
  25940. * $rootScope.model = { id: 2 };
  25941. * })
  25942. * .directive('convertToNumber', function() {
  25943. * return {
  25944. * require: 'ngModel',
  25945. * link: function(scope, element, attrs, ngModel) {
  25946. * ngModel.$parsers.push(function(val) {
  25947. * return parseInt(val, 10);
  25948. * });
  25949. * ngModel.$formatters.push(function(val) {
  25950. * return '' + val;
  25951. * });
  25952. * }
  25953. * };
  25954. * });
  25955. * </file>
  25956. * <file name="protractor.js" type="protractor">
  25957. * it('should initialize to model', function() {
  25958. * var select = element(by.css('select'));
  25959. * expect(element(by.model('model.id')).$('option:checked').getText()).toEqual('Two');
  25960. * });
  25961. * </file>
  25962. * </example>
  25963. *
  25964. */
  25965. var selectDirective = function() {
  25966. return {
  25967. restrict: 'E',
  25968. require: ['select', '?ngModel'],
  25969. controller: SelectController,
  25970. link: function(scope, element, attr, ctrls) {
  25971. // if ngModel is not defined, we don't need to do anything
  25972. var ngModelCtrl = ctrls[1];
  25973. if (!ngModelCtrl) return;
  25974. var selectCtrl = ctrls[0];
  25975. selectCtrl.ngModelCtrl = ngModelCtrl;
  25976. // We delegate rendering to the `writeValue` method, which can be changed
  25977. // if the select can have multiple selected values or if the options are being
  25978. // generated by `ngOptions`
  25979. ngModelCtrl.$render = function() {
  25980. selectCtrl.writeValue(ngModelCtrl.$viewValue);
  25981. };
  25982. // When the selected item(s) changes we delegate getting the value of the select control
  25983. // to the `readValue` method, which can be changed if the select can have multiple
  25984. // selected values or if the options are being generated by `ngOptions`
  25985. element.on('change', function() {
  25986. scope.$apply(function() {
  25987. ngModelCtrl.$setViewValue(selectCtrl.readValue());
  25988. });
  25989. });
  25990. // If the select allows multiple values then we need to modify how we read and write
  25991. // values from and to the control; also what it means for the value to be empty and
  25992. // we have to add an extra watch since ngModel doesn't work well with arrays - it
  25993. // doesn't trigger rendering if only an item in the array changes.
  25994. if (attr.multiple) {
  25995. // Read value now needs to check each option to see if it is selected
  25996. selectCtrl.readValue = function readMultipleValue() {
  25997. var array = [];
  25998. forEach(element.find('option'), function(option) {
  25999. if (option.selected) {
  26000. array.push(option.value);
  26001. }
  26002. });
  26003. return array;
  26004. };
  26005. // Write value now needs to set the selected property of each matching option
  26006. selectCtrl.writeValue = function writeMultipleValue(value) {
  26007. var items = new HashMap(value);
  26008. forEach(element.find('option'), function(option) {
  26009. option.selected = isDefined(items.get(option.value));
  26010. });
  26011. };
  26012. // we have to do it on each watch since ngModel watches reference, but
  26013. // we need to work of an array, so we need to see if anything was inserted/removed
  26014. var lastView, lastViewRef = NaN;
  26015. scope.$watch(function selectMultipleWatch() {
  26016. if (lastViewRef === ngModelCtrl.$viewValue && !equals(lastView, ngModelCtrl.$viewValue)) {
  26017. lastView = shallowCopy(ngModelCtrl.$viewValue);
  26018. ngModelCtrl.$render();
  26019. }
  26020. lastViewRef = ngModelCtrl.$viewValue;
  26021. });
  26022. // If we are a multiple select then value is now a collection
  26023. // so the meaning of $isEmpty changes
  26024. ngModelCtrl.$isEmpty = function(value) {
  26025. return !value || value.length === 0;
  26026. };
  26027. }
  26028. }
  26029. };
  26030. };
  26031. // The option directive is purely designed to communicate the existence (or lack of)
  26032. // of dynamically created (and destroyed) option elements to their containing select
  26033. // directive via its controller.
  26034. var optionDirective = ['$interpolate', function($interpolate) {
  26035. function chromeHack(optionElement) {
  26036. // Workaround for https://code.google.com/p/chromium/issues/detail?id=381459
  26037. // Adding an <option selected="selected"> element to a <select required="required"> should
  26038. // automatically select the new element
  26039. if (optionElement[0].hasAttribute('selected')) {
  26040. optionElement[0].selected = true;
  26041. }
  26042. }
  26043. return {
  26044. restrict: 'E',
  26045. priority: 100,
  26046. compile: function(element, attr) {
  26047. if (isDefined(attr.value)) {
  26048. // If the value attribute is defined, check if it contains an interpolation
  26049. var valueInterpolated = $interpolate(attr.value, true);
  26050. } else {
  26051. // If the value attribute is not defined then we fall back to the
  26052. // text content of the option element, which may be interpolated
  26053. var interpolateFn = $interpolate(element.text(), true);
  26054. if (!interpolateFn) {
  26055. attr.$set('value', element.text());
  26056. }
  26057. }
  26058. return function(scope, element, attr) {
  26059. // This is an optimization over using ^^ since we don't want to have to search
  26060. // all the way to the root of the DOM for every single option element
  26061. var selectCtrlName = '$selectController',
  26062. parent = element.parent(),
  26063. selectCtrl = parent.data(selectCtrlName) ||
  26064. parent.parent().data(selectCtrlName); // in case we are in optgroup
  26065. function addOption(optionValue) {
  26066. selectCtrl.addOption(optionValue, element);
  26067. selectCtrl.ngModelCtrl.$render();
  26068. chromeHack(element);
  26069. }
  26070. // Only update trigger option updates if this is an option within a `select`
  26071. // that also has `ngModel` attached
  26072. if (selectCtrl && selectCtrl.ngModelCtrl) {
  26073. if (valueInterpolated) {
  26074. // The value attribute is interpolated
  26075. var oldVal;
  26076. attr.$observe('value', function valueAttributeObserveAction(newVal) {
  26077. if (isDefined(oldVal)) {
  26078. selectCtrl.removeOption(oldVal);
  26079. }
  26080. oldVal = newVal;
  26081. addOption(newVal);
  26082. });
  26083. } else if (interpolateFn) {
  26084. // The text content is interpolated
  26085. scope.$watch(interpolateFn, function interpolateWatchAction(newVal, oldVal) {
  26086. attr.$set('value', newVal);
  26087. if (oldVal !== newVal) {
  26088. selectCtrl.removeOption(oldVal);
  26089. }
  26090. addOption(newVal);
  26091. });
  26092. } else {
  26093. // The value attribute is static
  26094. addOption(attr.value);
  26095. }
  26096. element.on('$destroy', function() {
  26097. selectCtrl.removeOption(attr.value);
  26098. selectCtrl.ngModelCtrl.$render();
  26099. });
  26100. }
  26101. };
  26102. }
  26103. };
  26104. }];
  26105. var styleDirective = valueFn({
  26106. restrict: 'E',
  26107. terminal: false
  26108. });
  26109. var requiredDirective = function() {
  26110. return {
  26111. restrict: 'A',
  26112. require: '?ngModel',
  26113. link: function(scope, elm, attr, ctrl) {
  26114. if (!ctrl) return;
  26115. attr.required = true; // force truthy in case we are on non input element
  26116. ctrl.$validators.required = function(modelValue, viewValue) {
  26117. return !attr.required || !ctrl.$isEmpty(viewValue);
  26118. };
  26119. attr.$observe('required', function() {
  26120. ctrl.$validate();
  26121. });
  26122. }
  26123. };
  26124. };
  26125. var patternDirective = function() {
  26126. return {
  26127. restrict: 'A',
  26128. require: '?ngModel',
  26129. link: function(scope, elm, attr, ctrl) {
  26130. if (!ctrl) return;
  26131. var regexp, patternExp = attr.ngPattern || attr.pattern;
  26132. attr.$observe('pattern', function(regex) {
  26133. if (isString(regex) && regex.length > 0) {
  26134. regex = new RegExp('^' + regex + '$');
  26135. }
  26136. if (regex && !regex.test) {
  26137. throw minErr('ngPattern')('noregexp',
  26138. 'Expected {0} to be a RegExp but was {1}. Element: {2}', patternExp,
  26139. regex, startingTag(elm));
  26140. }
  26141. regexp = regex || undefined;
  26142. ctrl.$validate();
  26143. });
  26144. ctrl.$validators.pattern = function(modelValue, viewValue) {
  26145. // HTML5 pattern constraint validates the input value, so we validate the viewValue
  26146. return ctrl.$isEmpty(viewValue) || isUndefined(regexp) || regexp.test(viewValue);
  26147. };
  26148. }
  26149. };
  26150. };
  26151. var maxlengthDirective = function() {
  26152. return {
  26153. restrict: 'A',
  26154. require: '?ngModel',
  26155. link: function(scope, elm, attr, ctrl) {
  26156. if (!ctrl) return;
  26157. var maxlength = -1;
  26158. attr.$observe('maxlength', function(value) {
  26159. var intVal = toInt(value);
  26160. maxlength = isNaN(intVal) ? -1 : intVal;
  26161. ctrl.$validate();
  26162. });
  26163. ctrl.$validators.maxlength = function(modelValue, viewValue) {
  26164. return (maxlength < 0) || ctrl.$isEmpty(viewValue) || (viewValue.length <= maxlength);
  26165. };
  26166. }
  26167. };
  26168. };
  26169. var minlengthDirective = function() {
  26170. return {
  26171. restrict: 'A',
  26172. require: '?ngModel',
  26173. link: function(scope, elm, attr, ctrl) {
  26174. if (!ctrl) return;
  26175. var minlength = 0;
  26176. attr.$observe('minlength', function(value) {
  26177. minlength = toInt(value) || 0;
  26178. ctrl.$validate();
  26179. });
  26180. ctrl.$validators.minlength = function(modelValue, viewValue) {
  26181. return ctrl.$isEmpty(viewValue) || viewValue.length >= minlength;
  26182. };
  26183. }
  26184. };
  26185. };
  26186. if (window.angular.bootstrap) {
  26187. //AngularJS is already loaded, so we can return here...
  26188. console.log('WARNING: Tried to load angular more than once.');
  26189. return;
  26190. }
  26191. //try to bind to jquery now so that one can write jqLite(document).ready()
  26192. //but we will rebind on bootstrap again.
  26193. bindJQuery();
  26194. publishExternalAPI(angular);
  26195. angular.module("ngLocale", [], ["$provide", function($provide) {
  26196. var PLURAL_CATEGORY = {ZERO: "zero", ONE: "one", TWO: "two", FEW: "few", MANY: "many", OTHER: "other"};
  26197. function getDecimals(n) {
  26198. n = n + '';
  26199. var i = n.indexOf('.');
  26200. return (i == -1) ? 0 : n.length - i - 1;
  26201. }
  26202. function getVF(n, opt_precision) {
  26203. var v = opt_precision;
  26204. if (undefined === v) {
  26205. v = Math.min(getDecimals(n), 3);
  26206. }
  26207. var base = Math.pow(10, v);
  26208. var f = ((n * base) | 0) % base;
  26209. return {v: v, f: f};
  26210. }
  26211. $provide.value("$locale", {
  26212. "DATETIME_FORMATS": {
  26213. "AMPMS": [
  26214. "AM",
  26215. "PM"
  26216. ],
  26217. "DAY": [
  26218. "Sunday",
  26219. "Monday",
  26220. "Tuesday",
  26221. "Wednesday",
  26222. "Thursday",
  26223. "Friday",
  26224. "Saturday"
  26225. ],
  26226. "ERANAMES": [
  26227. "Before Christ",
  26228. "Anno Domini"
  26229. ],
  26230. "ERAS": [
  26231. "BC",
  26232. "AD"
  26233. ],
  26234. "FIRSTDAYOFWEEK": 6,
  26235. "MONTH": [
  26236. "January",
  26237. "February",
  26238. "March",
  26239. "April",
  26240. "May",
  26241. "June",
  26242. "July",
  26243. "August",
  26244. "September",
  26245. "October",
  26246. "November",
  26247. "December"
  26248. ],
  26249. "SHORTDAY": [
  26250. "Sun",
  26251. "Mon",
  26252. "Tue",
  26253. "Wed",
  26254. "Thu",
  26255. "Fri",
  26256. "Sat"
  26257. ],
  26258. "SHORTMONTH": [
  26259. "Jan",
  26260. "Feb",
  26261. "Mar",
  26262. "Apr",
  26263. "May",
  26264. "Jun",
  26265. "Jul",
  26266. "Aug",
  26267. "Sep",
  26268. "Oct",
  26269. "Nov",
  26270. "Dec"
  26271. ],
  26272. "WEEKENDRANGE": [
  26273. 5,
  26274. 6
  26275. ],
  26276. "fullDate": "EEEE, MMMM d, y",
  26277. "longDate": "MMMM d, y",
  26278. "medium": "MMM d, y h:mm:ss a",
  26279. "mediumDate": "MMM d, y",
  26280. "mediumTime": "h:mm:ss a",
  26281. "short": "M/d/yy h:mm a",
  26282. "shortDate": "M/d/yy",
  26283. "shortTime": "h:mm a"
  26284. },
  26285. "NUMBER_FORMATS": {
  26286. "CURRENCY_SYM": "$",
  26287. "DECIMAL_SEP": ".",
  26288. "GROUP_SEP": ",",
  26289. "PATTERNS": [
  26290. {
  26291. "gSize": 3,
  26292. "lgSize": 3,
  26293. "maxFrac": 3,
  26294. "minFrac": 0,
  26295. "minInt": 1,
  26296. "negPre": "-",
  26297. "negSuf": "",
  26298. "posPre": "",
  26299. "posSuf": ""
  26300. },
  26301. {
  26302. "gSize": 3,
  26303. "lgSize": 3,
  26304. "maxFrac": 2,
  26305. "minFrac": 2,
  26306. "minInt": 1,
  26307. "negPre": "-\u00a4",
  26308. "negSuf": "",
  26309. "posPre": "\u00a4",
  26310. "posSuf": ""
  26311. }
  26312. ]
  26313. },
  26314. "id": "en-us",
  26315. "pluralCat": function(n, opt_precision) { var i = n | 0; var vf = getVF(n, opt_precision); if (i == 1 && vf.v == 0) { return PLURAL_CATEGORY.ONE; } return PLURAL_CATEGORY.OTHER;}
  26316. });
  26317. }]);
  26318. jqLite(document).ready(function() {
  26319. angularInit(document, bootstrap);
  26320. });
  26321. })(window, document);
  26322. !window.angular.$$csp().noInlineStyle && window.angular.element(document.head).prepend('<style type="text/css">@charset "UTF-8";[ng\\:cloak],[ng-cloak],[data-ng-cloak],[x-ng-cloak],.ng-cloak,.x-ng-cloak,.ng-hide:not(.ng-hide-animate){display:none !important;}ng\\:form{display:block;}.ng-animate-shim{visibility:hidden;}.ng-anchor{position:absolute;}</style>');

软件技术创新是当今国家整体创新能力的重要基础和发展引擎。近年来,大众参与的软件创新与创业活动已经成为网络时代软件开发和应用的新形态,正在快速改变着全球软件创新模式和软件产业格局。 ...