diff --git a/examples/bootstrap.html b/examples/bootstrap.html index a1e362b46..bdca6874e 100644 --- a/examples/bootstrap.html +++ b/examples/bootstrap.html @@ -36,28 +36,63 @@ -

Selected: {{person.selected.name}}

+

Selected: + + , + {{p.name}} + +

ui-select inside a Bootstrap form -
- -
+
+ +
- - {{$select.selected.name}} - -
- -
-
+ + {{$select.selected.name}} + +
+ +
+
+
-
-
+
+ +
+ + + {{$select.selected.name}} + +
+ +
+
+ +
+
+ +
+ +
+ + + {{$item.name}} + +
+ +
+
+ +
+
+ +
diff --git a/examples/newdemo.html b/examples/newdemo.html new file mode 100644 index 000000000..f461a54ac --- /dev/null +++ b/examples/newdemo.html @@ -0,0 +1,192 @@ + + + + + AngularJS ui-select + + + + + + + + + + + + + + + + + + +

Selected: {{person.selected.name}}

+ + +
+ ui-select inside a Bootstrap form + +
+ + +
+ + {{$item}} + + {{color}} + + +
+
+ +
+ + + + diff --git a/examples/newdemo.js b/examples/newdemo.js new file mode 100644 index 000000000..7c2b32f83 --- /dev/null +++ b/examples/newdemo.js @@ -0,0 +1,616 @@ +'use strict'; + +var app = angular.module('demo', ['ngSanitize', 'ui.select', 'ui.select.sort', 'ui.select.tagging']); + +/** + * AngularJS default filter with the following expression: + * "person in people | filter: {name: $select.search, age: $select.search}" + * performs a AND between 'name: $select.search' and 'age: $select.search'. + * We want to perform a OR. + */ +app.filter('propsFilter', function () { + return function (items, props) { + var out = []; + + if (angular.isArray(items)) { + items.forEach(function (item) { + var itemMatches = false; + + var keys = Object.keys(props); + for (var i = 0; i < keys.length; i++) { + var prop = keys[i]; + var text = props[prop].toLowerCase(); + if (item[prop].toString().toLowerCase().indexOf(text) !== -1) { + itemMatches = true; + break; + } + } + + if (itemMatches) { + out.push(item); + } + }); + } else { + // Let the output be the input untouched + out = items; + } + + return out; + }; +}); + +app.controller('DemoCtrl', function ($scope, $http, $timeout, $interval) { + $scope.theme = "bootstrap"; + $scope.disabled = undefined; + $scope.searchEnabled = undefined; + + $scope.setInputFocus = function () { + $scope.$broadcast('UiSelectDemo1'); + } + + $scope.enable = function () { + $scope.disabled = false; + }; + + $scope.disable = function () { + $scope.disabled = true; + }; + + $scope.enableSearch = function () { + $scope.searchEnabled = true; + } + + $scope.disableSearch = function () { + $scope.searchEnabled = false; + } + + $scope.clear = function () { + $scope.person.selected = undefined; + $scope.address.selected = undefined; + $scope.country.selected = undefined; + }; + + $scope.someGroupFn = function (item) { + + if (item.name[0] >= 'A' && item.name[0] <= 'M') + return 'From A - M'; + + if (item.name[0] >= 'N' && item.name[0] <= 'Z') + return 'From N - Z'; + + }; + + $scope.firstLetterGroupFn = function (item) { + return item.name[0]; + }; + + $scope.reverseOrderFilterFn = function (groups) { + return groups.reverse(); + }; + + $scope.personAsync = {selected: "wladimir@email.com"}; + $scope.peopleAsync = []; + + $timeout(function () { + $scope.peopleAsync = [ + {name: 'Adam', email: 'adam@email.com', age: 12, country: 'United States'}, + {name: 'Amalie', email: 'amalie@email.com', age: 12, country: 'Argentina'}, + {name: 'Estefanía', email: 'estefania@email.com', age: 21, country: 'Argentina'}, + {name: 'Adrian', email: 'adrian@email.com', age: 21, country: 'Ecuador'}, + {name: 'Wladimir', email: 'wladimir@email.com', age: 30, country: 'Ecuador'}, + {name: 'Samantha', email: 'samantha@email.com', age: 30, country: 'United States'}, + {name: 'Nicole', email: 'nicole@email.com', age: 43, country: 'Colombia'}, + {name: 'Natasha', email: 'natasha@email.com', age: 54, country: 'Ecuador'}, + {name: 'Michael', email: 'michael@email.com', age: 15, country: 'Colombia'}, + {name: 'Nicolás', email: 'nicole@email.com', age: 43, country: 'Colombia'} + ]; + }, 3000); + + $scope.counter = 0; + $scope.someFunction = function (item, model) { + $scope.counter++; + $scope.eventResult = {item: item, model: model}; + }; + + $scope.removed = function (item, model) { + $scope.lastRemoved = { + item: item, + model: model + }; + }; + + $scope.tagTransform = function (newTag) { + var item = { + name: newTag, + email: newTag.toLowerCase() + '@email.com', + age: 'unknown', + country: 'unknown' + }; + + return item; + }; + + $scope.person = {}; + $scope.people = [ + {name: 'Adam', email: 'adam@email.com', age: 12, country: 'United States'}, + {name: 'Amalie', email: 'amalie@email.com', age: 12, country: 'Argentina'}, + {name: 'Estefanía', email: 'estefania@email.com', age: 21, country: 'Argentina'}, + {name: 'Adrian', email: 'adrian@email.com', age: 21, country: 'Ecuador'}, + {name: 'Wladimir', email: 'wladimir@email.com', age: 30, country: 'Ecuador'}, + {name: 'Samantha', email: 'samantha@email.com', age: 30, country: 'United States'}, + {name: 'Nicole', email: 'nicole@email.com', age: 43, country: 'Colombia'}, + {name: 'Natasha', email: 'natasha@email.com', age: 54, country: 'Ecuador'}, + {name: 'Michael', email: 'michael@email.com', age: 15, country: 'Colombia'}, + {name: 'Nicolás', email: 'nicolas@email.com', age: 43, country: 'Colombia'} + ]; + + $scope.people2 = { + adam:{name: 'Adam', email: 'adam@email.com', age: 12, country: 'United States'}, + amalie: {name: 'Amalie', email: 'amalie@email.com', age: 12, country: 'Argentina'}, + estefana: {name: 'Estefanía', email: 'estefania@email.com', age: 21, country: 'Argentina'}, + adriana: {name: 'Adrian', email: 'adrian@email.com', age: 21, country: 'Ecuador'}, + vlad: {name: 'Wladimir', email: 'wladimir@email.com', age: 30, country: 'Ecuador'}, + sam: {name: 'Samantha', email: 'samantha@email.com', age: 30, country: 'United States'}, + nic: {name: 'Nicole', email: 'nicole@email.com', age: 43, country: 'Colombia'}, + nat: {name: 'Natasha', email: 'natasha@email.com', age: 54, country: 'Ecuador'}, + Mic: {name: 'Michael', email: 'michael@email.com', age: 15, country: 'Colombia'}, + nicola: {name: 'Nicolás', email: 'nicolas@email.com', age: 43, country: 'Colombia'} + }; + + $scope.availableColors = ['Red', 'Green', 'Blue', 'Yellow', 'Magenta', 'Maroon', 'Umbra', 'Turquoise']; + + $scope.singleDemo = {}; + $scope.singleDemo.color = ''; + $scope.multipleDemo = {}; + $scope.multipleDemo.colors = ['Blue', 'Red']; + $scope.multipleDemo.colors2 = ['Blue', 'Red']; + $scope.multipleDemo.selectedPeople = [$scope.people[5], $scope.people[4]]; + $scope.multipleDemo.selectedPeople2 = $scope.multipleDemo.selectedPeople; + $scope.multipleDemo.selectedPeopleWithGroupBy = [$scope.people[8], $scope.people[6]]; + $scope.multipleDemo.selectedPeopleSimple = ['samantha@email.com', 'wladimir@email.com']; + + $scope.appendToBodyDemo = { + remainingToggleTime: 0, + present: true, + startToggleTimer: function () { + var scope = $scope.appendToBodyDemo; + var promise = $interval(function () { + if (scope.remainingTime < 1000) { + $interval.cancel(promise); + scope.present = !scope.present; + scope.remainingTime = 0; + } else { + scope.remainingTime -= 1000; + } + }, 1000); + scope.remainingTime = 3000; + } + }; + + $scope.address = {}; + $scope.refreshAddresses = function (address) { + var params = {address: address, sensor: false}; + return $http.get( + 'http://maps.googleapis.com/maps/api/geocode/json', + {params: params} + ).then(function (response) { + $scope.addresses = response.data.results; + }); + }; + + $scope.addPerson = function (item, model) { + if (item.hasOwnProperty('isTag')) { + delete item.isTag; + $scope.people.push(item); + } + } + + $scope.country = {}; + $scope.countries = [ // Taken from https://gist.github.com/unceus/6501985 + {name: 'Afghanistan', code: 'AF'}, + {name: 'Åland Islands', code: 'AX'}, + {name: 'Albania', code: 'AL'}, + {name: 'Algeria', code: 'DZ'}, + {name: 'American Samoa', code: 'AS'}, + {name: 'Andorra', code: 'AD'}, + {name: 'Angola', code: 'AO'}, + {name: 'Anguilla', code: 'AI'}, + {name: 'Antarctica', code: 'AQ'}, + {name: 'Antigua and Barbuda', code: 'AG'}, + {name: 'Argentina', code: 'AR'}, + {name: 'Armenia', code: 'AM'}, + {name: 'Aruba', code: 'AW'}, + {name: 'Australia', code: 'AU'}, + {name: 'Austria', code: 'AT'}, + {name: 'Azerbaijan', code: 'AZ'}, + {name: 'Bahamas', code: 'BS'}, + {name: 'Bahrain', code: 'BH'}, + {name: 'Bangladesh', code: 'BD'}, + {name: 'Barbados', code: 'BB'}, + {name: 'Belarus', code: 'BY'}, + {name: 'Belgium', code: 'BE'}, + {name: 'Belize', code: 'BZ'}, + {name: 'Benin', code: 'BJ'}, + {name: 'Bermuda', code: 'BM'}, + {name: 'Bhutan', code: 'BT'}, + {name: 'Bolivia', code: 'BO'}, + {name: 'Bosnia and Herzegovina', code: 'BA'}, + {name: 'Botswana', code: 'BW'}, + {name: 'Bouvet Island', code: 'BV'}, + {name: 'Brazil', code: 'BR'}, + {name: 'British Indian Ocean Territory', code: 'IO'}, + {name: 'Brunei Darussalam', code: 'BN'}, + {name: 'Bulgaria', code: 'BG'}, + {name: 'Burkina Faso', code: 'BF'}, + {name: 'Burundi', code: 'BI'}, + {name: 'Cambodia', code: 'KH'}, + {name: 'Cameroon', code: 'CM'}, + {name: 'Canada', code: 'CA'}, + {name: 'Cape Verde', code: 'CV'}, + {name: 'Cayman Islands', code: 'KY'}, + {name: 'Central African Republic', code: 'CF'}, + {name: 'Chad', code: 'TD'}, + {name: 'Chile', code: 'CL'}, + {name: 'China', code: 'CN'}, + {name: 'Christmas Island', code: 'CX'}, + {name: 'Cocos (Keeling) Islands', code: 'CC'}, + {name: 'Colombia', code: 'CO'}, + {name: 'Comoros', code: 'KM'}, + {name: 'Congo', code: 'CG'}, + {name: 'Congo, The Democratic Republic of the', code: 'CD'}, + {name: 'Cook Islands', code: 'CK'}, + {name: 'Costa Rica', code: 'CR'}, + {name: 'Cote D\'Ivoire', code: 'CI'}, + {name: 'Croatia', code: 'HR'}, + {name: 'Cuba', code: 'CU'}, + {name: 'Cyprus', code: 'CY'}, + {name: 'Czech Republic', code: 'CZ'}, + {name: 'Denmark', code: 'DK'}, + {name: 'Djibouti', code: 'DJ'}, + {name: 'Dominica', code: 'DM'}, + {name: 'Dominican Republic', code: 'DO'}, + {name: 'Ecuador', code: 'EC'}, + {name: 'Egypt', code: 'EG'}, + {name: 'El Salvador', code: 'SV'}, + {name: 'Equatorial Guinea', code: 'GQ'}, + {name: 'Eritrea', code: 'ER'}, + {name: 'Estonia', code: 'EE'}, + {name: 'Ethiopia', code: 'ET'}, + {name: 'Falkland Islands (Malvinas)', code: 'FK'}, + {name: 'Faroe Islands', code: 'FO'}, + {name: 'Fiji', code: 'FJ'}, + {name: 'Finland', code: 'FI'}, + {name: 'France', code: 'FR'}, + {name: 'French Guiana', code: 'GF'}, + {name: 'French Polynesia', code: 'PF'}, + {name: 'French Southern Territories', code: 'TF'}, + {name: 'Gabon', code: 'GA'}, + {name: 'Gambia', code: 'GM'}, + {name: 'Georgia', code: 'GE'}, + {name: 'Germany', code: 'DE'}, + {name: 'Ghana', code: 'GH'}, + {name: 'Gibraltar', code: 'GI'}, + {name: 'Greece', code: 'GR'}, + {name: 'Greenland', code: 'GL'}, + {name: 'Grenada', code: 'GD'}, + {name: 'Guadeloupe', code: 'GP'}, + {name: 'Guam', code: 'GU'}, + {name: 'Guatemala', code: 'GT'}, + {name: 'Guernsey', code: 'GG'}, + {name: 'Guinea', code: 'GN'}, + {name: 'Guinea-Bissau', code: 'GW'}, + {name: 'Guyana', code: 'GY'}, + {name: 'Haiti', code: 'HT'}, + {name: 'Heard Island and Mcdonald Islands', code: 'HM'}, + {name: 'Holy See (Vatican City State)', code: 'VA'}, + {name: 'Honduras', code: 'HN'}, + {name: 'Hong Kong', code: 'HK'}, + {name: 'Hungary', code: 'HU'}, + {name: 'Iceland', code: 'IS'}, + {name: 'India', code: 'IN'}, + {name: 'Indonesia', code: 'ID'}, + {name: 'Iran, Islamic Republic Of', code: 'IR'}, + {name: 'Iraq', code: 'IQ'}, + {name: 'Ireland', code: 'IE'}, + {name: 'Isle of Man', code: 'IM'}, + {name: 'Israel', code: 'IL'}, + {name: 'Italy', code: 'IT'}, + {name: 'Jamaica', code: 'JM'}, + {name: 'Japan', code: 'JP'}, + {name: 'Jersey', code: 'JE'}, + {name: 'Jordan', code: 'JO'}, + {name: 'Kazakhstan', code: 'KZ'}, + {name: 'Kenya', code: 'KE'}, + {name: 'Kiribati', code: 'KI'}, + {name: 'Korea, Democratic People\'s Republic of', code: 'KP'}, + {name: 'Korea, Republic of', code: 'KR'}, + {name: 'Kuwait', code: 'KW'}, + {name: 'Kyrgyzstan', code: 'KG'}, + {name: 'Lao People\'s Democratic Republic', code: 'LA'}, + {name: 'Latvia', code: 'LV'}, + {name: 'Lebanon', code: 'LB'}, + {name: 'Lesotho', code: 'LS'}, + {name: 'Liberia', code: 'LR'}, + {name: 'Libyan Arab Jamahiriya', code: 'LY'}, + {name: 'Liechtenstein', code: 'LI'}, + {name: 'Lithuania', code: 'LT'}, + {name: 'Luxembourg', code: 'LU'}, + {name: 'Macao', code: 'MO'}, + {name: 'Macedonia, The Former Yugoslav Republic of', code: 'MK'}, + {name: 'Madagascar', code: 'MG'}, + {name: 'Malawi', code: 'MW'}, + {name: 'Malaysia', code: 'MY'}, + {name: 'Maldives', code: 'MV'}, + {name: 'Mali', code: 'ML'}, + {name: 'Malta', code: 'MT'}, + {name: 'Marshall Islands', code: 'MH'}, + {name: 'Martinique', code: 'MQ'}, + {name: 'Mauritania', code: 'MR'}, + {name: 'Mauritius', code: 'MU'}, + {name: 'Mayotte', code: 'YT'}, + {name: 'Mexico', code: 'MX'}, + {name: 'Micronesia, Federated States of', code: 'FM'}, + {name: 'Moldova, Republic of', code: 'MD'}, + {name: 'Monaco', code: 'MC'}, + {name: 'Mongolia', code: 'MN'}, + {name: 'Montserrat', code: 'MS'}, + {name: 'Morocco', code: 'MA'}, + {name: 'Mozambique', code: 'MZ'}, + {name: 'Myanmar', code: 'MM'}, + {name: 'Namibia', code: 'NA'}, + {name: 'Nauru', code: 'NR'}, + {name: 'Nepal', code: 'NP'}, + {name: 'Netherlands', code: 'NL'}, + {name: 'Netherlands Antilles', code: 'AN'}, + {name: 'New Caledonia', code: 'NC'}, + {name: 'New Zealand', code: 'NZ'}, + {name: 'Nicaragua', code: 'NI'}, + {name: 'Niger', code: 'NE'}, + {name: 'Nigeria', code: 'NG'}, + {name: 'Niue', code: 'NU'}, + {name: 'Norfolk Island', code: 'NF'}, + {name: 'Northern Mariana Islands', code: 'MP'}, + {name: 'Norway', code: 'NO'}, + {name: 'Oman', code: 'OM'}, + {name: 'Pakistan', code: 'PK'}, + {name: 'Palau', code: 'PW'}, + {name: 'Palestinian Territory, Occupied', code: 'PS'}, + {name: 'Panama', code: 'PA'}, + {name: 'Papua New Guinea', code: 'PG'}, + {name: 'Paraguay', code: 'PY'}, + {name: 'Peru', code: 'PE'}, + {name: 'Philippines', code: 'PH'}, + {name: 'Pitcairn', code: 'PN'}, + {name: 'Poland', code: 'PL'}, + {name: 'Portugal', code: 'PT'}, + {name: 'Puerto Rico', code: 'PR'}, + {name: 'Qatar', code: 'QA'}, + {name: 'Reunion', code: 'RE'}, + {name: 'Romania', code: 'RO'}, + {name: 'Russian Federation', code: 'RU'}, + {name: 'Rwanda', code: 'RW'}, + {name: 'Saint Helena', code: 'SH'}, + {name: 'Saint Kitts and Nevis', code: 'KN'}, + {name: 'Saint Lucia', code: 'LC'}, + {name: 'Saint Pierre and Miquelon', code: 'PM'}, + {name: 'Saint Vincent and the Grenadines', code: 'VC'}, + {name: 'Samoa', code: 'WS'}, + {name: 'San Marino', code: 'SM'}, + {name: 'Sao Tome and Principe', code: 'ST'}, + {name: 'Saudi Arabia', code: 'SA'}, + {name: 'Senegal', code: 'SN'}, + {name: 'Serbia and Montenegro', code: 'CS'}, + {name: 'Seychelles', code: 'SC'}, + {name: 'Sierra Leone', code: 'SL'}, + {name: 'Singapore', code: 'SG'}, + {name: 'Slovakia', code: 'SK'}, + {name: 'Slovenia', code: 'SI'}, + {name: 'Solomon Islands', code: 'SB'}, + {name: 'Somalia', code: 'SO'}, + {name: 'South Africa', code: 'ZA'}, + {name: 'South Georgia and the South Sandwich Islands', code: 'GS'}, + {name: 'Spain', code: 'ES'}, + {name: 'Sri Lanka', code: 'LK'}, + {name: 'Sudan', code: 'SD'}, + {name: 'Suriname', code: 'SR'}, + {name: 'Svalbard and Jan Mayen', code: 'SJ'}, + {name: 'Swaziland', code: 'SZ'}, + {name: 'Sweden', code: 'SE'}, + {name: 'Switzerland', code: 'CH'}, + {name: 'Syrian Arab Republic', code: 'SY'}, + {name: 'Taiwan, Province of China', code: 'TW'}, + {name: 'Tajikistan', code: 'TJ'}, + {name: 'Tanzania, United Republic of', code: 'TZ'}, + {name: 'Thailand', code: 'TH'}, + {name: 'Timor-Leste', code: 'TL'}, + {name: 'Togo', code: 'TG'}, + {name: 'Tokelau', code: 'TK'}, + {name: 'Tonga', code: 'TO'}, + {name: 'Trinidad and Tobago', code: 'TT'}, + {name: 'Tunisia', code: 'TN'}, + {name: 'Turkey', code: 'TR'}, + {name: 'Turkmenistan', code: 'TM'}, + {name: 'Turks and Caicos Islands', code: 'TC'}, + {name: 'Tuvalu', code: 'TV'}, + {name: 'Uganda', code: 'UG'}, + {name: 'Ukraine', code: 'UA'}, + {name: 'United Arab Emirates', code: 'AE'}, + {name: 'United Kingdom', code: 'GB'}, + {name: 'United States', code: 'US'}, + {name: 'United States Minor Outlying Islands', code: 'UM'}, + {name: 'Uruguay', code: 'UY'}, + {name: 'Uzbekistan', code: 'UZ'}, + {name: 'Vanuatu', code: 'VU'}, + {name: 'Venezuela', code: 'VE'}, + {name: 'Vietnam', code: 'VN'}, + {name: 'Virgin Islands, British', code: 'VG'}, + {name: 'Virgin Islands, U.S.', code: 'VI'}, + {name: 'Wallis and Futuna', code: 'WF'}, + {name: 'Western Sahara', code: 'EH'}, + {name: 'Yemen', code: 'YE'}, + {name: 'Zambia', code: 'ZM'}, + {name: 'Zimbabwe', code: 'ZW'} + ]; + + var tagging = {isActivated: false, fct: undefined}; + var taggingTokens = {isActivated: false, tokens: undefined}; + + $scope.onKeypress = function (e) { + var $select = this.$select; + // Push a "create new" item into array if there is a search string + if ($select.search.length > 0) { + // always reset the activeIndex to the first item when tagging + $select.activeIndex = $select.taggingLabel === false ? -1 : 0; + + var items = angular.copy($select.items); + var stashArr = angular.copy($select.items); + var newItem; + var item; + var hasTag = false; + var dupeIndex = -1; + var tagItems; + var tagItem; + + newItem = $select.search; + dupeIndex = _findApproxDupe($select.items, newItem); + if(dupeIndex != -1) { + items = items.slice(dupeIndex + 1, items.length - 1); + } + + // Verify that the tag doesn't match the value of a selected item + if (_findCaseInsensitiveDupe($select.search, stashArr.concat($select.selected))) { + $scope.$evalAsync(function () { + $select.activeIndex = 0; + $select.items = items; + }); + return; + } + + // Verify that the tag doesn't match the value of a new tag item + if (_findCaseInsensitiveDupe($select.search, stashArr)) { + $scope.$evalAsync(function () { + $select.activeIndex = 0; + $select.items = items; + }); + return; + } + + // Add the new item + stashArr = []; + stashArr.push(newItem); + stashArr = stashArr.concat(items); + + $scope.$evalAsync(function () { + $select.activeIndex = 0; + $select.items = stashArr; + }); + } + }; + + $scope.onBeforeSelect = function ($item) { + var $select = this.$select; + + // For tagging, use the search if there's no item selected + var item = $item !== undefined ? $item : $select.search; + + return !_findCaseInsensitiveDupe(item, $select.selected); + }; + + + function _findCaseInsensitiveDupe(search, arr) { + if (arr === undefined || search === undefined) { + return false; + } + var hasDupe = arr.filter(function (origItem) { + if (search.toUpperCase() === undefined || origItem === undefined) { + return false; + } + return origItem.toUpperCase() === search.toUpperCase(); + }).length > 0; + + return hasDupe; + } + + function _findApproxDupe(haystack, needle) { + var dupeIndex = -1; + if (angular.isArray(haystack)) { + for (var i = 0; i < haystack.length; i++) { + if(needle.indexOf(haystack[i]) == 0) { + dupeIndex = i; + } + } + } + return dupeIndex; + } + + $scope.onComboKeypress = function (e) { + return; + var $select = this.$select; + // Push a "create new" item into array if there is a search string + if ($select.search.length > 0) { + // always reset the activeIndex to the first item when tagging + $select.activeIndex = $select.taggingLabel === false ? -1 : 0; + + var items = angular.copy($select.items); + var stashArr = angular.copy($select.items); + var newItem; + var item; + var hasTag = false; + var dupeIndex = -1; + var tagItems; + var tagItem; + + newItem = $select.search; + dupeIndex = _findApproxDupe($select.items, newItem); + if(dupeIndex != -1) { + items = items.slice(dupeIndex + 1, items.length - 1); + } + + // Verify that the tag doesn't match the value of a selected item + if (_findCaseInsensitiveDupe($select.search, stashArr.concat($select.selected))) { + $scope.$evalAsync(function () { + $select.activeIndex = 0; + $select.items = items; + }); + return; + } + + // Verify that the tag doesn't match the value of a new tag item + if (_findCaseInsensitiveDupe($select.search, stashArr)) { + $scope.$evalAsync(function () { + $select.activeIndex = 0; + $select.items = items; + }); + return; + } + + // Add the new item + stashArr = []; + stashArr.push(newItem); + stashArr = stashArr.concat(items); + + $scope.$evalAsync(function () { + $select.activeIndex = 0; + $select.items = stashArr; + }); + } + }; + + $scope.onComboBeforeSelect = function ($item) { + var $select = this.$select; + + var newItem = {name: $select.search, email: 'an email', age: 12, country: 'nowhere'}; + +// var stashArr = []; + // stashArr.push(newItem); + // stashArr = stashArr.concat($select.items); + + $scope.$evalAsync(function () { + $select.activeIndex = -2; + // $select.items = stashArr; + }); + + // For tagging, use the search if there's no item selected + return $item !== undefined ? $item : newItem; + }; +}); diff --git a/examples/select2-bootstrap3.html b/examples/select2-bootstrap3.html index 1065e05c2..ddd27f656 100644 --- a/examples/select2-bootstrap3.html +++ b/examples/select2-bootstrap3.html @@ -49,20 +49,35 @@
ui-select inside a Bootstrap form -
- -
+
+ +
+ + + {{$select.selected.name}} + +
+ +
+
+ +
+
- - {{$select.selected.name}} - -
- -
-
+
+ +
+ + + {{$select.selected.name}} + +
+ +
+
+
-
diff --git a/examples/selectize-bootstrap3.html b/examples/selectize-bootstrap3.html index 834407a08..141c811d6 100644 --- a/examples/selectize-bootstrap3.html +++ b/examples/selectize-bootstrap3.html @@ -64,20 +64,35 @@
ui-select inside a Bootstrap form -
- -
+
+ +
+ + + {{$select.selected.name}} + +
+ +
+
+ +
+
- - {{$select.selected.name}} - -
- -
-
+
+ +
+ + + {{$select.selected.name}} + +
+ +
+
+
-
diff --git a/gulpfile.js b/gulpfile.js index 85659f2a8..8d170b740 100644 --- a/gulpfile.js +++ b/gulpfile.js @@ -16,91 +16,228 @@ var gutil = require('gulp-util'); var plumber = require('gulp-plumber');//To prevent pipe breaking caused by errors at 'watch' var config = { - pkg : JSON.parse(fs.readFileSync('./package.json')), - banner: - '/*!\n' + - ' * <%= pkg.name %>\n' + - ' * <%= pkg.homepage %>\n' + - ' * Version: <%= pkg.version %> - <%= timestamp %>\n' + - ' * License: <%= pkg.license %>\n' + - ' */\n\n\n' + pkg: JSON.parse(fs.readFileSync('./package.json')), + banner: '/*!\n' + + ' * <%= pkg.name %>\n' + + ' * <%= pkg.homepage %>\n' + + ' * Version: <%= pkg.version %> - <%= timestamp %>\n' + + ' * License: <%= pkg.license %>\n' + + ' */\n\n\n' }; -gulp.task('default', ['build','test']); +gulp.task('default', ['build', 'test']); gulp.task('build', ['scripts', 'styles']); gulp.task('test', ['build', 'karma']); -gulp.task('watch', ['build','karma-watch'], function() { - gulp.watch(['src/**/*.{js,html}'], ['build']); +gulp.task('watch', ['build', 'karma-watch'], function () { + gulp.watch(['src/**/*.{js,html}'], ['build']); }); -gulp.task('clean', function(cb) { - del(['dist'], cb); +gulp.task('clean', function (cb) { + del(['dist'], cb); }); -gulp.task('scripts', ['clean'], function() { +gulp.task('scripts', ['clean'], function () { - var buildTemplates = function () { - return gulp.src('src/**/*.html') - .pipe(minifyHtml({ - empty: true, - spare: true, - quotes: true + var buildTplBootstrap = function () { + return gulp.src('src/bootstrap/*.html') + .pipe(minifyHtml({ + empty: true, + spare: true, + quotes: true })) - .pipe(templateCache({module: 'ui.select'})); - }; - - var buildLib = function(){ - return gulp.src(['src/common.js','src/*.js']) - .pipe(plumber({ - errorHandler: handleError - })) - .pipe(concat('select_without_templates.js')) - .pipe(header('(function () { \n"use strict";\n')) - .pipe(footer('\n}());')) - .pipe(jshint()) - .pipe(jshint.reporter('jshint-stylish')) - .pipe(jshint.reporter('fail')); - }; - - return es.merge(buildLib(), buildTemplates()) - .pipe(plumber({ - errorHandler: handleError - })) - .pipe(concat('select.js')) - .pipe(header(config.banner, { - timestamp: (new Date()).toISOString(), pkg: config.pkg - })) - .pipe(gulp.dest('dist')) - .pipe(uglify({preserveComments: 'some'})) - .pipe(rename({ext:'.min.js'})) - .pipe(gulp.dest('dist')); + .pipe(templateCache({root: "bootstrap", module: 'ui.select'})); + }; + + var buildTplSelect2 = function () { + return gulp.src('src/select2/*.html') + .pipe(minifyHtml({ + empty: true, + spare: true, + quotes: true + })) + .pipe(templateCache({root: "select2", module: 'ui.select'})); + }; + + var buildTplSelectize = function () { + return gulp.src('src/selectize/*.html') + .pipe(minifyHtml({ + empty: true, + spare: true, + quotes: true + })) + .pipe(templateCache({root: "selectize", module: 'ui.select'})); + }; + + var buildLib = function () { + return gulp.src(['src/*.js']) + .pipe(plumber({ + errorHandler: handleError + })) + .pipe(concat('select_without_templates.js')) + .pipe(header('(function () { \n"use strict";\n')) + .pipe(footer('\n}());')) + .pipe(jshint()) + .pipe(jshint.reporter('jshint-stylish')) + .pipe(jshint.reporter('fail')); + }; + + var buildSort = function () { + return gulp.src(['src/addons/uiSelectSortDirective.js']) + .pipe(plumber({ + errorHandler: handleError + })) + .pipe(concat('select.sort.js')) + .pipe(header('(function () { \n"use strict";\n')) + .pipe(footer('\n}());')) + .pipe(jshint()) + .pipe(jshint.reporter('jshint-stylish')) + .pipe(jshint.reporter('fail') + ); + }; + + var buildTagging = function () { + return gulp.src(['src/addons/uiSelectTaggingDirective.js']) + .pipe(plumber({ + errorHandler: handleError + })) + .pipe(concat('select.tagging.js')) + .pipe(header('(function () { \n"use strict";\n')) + .pipe(footer('\n}());')) + .pipe(jshint()) + .pipe(jshint.reporter('jshint-stylish')) + .pipe(jshint.reporter('fail') + ); + }; + + es.merge(buildTplBootstrap(), buildTplSelect2(), buildTplSelectize()) + .pipe(plumber({ + errorHandler: handleError + })) + .pipe(concat('select.js')) + .pipe(header(config.banner, { + timestamp: (new Date()).toISOString(), pkg: config.pkg + })) + .pipe(rename({ext: '.tpl.js'})) + .pipe(gulp.dest('dist')); + + es.merge(buildLib()) + .pipe(plumber({ + errorHandler: handleError + })) + .pipe(concat('select.js')) + .pipe(header(config.banner, { + timestamp: (new Date()).toISOString(), pkg: config.pkg + })) + .pipe(rename({ext: '.no-tpl.js'})) + .pipe(gulp.dest('dist')) + .pipe(uglify({preserveComments: 'some'})) + .pipe(rename({ext: '.no-tpl.min.js'})) + .pipe(gulp.dest('dist')); + + es.merge(buildLib(), buildTplBootstrap()) + .pipe(plumber({ + errorHandler: handleError + })) + .pipe(concat('select.bootstrap.js')) + .pipe(header(config.banner, { + timestamp: (new Date()).toISOString(), pkg: config.pkg + })) + .pipe(gulp.dest('dist')) + .pipe(uglify({preserveComments: 'some'})) + .pipe(rename({ext: '.bootstrap.min.js'})) + .pipe(gulp.dest('dist')); + + es.merge(buildLib(), buildTplSelect2()) + .pipe(plumber({ + errorHandler: handleError + })) + .pipe(concat('select.select2.js')) + .pipe(header(config.banner, { + timestamp: (new Date()).toISOString(), pkg: config.pkg + })) + .pipe(gulp.dest('dist')) + .pipe(uglify({preserveComments: 'some'})) + .pipe(rename({ext: '.select2.min.js'})) + .pipe(gulp.dest('dist')); + + es.merge(buildLib(), buildTplSelectize()) + .pipe(plumber({ + errorHandler: handleError + })) + .pipe(concat('select.selectize.js')) + .pipe(header(config.banner, { + timestamp: (new Date()).toISOString(), pkg: config.pkg + })) + .pipe(gulp.dest('dist')) + .pipe(uglify({preserveComments: 'some'})) + .pipe(rename({ext: '.selectize.min.js'})) + .pipe(gulp.dest('dist')); + + es.merge(buildSort()) + .pipe(plumber({ + errorHandler: handleError + })) + .pipe(concat('select.sort.js')) + .pipe(header(config.banner, { + timestamp: (new Date()).toISOString(), pkg: config.pkg + })) + .pipe(gulp.dest('dist')) + .pipe(uglify({preserveComments: 'some'})) + .pipe(rename({ext: '.sort.min.js'})) + .pipe(gulp.dest('dist')); + + es.merge(buildTagging()) + .pipe(plumber({ + errorHandler: handleError + })) + .pipe(concat('select.sort.js')) + .pipe(header(config.banner, { + timestamp: (new Date()).toISOString(), pkg: config.pkg + })) + .pipe(gulp.dest('dist')) + .pipe(uglify({preserveComments: 'some'})) + .pipe(rename({ext: '.sort.min.js'})) + .pipe(gulp.dest('dist')); + + return es.merge(buildLib(), buildTagging(), buildSort(), buildTplBootstrap(), buildTplSelect2(), buildTplSelectize()) + .pipe(plumber({ + errorHandler: handleError + })) + .pipe(concat('select.js')) + .pipe(header(config.banner, { + timestamp: (new Date()).toISOString(), pkg: config.pkg + })) + .pipe(gulp.dest('dist')) + .pipe(uglify({preserveComments: 'some'})) + .pipe(rename({ext: '.min.js'})) + .pipe(gulp.dest('dist')); }); -gulp.task('styles', ['clean'], function() { +gulp.task('styles', ['clean'], function () { - return gulp.src('src/common.css') - .pipe(header(config.banner, { - timestamp: (new Date()).toISOString(), pkg: config.pkg - })) - .pipe(rename('select.css')) - .pipe(gulp.dest('dist')) - .pipe(minifyCSS()) - .pipe(rename({ext:'.min.css'})) - .pipe(gulp.dest('dist')); + return gulp.src('src/common.css') + .pipe(header(config.banner, { + timestamp: (new Date()).toISOString(), pkg: config.pkg + })) + .pipe(rename('select.css')) + .pipe(gulp.dest('dist')) + .pipe(minifyCSS()) + .pipe(rename({ext: '.min.css'})) + .pipe(gulp.dest('dist')); }); -gulp.task('karma', ['build'], function() { - karma.start({configFile : __dirname +'/karma.conf.js', singleRun: true}); +gulp.task('karma', ['build'], function () { + karma.start({configFile: __dirname + '/karma.conf.js', singleRun: true}); }); -gulp.task('karma-watch', ['build'], function() { - karma.start({configFile : __dirname +'/karma.conf.js', singleRun: false}); +gulp.task('karma-watch', ['build'], function () { + karma.start({configFile: __dirname + '/karma.conf.js', singleRun: false}); }); var handleError = function (err) { - console.log(err.toString()); - this.emit('end'); + console.log(err.toString()); + this.emit('end'); }; \ No newline at end of file diff --git a/package.json b/package.json index fbc81d5bf..41e7ee781 100644 --- a/package.json +++ b/package.json @@ -33,7 +33,6 @@ "karma-coverage": "~0.2" }, "scripts": { - "postinstall": "bower install", "test": "gulp test" }, "license": "MIT" diff --git a/src/addons/uiSelectSortDirective.js b/src/addons/uiSelectSortDirective.js new file mode 100644 index 000000000..ec13136a6 --- /dev/null +++ b/src/addons/uiSelectSortDirective.js @@ -0,0 +1,141 @@ +// Make multiple matches sortable +angular.module('ui.select.sort', ['ui.select']) + .directive('uiSelectSort', + ['$timeout', 'uiSelectConfig', 'uiSelectMinErr', function ($timeout, uiSelectConfig, uiSelectMinErr) { + return { + require: '^uiSelect', + link: function (scope, element, attrs, $select) { + if (scope[attrs.uiSelectSort] === null) { + throw uiSelectMinErr('sort', "Expected a list to sort"); + } + + var options = angular.extend({ + axis: 'horizontal' + }, + scope.$eval(attrs.uiSelectSortOptions)); + + var axis = options.axis, + draggingClassName = 'dragging', + droppingClassName = 'dropping', + droppingBeforeClassName = 'dropping-before', + droppingAfterClassName = 'dropping-after'; + + scope.$watch(function () { + return $select.sortable; + }, function (n) { + if (n) { + element.attr('draggable', true); + } else { + element.removeAttr('draggable'); + } + }); + + element.on('dragstart', function (e) { + element.addClass(draggingClassName); + + (e.dataTransfer || e.originalEvent.dataTransfer).setData('text/plain', scope.$index); + }); + + element.on('dragend', function () { + element.removeClass(draggingClassName); + }); + + var move = function (from, to) { + /*jshint validthis: true */ + this.splice(to, 0, this.splice(from, 1)[0]); + }; + + var dragOverHandler = function (e) { + e.preventDefault(); + + var offset = axis === 'vertical' ? + e.offsetY || e.layerY || (e.originalEvent ? e.originalEvent.offsetY : 0) : + e.offsetX || e.layerX || (e.originalEvent ? e.originalEvent.offsetX : 0); + + if (offset < (this[axis === 'vertical' ? 'offsetHeight' : 'offsetWidth'] / 2)) { + element.removeClass(droppingAfterClassName); + element.addClass(droppingBeforeClassName); + + } else { + element.removeClass(droppingBeforeClassName); + element.addClass(droppingAfterClassName); + } + }; + + var dropTimeout; + + var dropHandler = function (e) { + e.preventDefault(); + + var droppedItemIndex = parseInt((e.dataTransfer || + e.originalEvent.dataTransfer).getData('text/plain'), 10); + + // prevent event firing multiple times in firefox + $timeout.cancel(dropTimeout); + dropTimeout = $timeout(function () { + _dropHandler(droppedItemIndex); + }, 20); + }; + + var _dropHandler = function (droppedItemIndex) { + var theList = scope.$eval(attrs.uiSelectSort), + itemToMove = theList[droppedItemIndex], + newIndex = null; + + if (element.hasClass(droppingBeforeClassName)) { + if (droppedItemIndex < scope.$index) { + newIndex = scope.$index - 1; + } else { + newIndex = scope.$index; + } + } else { + if (droppedItemIndex < scope.$index) { + newIndex = scope.$index; + } else { + newIndex = scope.$index + 1; + } + } + + move.apply(theList, [droppedItemIndex, newIndex]); + + scope.$apply(function () { + scope.$emit('uiSelectSort:change', { + array: theList, + item: itemToMove, + from: droppedItemIndex, + to: newIndex + }); + }); + + element.removeClass(droppingClassName); + element.removeClass(droppingBeforeClassName); + element.removeClass(droppingAfterClassName); + + element.off('drop', dropHandler); + }; + + element.on('dragenter', function () { + if (element.hasClass(draggingClassName)) { + return; + } + + element.addClass(droppingClassName); + + element.on('dragover', dragOverHandler); + element.on('drop', dropHandler); + }); + + element.on('dragleave', function (e) { + if (e.target != element) { + return; + } + element.removeClass(droppingClassName); + element.removeClass(droppingBeforeClassName); + element.removeClass(droppingAfterClassName); + + element.off('dragover', dragOverHandler); + element.off('drop', dropHandler); + }); + } + }; + }]); diff --git a/src/addons/uiSelectTaggingDirective.js b/src/addons/uiSelectTaggingDirective.js new file mode 100644 index 000000000..33ab84331 --- /dev/null +++ b/src/addons/uiSelectTaggingDirective.js @@ -0,0 +1,190 @@ +angular.module('ui.select.tagging', ['ui.select']) + .directive('uiSelectTagging', + ['$parse', '$timeout', function () { + return { + require: '^uiSelect', + link: function (scope, element, attrs, $select) { + var ctrl = $select; + ctrl.taggingLabel = attrs.taggingLabel !== undefined ? attrs.taggingLabel : false; + ctrl.taggingTokens = + attrs.taggingTokens !== undefined ? attrs.taggingTokens.split('|') : [',', 'ENTER']; + + // If tagging try to split by tokens and add items + ctrl.searchInput.on('paste', function (e) { + var data = e.clipboardData.getData('text/plain'); + if (data && data.length > 0) { + // Split by first token only + var items = data.split(ctrl.taggingTokens[0]); + if (items && items.length > 0) { + angular.forEach(items, function (item) { + if(item === null || item.length === 0) { + return; + } + var newItem = ctrl.beforeTagging(item); + if (newItem) { + ctrl.select(newItem, true); + } + }); + e.preventDefault(); + e.stopPropagation(); + } + } + }); + + // Define the default callback into the controller + ctrl.beforeTagging = function (item) { + return item; + }; + + + // Override the keypress callback + ctrl.afterKeypress = function (e) { + + +// if ( ! ctrl.KEY.isVerticalMovement(e.which) ) { +// scope.$evalAsync( function () { +// $select.activeIndex = $select.taggingLabel === false ? -1 : 0; +// }); +// } + + // Push a "create new" item into array if there is a search string + if ($select.search.length > 0) { + // Return early with these keys + if (e.which === ctrl.KEY.TAB || ctrl.KEY.isControl(e) || ctrl.KEY.isFunctionKey(e) || + e.which === ctrl.KEY.ESC || + ctrl.KEY.isVerticalMovement(e.which)) { + return; + } + + // Check for end of tagging + for (var i = 0; i < ctrl.taggingTokens.length; i++) { + if (ctrl.taggingTokens[i] === ctrl.KEY.MAP[e.keyCode]) { + // Make sure there is a new value to push via tagging + if (ctrl.search.length > 0) { + // Make sure that we don't leave the tagging character on the end of the item label + if ($select.search.substr($select.search.length - 1) == ctrl.KEY.MAP[e.keyCode]) { + $select.search = $select.search.substr(0, $select.search.length - 1); + } + + // Select this item and return + ctrl.select(ctrl.beforeTagging($select.search)); + return; + } + } + } + + $select.activeIndex = $select.taggingLabel === false ? -1 : 0; + // If taggingLabel === false bypasses all of this + if ($select.taggingLabel === false) { + return; + } + + var items = angular.copy($select.items); + var stashArr = angular.copy($select.items); + var newItem; + var item; + var hasTag = false; + var dupeIndex = -1; + var tagItems; + var tagItem; + + + // Find any tagging items already in the $select.items array and store them + tagItems = $select.$filter('filter')(items, function (item) { + return item.match($select.taggingLabel); + }); + if (tagItems.length > 0) { + tagItem = tagItems[0]; + } + item = items[0]; + // Remove existing tag item if found (should only ever be one tag item) + if (item !== undefined && items.length > 0 && tagItem) { + hasTag = true; + items = items.slice(1, items.length); + stashArr = stashArr.slice(1, stashArr.length); + } + newItem = $select.search + ' ' + $select.taggingLabel; + if (_findApproxDupe($select.selected, $select.search) > -1) { + return; + } + // Verify the the tag doesn't match the value of an existing item from + // the searched data set or the items already selected + if (_findCaseInsensitiveDupe(stashArr.concat($select.selected))) { + // if there is a tag from prev iteration, strip it / queue the change + // and return early + if (hasTag) { + items = stashArr; + scope.$evalAsync(function () { + $select.activeIndex = 0; + $select.items = items; + }); + } + return; + } + if (_findCaseInsensitiveDupe(stashArr)) { + // If there is a tag from prev iteration, strip it + if (hasTag) { + $select.items = stashArr.slice(1, stashArr.length); + } + return; + } + + if (hasTag) { + dupeIndex = _findApproxDupe($select.selected, newItem); + } + // dupe found, shave the first item + if (dupeIndex > -1) { + items = items.slice(dupeIndex + 1, items.length - 1); + } else { + items = []; + items.push(newItem); + items = items.concat(stashArr); + } + scope.$evalAsync(function () { + $select.activeIndex = 0; + $select.items = items; + }); + } + }; + + + function _findCaseInsensitiveDupe(arr) { + if (arr === undefined || $select.search === undefined) { + return false; + } + return arr.filter(function (origItem) { + if ($select.search.toUpperCase() === undefined || origItem === undefined) { + return false; + } + return origItem.toUpperCase() === $select.search.toUpperCase(); + }).length > 0; + } + + function _findApproxDupe(haystack, needle) { + var dupeIndex = -1; + if (angular.isArray(haystack)) { + var tempArr = angular.copy(haystack); + for (var i = 0; i < tempArr.length; i++) { + // handle the simple string version of tagging +// if ($select.tagging.fct === undefined) { + // search the array for the match + if (tempArr[i] + ' ' + $select.taggingLabel === needle) { + dupeIndex = i; + } + // handle the object tagging implementation + /* } else { + var mockObj = tempArr[i]; + mockObj.isTag = true; + if (angular.equals(mockObj, needle)) { + dupeIndex = i; + } + }*/ + } + } + return dupeIndex; + } + + + } + }; + }]); diff --git a/src/bootstrap/match.tpl.html b/src/bootstrap/match.tpl.html index a76c9b862..33e607123 100644 --- a/src/bootstrap/match.tpl.html +++ b/src/bootstrap/match.tpl.html @@ -1,11 +1,11 @@ -
+
- {{$select.placeholder}} + {{$select.placeholder}} + ng-show="$select.open">
diff --git a/src/common.css b/src/common.css index e1026d4a1..62473aab2 100644 --- a/src/common.css +++ b/src/common.css @@ -47,6 +47,10 @@ body > .select2-container.open { border-top-right-radius: 0; } .ui-select-container[theme="select2"].direction-up .ui-select-dropdown { + bottom: 100%; + top: auto; + position: absolute; + border-radius: 4px; /* FIXME hardcoded value :-/ */ border-bottom-left-radius: 0; border-bottom-right-radius: 0; @@ -89,6 +93,10 @@ body > .select2-container.open { /* Handle up direction Selectize */ .ui-select-container[theme="selectize"].direction-up .ui-select-dropdown { + bottom: 100%; + top: auto; + position: absolute; + box-shadow: 0 -4px 8px rgba(0, 0, 0, 0.25); margin-top: -2px; /* FIXME hardcoded value :-/ */ @@ -207,6 +215,19 @@ body > .ui-select-bootstrap.open { border-right: 1px solid #428bca; } +.ui-select-bootstrap .ui-select-placeholder { + color: #999; + opacity: 1; +} + +.ui-select-bootstrap .ui-select-placeholder { + color: #999; +} + +.ui-select-bootstrap .ui-select-placeholder { + color: #999; +} + .ui-select-bootstrap .ui-select-choices-row>a { display: block; padding: 3px 20px; @@ -250,5 +271,9 @@ body > .ui-select-bootstrap.open { /* Handle up direction Bootstrap */ .ui-select-container[theme="bootstrap"].direction-up .ui-select-dropdown { + bottom: 100%; + top: auto; + position: absolute; + box-shadow: 0 -4px 8px rgba(0, 0, 0, 0.25); } diff --git a/src/common.js b/src/common.js index efc7a5b9f..1d1ecb188 100644 --- a/src/common.js +++ b/src/common.js @@ -1,53 +1,4 @@ -var KEY = { - TAB: 9, - ENTER: 13, - ESC: 27, - SPACE: 32, - LEFT: 37, - UP: 38, - RIGHT: 39, - DOWN: 40, - SHIFT: 16, - CTRL: 17, - ALT: 18, - PAGE_UP: 33, - PAGE_DOWN: 34, - HOME: 36, - END: 35, - BACKSPACE: 8, - DELETE: 46, - COMMAND: 91, - - MAP: { 91 : "COMMAND", 8 : "BACKSPACE" , 9 : "TAB" , 13 : "ENTER" , 16 : "SHIFT" , 17 : "CTRL" , 18 : "ALT" , 19 : "PAUSEBREAK" , 20 : "CAPSLOCK" , 27 : "ESC" , 32 : "SPACE" , 33 : "PAGE_UP", 34 : "PAGE_DOWN" , 35 : "END" , 36 : "HOME" , 37 : "LEFT" , 38 : "UP" , 39 : "RIGHT" , 40 : "DOWN" , 43 : "+" , 44 : "PRINTSCREEN" , 45 : "INSERT" , 46 : "DELETE", 48 : "0" , 49 : "1" , 50 : "2" , 51 : "3" , 52 : "4" , 53 : "5" , 54 : "6" , 55 : "7" , 56 : "8" , 57 : "9" , 59 : ";", 61 : "=" , 65 : "A" , 66 : "B" , 67 : "C" , 68 : "D" , 69 : "E" , 70 : "F" , 71 : "G" , 72 : "H" , 73 : "I" , 74 : "J" , 75 : "K" , 76 : "L", 77 : "M" , 78 : "N" , 79 : "O" , 80 : "P" , 81 : "Q" , 82 : "R" , 83 : "S" , 84 : "T" , 85 : "U" , 86 : "V" , 87 : "W" , 88 : "X" , 89 : "Y" , 90 : "Z", 96 : "0" , 97 : "1" , 98 : "2" , 99 : "3" , 100 : "4" , 101 : "5" , 102 : "6" , 103 : "7" , 104 : "8" , 105 : "9", 106 : "*" , 107 : "+" , 109 : "-" , 110 : "." , 111 : "/", 112 : "F1" , 113 : "F2" , 114 : "F3" , 115 : "F4" , 116 : "F5" , 117 : "F6" , 118 : "F7" , 119 : "F8" , 120 : "F9" , 121 : "F10" , 122 : "F11" , 123 : "F12", 144 : "NUMLOCK" , 145 : "SCROLLLOCK" , 186 : ";" , 187 : "=" , 188 : "," , 189 : "-" , 190 : "." , 191 : "/" , 192 : "`" , 219 : "[" , 220 : "\\" , 221 : "]" , 222 : "'" - }, - - isControl: function (e) { - var k = e.which; - switch (k) { - case KEY.COMMAND: - case KEY.SHIFT: - case KEY.CTRL: - case KEY.ALT: - return true; - } - - if (e.metaKey) return true; - - return false; - }, - isFunctionKey: function (k) { - k = k.which ? k.which : k; - return k >= 112 && k <= 123; - }, - isVerticalMovement: function (k){ - return ~[KEY.UP, KEY.DOWN].indexOf(k); - }, - isHorizontalMovement: function (k){ - return ~[KEY.LEFT,KEY.RIGHT,KEY.BACKSPACE,KEY.DELETE].indexOf(k); - } - }; - /** * Add querySelectorAll() to jqLite. * @@ -58,101 +9,103 @@ var KEY = { * See feat(jqLite): use querySelectorAll instead of getElementsByTagName in jqLite.find https://github.com/angular/angular.js/pull/3598 */ if (angular.element.prototype.querySelectorAll === undefined) { - angular.element.prototype.querySelectorAll = function(selector) { - return angular.element(this[0].querySelectorAll(selector)); - }; + angular.element.prototype.querySelectorAll = function (selector) { + return angular.element(this[0].querySelectorAll(selector)); + }; } /** * Add closest() to jqLite. */ if (angular.element.prototype.closest === undefined) { - angular.element.prototype.closest = function( selector) { - var elem = this[0]; - var matchesSelector = elem.matches || elem.webkitMatchesSelector || elem.mozMatchesSelector || elem.msMatchesSelector; - - while (elem) { - if (matchesSelector.bind(elem)(selector)) { - return elem; - } else { - elem = elem.parentElement; - } - } - return false; - }; + angular.element.prototype.closest = function (selector) { + var elem = this[0]; + var matchesSelector = elem.matches || elem.webkitMatchesSelector || elem.mozMatchesSelector || + elem.msMatchesSelector; + + while (elem) { + if (matchesSelector.bind(elem)(selector)) { + return elem; + } else { + elem = elem.parentElement; + } + } + return false; + }; } var latestId = 0; var uis = angular.module('ui.select', []) -.constant('uiSelectConfig', { - theme: 'bootstrap', - searchEnabled: true, - sortable: false, - placeholder: '', // Empty by default, like HTML tag + closeOnSelect: true, + generateId: function () { + return latestId++; + }, + appendToBody: false + }) + + // See Rename minErr and make it accessible from outside https://github.com/angular/angular.js/issues/6913 + .service('uiSelectMinErr', function () { + var minErr = angular.$$minErr('ui.select'); + return function () { + var error = minErr.apply(this, arguments); + var message = error.message.replace(new RegExp('\nhttp://errors.angularjs.org/.*'), ''); + return new Error(message); + }; + }) + + // Recreates old behavior of ng-transclude. Used internally. + .directive('uisTranscludeAppend', function () { + return { + link: function (scope, element, attrs, ctrl, transclude) { + transclude(scope, function (clone) { + element.append(clone); + }); + } + }; + }) + + /** + * Highlights text that matches $select.search. + * + * Taken from AngularUI Bootstrap Typeahead + * See https://github.com/angular-ui/bootstrap/blob/0.10.0/src/typeahead/typeahead.js#L340 + */ + .filter('highlight', function () { + function escapeRegexp(queryToEscape) { + return queryToEscape.replace(/([.?*+^$[\]\\(){}|-])/g, '\\$1'); + } - return function(element) { - var boundingClientRect = element[0].getBoundingClientRect(); - return { - width: boundingClientRect.width || element.prop('offsetWidth'), - height: boundingClientRect.height || element.prop('offsetHeight'), - top: boundingClientRect.top + ($window.pageYOffset || $document[0].documentElement.scrollTop), - left: boundingClientRect.left + ($window.pageXOffset || $document[0].documentElement.scrollLeft) - }; - }; -}]); + return function (matchItem, query) { + matchItem = String(matchItem); + return query && matchItem ? matchItem.replace(new RegExp(escapeRegexp(query), 'gi'), + '$&') : matchItem; + }; + }) + + /** + * A read-only equivalent of jQuery's offset function: http://api.jquery.com/offset/ + * + * Taken from AngularUI Bootstrap Position: + * See https://github.com/angular-ui/bootstrap/blob/master/src/position/position.js#L70 + */ + .factory('uisOffset', + ['$document', '$window', + function ($document, $window) { + + return function (element) { + var boundingClientRect = element[0].getBoundingClientRect(); + return { + width: boundingClientRect.width || element.prop('offsetWidth'), + height: boundingClientRect.height || element.prop('offsetHeight'), + top: boundingClientRect.top + ($window.pageYOffset || $document[0].documentElement.scrollTop), + left: boundingClientRect.left + ($window.pageXOffset || $document[0].documentElement.scrollLeft) + }; + }; + }]); diff --git a/src/uiSelectChoicesDirective.js b/src/uiSelectChoicesDirective.js index 69e29b6cc..c6352e29c 100644 --- a/src/uiSelectChoicesDirective.js +++ b/src/uiSelectChoicesDirective.js @@ -1,67 +1,71 @@ uis.directive('uiSelectChoices', - ['uiSelectConfig', 'uisRepeatParser', 'uiSelectMinErr', '$compile', - function(uiSelectConfig, RepeatParser, uiSelectMinErr, $compile) { + ['uiSelectConfig', 'uisRepeatParser', 'uiSelectMinErr', '$compile', + function (uiSelectConfig, RepeatParser, uiSelectMinErr, $compile) { - return { - restrict: 'EA', - require: '^uiSelect', - replace: true, - transclude: true, - templateUrl: function(tElement) { - // Gets theme attribute from parent (ui-select) - var theme = tElement.parent().attr('theme') || uiSelectConfig.theme; - return theme + '/choices.tpl.html'; - }, + return { + restrict: 'EA', + require: '^uiSelect', + replace: true, + transclude: true, + templateUrl: function (tElement) { + // Gets theme attribute from parent (ui-select) + var theme = tElement.parent().attr('theme') || uiSelectConfig.theme; + return theme + '/choices.tpl.html'; + }, - compile: function(tElement, tAttrs) { + compile: function (tElement, tAttrs) { - if (!tAttrs.repeat) throw uiSelectMinErr('repeat', "Expected 'repeat' expression."); + if (!tAttrs.repeat) { + throw uiSelectMinErr('repeat', "Expected 'repeat' expression."); + } - return function link(scope, element, attrs, $select, transcludeFn) { + return function link(scope, element, attrs, $select, transcludeFn) { - // var repeat = RepeatParser.parse(attrs.repeat); - var groupByExp = attrs.groupBy; - var groupFilterExp = attrs.groupFilter; + // var repeat = RepeatParser.parse(attrs.repeat); + var groupByExp = attrs.groupBy; + var groupFilterExp = attrs.groupFilter; - $select.parseRepeatAttr(attrs.repeat, groupByExp, groupFilterExp); //Result ready at $select.parserResult + $select.parseRepeatAttr(attrs.repeat, groupByExp, groupFilterExp); //Result ready at $select.parserResult - $select.disableChoiceExpression = attrs.uiDisableChoice; - $select.onHighlightCallback = attrs.onHighlight; + $select.disableChoiceExpression = attrs.uiDisableChoice; + $select.onHighlightCallback = attrs.onHighlight; - if(groupByExp) { - var groups = element.querySelectorAll('.ui-select-choices-group'); - if (groups.length !== 1) throw uiSelectMinErr('rows', "Expected 1 .ui-select-choices-group but got '{0}'.", groups.length); - groups.attr('ng-repeat', RepeatParser.getGroupNgRepeatExpression()); - } + if (groupByExp) { + var groups = element.querySelectorAll('.ui-select-choices-group'); + if (groups.length !== 1) throw uiSelectMinErr('rows', + "Expected 1 .ui-select-choices-group but got '{0}'.", groups.length); + groups.attr('ng-repeat', RepeatParser.getGroupNgRepeatExpression()); + } - var choices = element.querySelectorAll('.ui-select-choices-row'); - if (choices.length !== 1) { - throw uiSelectMinErr('rows', "Expected 1 .ui-select-choices-row but got '{0}'.", choices.length); - } + var choices = element.querySelectorAll('.ui-select-choices-row'); + if (choices.length !== 1) { + throw uiSelectMinErr('rows', "Expected 1 .ui-select-choices-row but got '{0}'.", + choices.length); + } - choices.attr('ng-repeat', RepeatParser.getNgRepeatExpression($select.parserResult.itemName, '$select.items', $select.parserResult.trackByExp, groupByExp)) - .attr('ng-if', '$select.open') //Prevent unnecessary watches when dropdown is closed - .attr('ng-mouseenter', '$select.setActiveItem('+$select.parserResult.itemName +')') - .attr('ng-click', '$select.select(' + $select.parserResult.itemName + ',false,$event)'); + choices.attr('ng-repeat', + RepeatParser.getNgRepeatExpression($select.parserResult.itemName, '$select.items', + $select.parserResult.trackByExp, groupByExp)) + .attr('ng-if', '$select.open') // Prevent unnecessary watches when dropdown is closed + .attr('ng-mouseenter', '$select.setActiveItem(' + $select.parserResult.itemName + ')') + .attr('ng-click', '$select.select(' + $select.parserResult.itemName + ',false,$event)'); - var rowsInner = element.querySelectorAll('.ui-select-choices-row-inner'); - if (rowsInner.length !== 1) throw uiSelectMinErr('rows', "Expected 1 .ui-select-choices-row-inner but got '{0}'.", rowsInner.length); - rowsInner.attr('uis-transclude-append', ''); //Adding uisTranscludeAppend directive to row element after choices element has ngRepeat + var rowsInner = element.querySelectorAll('.ui-select-choices-row-inner'); + if (rowsInner.length !== 1) { + throw uiSelectMinErr('rows', + "Expected 1 .ui-select-choices-row-inner but got '{0}'.", rowsInner.length); + } + rowsInner.attr('uis-transclude-append', ''); //Adding uisTranscludeAppend directive to row element after choices element has ngRepeat - $compile(element, transcludeFn)(scope); //Passing current transcludeFn to be able to append elements correctly from uisTranscludeAppend + $compile(element, transcludeFn)(scope); //Passing current transcludeFn to be able to append elements correctly from uisTranscludeAppend - scope.$watch('$select.search', function(newValue) { - if(newValue && !$select.open && $select.multiple) $select.activate(false, true); - $select.activeIndex = $select.tagging.isActivated ? -1 : 0; - $select.refresh(attrs.refresh); - }); - - attrs.$observe('refreshDelay', function() { - // $eval() is needed otherwise we get a string instead of a number - var refreshDelay = scope.$eval(attrs.refreshDelay); - $select.refreshDelay = refreshDelay !== undefined ? refreshDelay : uiSelectConfig.refreshDelay; - }); - }; - } - }; -}]); + scope.$watch('$select.search', function (newValue) { + if (newValue && !$select.open && $select.multiple) { + $select.activate(false, true); + } + $select.activeIndex = 0; + }); + }; + } + }; + }]); diff --git a/src/uiSelectController.js b/src/uiSelectController.js index c0a1a94ac..5a42e2459 100644 --- a/src/uiSelectController.js +++ b/src/uiSelectController.js @@ -5,517 +5,780 @@ * put as much logic in the controller (instead of the link functions) as possible so it can be easily tested. */ uis.controller('uiSelectCtrl', - ['$scope', '$element', '$timeout', '$filter', 'uisRepeatParser', 'uiSelectMinErr', 'uiSelectConfig', - function($scope, $element, $timeout, $filter, RepeatParser, uiSelectMinErr, uiSelectConfig) { - - var ctrl = this; - - var EMPTY_SEARCH = ''; - - ctrl.placeholder = uiSelectConfig.placeholder; - ctrl.searchEnabled = uiSelectConfig.searchEnabled; - ctrl.sortable = uiSelectConfig.sortable; - ctrl.refreshDelay = uiSelectConfig.refreshDelay; - - ctrl.removeSelected = false; //If selected item(s) should be removed from dropdown list - ctrl.closeOnSelect = true; //Initialized inside uiSelect directive link function - ctrl.search = EMPTY_SEARCH; - - ctrl.activeIndex = 0; //Dropdown of choices - ctrl.items = []; //All available choices - - ctrl.open = false; - ctrl.focus = false; - ctrl.disabled = false; - ctrl.selected = undefined; - - ctrl.focusser = undefined; //Reference to input element used to handle focus events - ctrl.resetSearchInput = true; - ctrl.multiple = undefined; // Initialized inside uiSelect directive link function - ctrl.disableChoiceExpression = undefined; // Initialized inside uiSelectChoices directive link function - ctrl.tagging = {isActivated: false, fct: undefined}; - ctrl.taggingTokens = {isActivated: false, tokens: undefined}; - ctrl.lockChoiceExpression = undefined; // Initialized inside uiSelectMatch directive link function - ctrl.clickTriggeredSelect = false; - ctrl.$filter = $filter; - - ctrl.searchInput = $element.querySelectorAll('input.ui-select-search'); - if (ctrl.searchInput.length !== 1) { - throw uiSelectMinErr('searchInput', "Expected 1 input.ui-select-search but got '{0}'.", ctrl.searchInput.length); - } - - ctrl.isEmpty = function() { - return angular.isUndefined(ctrl.selected) || ctrl.selected === null || ctrl.selected === ''; - }; - - // Most of the time the user does not want to empty the search input when in typeahead mode - function _resetSearchInput() { - if (ctrl.resetSearchInput || (ctrl.resetSearchInput === undefined && uiSelectConfig.resetSearchInput)) { - ctrl.search = EMPTY_SEARCH; - //reset activeIndex - if (ctrl.selected && ctrl.items.length && !ctrl.multiple) { - ctrl.activeIndex = ctrl.items.indexOf(ctrl.selected); - } - } - } - - function _groupsFilter(groups, groupNames) { - var i, j, result = []; - for(i = 0; i < groupNames.length ;i++){ - for(j = 0; j < groups.length ;j++){ - if(groups[j].name == [groupNames[i]]){ - result.push(groups[j]); - } - } - } - return result; - } - - // When the user clicks on ui-select, displays the dropdown list - ctrl.activate = function(initSearchValue, avoidReset) { - if (!ctrl.disabled && !ctrl.open) { - if(!avoidReset) _resetSearchInput(); - - $scope.$broadcast('uis:activate'); - - ctrl.open = true; - - ctrl.activeIndex = ctrl.activeIndex >= ctrl.items.length ? 0 : ctrl.activeIndex; - - // ensure that the index is set to zero for tagging variants - // that where first option is auto-selected - if ( ctrl.activeIndex === -1 && ctrl.taggingLabel !== false ) { - ctrl.activeIndex = 0; - } - - // Give it time to appear before focus - $timeout(function() { - ctrl.search = initSearchValue || ctrl.search; - ctrl.searchInput[0].focus(); - }); - } - }; - - ctrl.findGroupByName = function(name) { - return ctrl.groups && ctrl.groups.filter(function(group) { - return group.name === name; - })[0]; - }; - - ctrl.parseRepeatAttr = function(repeatAttr, groupByExp, groupFilterExp) { - function updateGroups(items) { - var groupFn = $scope.$eval(groupByExp); - ctrl.groups = []; - angular.forEach(items, function(item) { - var groupName = angular.isFunction(groupFn) ? groupFn(item) : item[groupFn]; - var group = ctrl.findGroupByName(groupName); - if(group) { - group.items.push(item); - } - else { - ctrl.groups.push({name: groupName, items: [item]}); - } - }); - if(groupFilterExp){ - var groupFilterFn = $scope.$eval(groupFilterExp); - if( angular.isFunction(groupFilterFn)){ - ctrl.groups = groupFilterFn(ctrl.groups); - } else if(angular.isArray(groupFilterFn)){ - ctrl.groups = _groupsFilter(ctrl.groups, groupFilterFn); - } - } - ctrl.items = []; - ctrl.groups.forEach(function(group) { - ctrl.items = ctrl.items.concat(group.items); - }); - } - - function setPlainItems(items) { - ctrl.items = items; - } - - ctrl.setItemsFn = groupByExp ? updateGroups : setPlainItems; - - ctrl.parserResult = RepeatParser.parse(repeatAttr); - - ctrl.isGrouped = !!groupByExp; - ctrl.itemProperty = ctrl.parserResult.itemName; - - ctrl.refreshItems = function (data){ - data = data || ctrl.parserResult.source($scope); - var selectedItems = ctrl.selected; - //TODO should implement for single mode removeSelected - if ((angular.isArray(selectedItems) && !selectedItems.length) || !ctrl.removeSelected) { - ctrl.setItemsFn(data); - }else{ - if ( data !== undefined ) { - var filteredItems = data.filter(function(i) {return selectedItems.indexOf(i) < 0;}); - ctrl.setItemsFn(filteredItems); - } - } - }; - - // See https://github.com/angular/angular.js/blob/v1.2.15/src/ng/directive/ngRepeat.js#L259 - $scope.$watchCollection(ctrl.parserResult.source, function(items) { - if (items === undefined || items === null) { - // If the user specifies undefined or null => reset the collection - // Special case: items can be undefined if the user did not initialized the collection on the scope - // i.e $scope.addresses = [] is missing - ctrl.items = []; - } else { - if (!angular.isArray(items)) { - throw uiSelectMinErr('items', "Expected an array but got '{0}'.", items); - } else { - //Remove already selected items (ex: while searching) - //TODO Should add a test - ctrl.refreshItems(items); - ctrl.ngModel.$modelValue = null; //Force scope model value and ngModel value to be out of sync to re-run formatters - } - } - }); - - }; - - var _refreshDelayPromise; - - /** - * Typeahead mode: lets the user refresh the collection using his own function. - * - * See Expose $select.search for external / remote filtering https://github.com/angular-ui/ui-select/pull/31 - */ - ctrl.refresh = function(refreshAttr) { - if (refreshAttr !== undefined) { - - // Debounce - // See https://github.com/angular-ui/bootstrap/blob/0.10.0/src/typeahead/typeahead.js#L155 - // FYI AngularStrap typeahead does not have debouncing: https://github.com/mgcrea/angular-strap/blob/v2.0.0-rc.4/src/typeahead/typeahead.js#L177 - if (_refreshDelayPromise) { - $timeout.cancel(_refreshDelayPromise); - } - _refreshDelayPromise = $timeout(function() { - $scope.$eval(refreshAttr); - }, ctrl.refreshDelay); - } - }; - - ctrl.setActiveItem = function(item) { - ctrl.activeIndex = ctrl.items.indexOf(item); - }; - - ctrl.isActive = function(itemScope) { - if ( !ctrl.open ) { - return false; - } - var itemIndex = ctrl.items.indexOf(itemScope[ctrl.itemProperty]); - var isActive = itemIndex === ctrl.activeIndex; - - if ( !isActive || ( itemIndex < 0 && ctrl.taggingLabel !== false ) ||( itemIndex < 0 && ctrl.taggingLabel === false) ) { - return false; - } - - if (isActive && !angular.isUndefined(ctrl.onHighlightCallback)) { - itemScope.$eval(ctrl.onHighlightCallback); - } - - return isActive; - }; - - ctrl.isDisabled = function(itemScope) { - - if (!ctrl.open) return; - - var itemIndex = ctrl.items.indexOf(itemScope[ctrl.itemProperty]); - var isDisabled = false; - var item; - - if (itemIndex >= 0 && !angular.isUndefined(ctrl.disableChoiceExpression)) { - item = ctrl.items[itemIndex]; - isDisabled = !!(itemScope.$eval(ctrl.disableChoiceExpression)); // force the boolean value - item._uiSelectChoiceDisabled = isDisabled; // store this for later reference - } - - return isDisabled; - }; - - - // When the user selects an item with ENTER or clicks the dropdown - ctrl.select = function(item, skipFocusser, $event) { - if (item === undefined || !item._uiSelectChoiceDisabled) { - - if ( ! ctrl.items && ! ctrl.search ) return; - - if (!item || !item._uiSelectChoiceDisabled) { - if(ctrl.tagging.isActivated) { - // if taggingLabel is disabled, we pull from ctrl.search val - if ( ctrl.taggingLabel === false ) { - if ( ctrl.activeIndex < 0 ) { - item = ctrl.tagging.fct !== undefined ? ctrl.tagging.fct(ctrl.search) : ctrl.search; - if (!item || angular.equals( ctrl.items[0], item ) ) { - return; - } - } else { - // keyboard nav happened first, user selected from dropdown - item = ctrl.items[ctrl.activeIndex]; + ['$scope', '$element', '$timeout', '$filter', '$q', 'uisRepeatParser', 'uiSelectMinErr', 'uiSelectConfig', + function ($scope, $element, $timeout, $filter, $q, RepeatParser, uiSelectMinErr, uiSelectConfig) { + var ctrl = this; + + var EMPTY_SEARCH = ''; + + ctrl.placeholder = uiSelectConfig.placeholder; + ctrl.searchEnabled = uiSelectConfig.searchEnabled; + ctrl.sortable = uiSelectConfig.sortable; + + ctrl.removeSelected = false; // If selected item(s) should be removed from dropdown list + ctrl.closeOnSelect = true; // Initialized inside uiSelect directive link function + ctrl.search = EMPTY_SEARCH; + + ctrl.activeIndex = 0; // Dropdown of choices + ctrl.items = []; // All available choices + + ctrl.open = false; + ctrl.focus = false; + ctrl.disabled = false; + ctrl.selected = undefined; + + ctrl.focusser = undefined; // Reference to input element used to handle focus events + ctrl.resetSearchInput = true; + ctrl.multiple = undefined; // Initialized inside uiSelect directive link function + ctrl.disableChoiceExpression = undefined; // Initialized inside uiSelectChoices directive link function + ctrl.lockChoiceExpression = undefined; // Initialized inside uiSelectMatch directive link function + ctrl.clickTriggeredSelect = false; + ctrl.$filter = $filter; + + ctrl.searchInput = $element.querySelectorAll('input.ui-select-search'); + if (ctrl.searchInput.length !== 1) { + throw uiSelectMinErr('searchInput', "Expected 1 input.ui-select-search but got '{0}'.", + ctrl.searchInput.length); } - } else { - // tagging always operates at index zero, taggingLabel === false pushes - // the ctrl.search value without having it injected - if ( ctrl.activeIndex === 0 ) { - // ctrl.tagging pushes items to ctrl.items, so we only have empty val - // for `item` if it is a detected duplicate - if ( item === undefined ) return; - - // create new item on the fly if we don't already have one; - // use tagging function if we have one - if ( ctrl.tagging.fct !== undefined && typeof item === 'string' ) { - item = ctrl.tagging.fct(ctrl.search); - if (!item) return; - // if item type is 'string', apply the tagging label - } else if ( typeof item === 'string' ) { - // trim the trailing space - item = item.replace(ctrl.taggingLabel,'').trim(); - } + + // TODO: Maybe make these methods in KEY directly in the controller? + ctrl.KEY = { + TAB: 9, + ENTER: 13, + ESC: 27, + SPACE: 32, + LEFT: 37, + UP: 38, + RIGHT: 39, + DOWN: 40, + SHIFT: 16, + CTRL: 17, + ALT: 18, + PAGE_UP: 33, + PAGE_DOWN: 34, + HOME: 36, + END: 35, + BACKSPACE: 8, + DELETE: 46, + COMMAND: 91, + MAP: { + 91: "COMMAND", + 8: "BACKSPACE", + 9: "TAB", + 13: "ENTER", + 16: "SHIFT", + 17: "CTRL", + 18: "ALT", + 19: "PAUSEBREAK", + 20: "CAPSLOCK", + 27: "ESC", + 32: "SPACE", + 33: "PAGE_UP", + 34: "PAGE_DOWN", + 35: "END", + 36: "HOME", + 37: "LEFT", + 38: "UP", + 39: "RIGHT", + 40: "DOWN", + 43: "+", + 44: "PRINTSCREEN", + 45: "INSERT", + 46: "DELETE", + 48: "0", + 49: "1", + 50: "2", + 51: "3", + 52: "4", + 53: "5", + 54: "6", + 55: "7", + 56: "8", + 57: "9", + 59: ";", + 61: "=", + 65: "A", + 66: "B", + 67: "C", + 68: "D", + 69: "E", + 70: "F", + 71: "G", + 72: "H", + 73: "I", + 74: "J", + 75: "K", + 76: "L", + 77: "M", + 78: "N", + 79: "O", + 80: "P", + 81: "Q", + 82: "R", + 83: "S", + 84: "T", + 85: "U", + 86: "V", + 87: "W", + 88: "X", + 89: "Y", + 90: "Z", + 96: "0", + 97: "1", + 98: "2", + 99: "3", + 100: "4", + 101: "5", + 102: "6", + 103: "7", + 104: "8", + 105: "9", + 106: "*", + 107: "+", + 109: "-", + 110: ".", + 111: "/", + 112: "F1", + 113: "F2", + 114: "F3", + 115: "F4", + 116: "F5", + 117: "F6", + 118: "F7", + 119: "F8", + 120: "F9", + 121: "F10", + 122: "F11", + 123: "F12", + 144: "NUMLOCK", + 145: "SCROLLLOCK", + 186: ";", + 187: "=", + 188: ",", + 189: "-", + 190: ".", + 191: "/", + 192: "`", + 219: "[", + 220: "\\", + 221: "]", + 222: "'" + }, + + isControl: function (e) { + var k = e.which; + switch (k) { + case ctrl.KEY.COMMAND: + case ctrl.KEY.SHIFT: + case ctrl.KEY.CTRL: + case ctrl.KEY.ALT: + return true; + } + + if (e.metaKey) { + return true; + } + + return false; + }, + isFunctionKey: function (k) { + k = k.which ? k.which : k; + return k >= 112 && k <= 123; + }, + isVerticalMovement: function (k) { + return ~[ctrl.KEY.UP, ctrl.KEY.DOWN].indexOf(k); + }, + isHorizontalMovement: function (k) { + return ~[ctrl.KEY.LEFT, ctrl.KEY.RIGHT, ctrl.KEY.BACKSPACE, ctrl.KEY.DELETE].indexOf(k); + } + }; + + /** + * Returns true if the selection is empty + * @returns {boolean|*} + */ + ctrl.isEmpty = function () { + return angular.isUndefined(ctrl.selected) || ctrl.selected === null || ctrl.selected === ''; + }; + + // Most of the time the user does not want to empty the search input when in typeahead mode + function _resetSearchInput() { + if (ctrl.resetSearchInput || (ctrl.resetSearchInput === undefined && uiSelectConfig.resetSearchInput)) { + ctrl.search = EMPTY_SEARCH; + // Reset activeIndex + if (ctrl.selected && ctrl.items.length && !ctrl.multiple) { + ctrl.activeIndex = ctrl.items.indexOf(ctrl.selected); + } + } + } + + ctrl.findGroupByName = function (name) { + return ctrl.groups && ctrl.groups.filter(function (group) { + return group.name === name; + })[0]; + }; + + function _groupsFilter(groups, groupNames) { + var i, j, result = []; + for (i = 0; i < groupNames.length; i++) { + for (j = 0; j < groups.length; j++) { + if (groups[j].name == [groupNames[i]]) { + result.push(groups[j]); + } + } + } + return result; + } + + /** + * Activates the control. + * When the user clicks on ui-select, displays the dropdown list + * Also called following keyboard input to the search box + */ + ctrl.activate = function (initSearchValue, avoidReset) { + if (!ctrl.disabled && !ctrl.open) { + var completeCallback = function () { + if (!avoidReset) { + _resetSearchInput(); + } + + $scope.$broadcast('uis:activate'); + + ctrl.open = true; + if (!ctrl.searchEnabled) { + angular.element(ctrl.searchInput[0]).addClass('ui-select-offscreen'); + } + + ctrl.activeIndex = ctrl.activeIndex >= ctrl.items.length ? 0 : ctrl.activeIndex; + + // Give it time to appear before focus + $timeout(function () { + ctrl.search = initSearchValue || ctrl.search; + ctrl.searchInput[0].focus(); + }); + }; + + var result = ctrl.beforeDropdownOpen(); + if (angular.isFunction(result.then)) { + // Promise returned - wait for it to complete before completing the selection + result.then(function (result) { + if (result === true) { + completeCallback(); + } + }); + } else if (result === true) { + completeCallback(); + } + } + else if (ctrl.open && !ctrl.searchEnabled) { + // Close the selection if we don't have search enabled, and we click on the select again + ctrl.close(); + } + }; + + ctrl.parseRepeatAttr = function (repeatAttr, groupByExp, groupFilterExp) { + function updateGroups(items) { + var groupFn = $scope.$eval(groupByExp); + ctrl.groups = []; + angular.forEach(items, function (item) { + var groupName = angular.isFunction(groupFn) ? groupFn(item) : item[groupFn]; + var group = ctrl.findGroupByName(groupName); + if (group) { + group.items.push(item); + } + else { + ctrl.groups.push({name: groupName, items: [item]}); + } + }); + if (groupFilterExp) { + var groupFilterFn = $scope.$eval(groupFilterExp); + if (angular.isFunction(groupFilterFn)) { + ctrl.groups = groupFilterFn(ctrl.groups); + } else if (angular.isArray(groupFilterFn)) { + ctrl.groups = _groupsFilter(ctrl.groups, groupFilterFn); + } + } + ctrl.items = []; + ctrl.groups.forEach(function (group) { + ctrl.items = ctrl.items.concat(group.items); + }); + } + + function setPlainItems(items) { + ctrl.items = items; + } + + // Set the function to use when displaying items - either groups or single + ctrl.setItemsFn = groupByExp ? updateGroups : setPlainItems; + + ctrl.parserResult = RepeatParser.parse(repeatAttr); + + ctrl.isGrouped = !!groupByExp; + ctrl.itemProperty = ctrl.parserResult.itemName; + + ctrl.refreshItems = function (data) { + data = data || ctrl.parserResult.source($scope); + var selectedItems = ctrl.selected; + // TODO should implement for single mode removeSelected + if (ctrl.isEmpty() || (angular.isArray(selectedItems) && !selectedItems.length) || + !ctrl.removeSelected) { + ctrl.setItemsFn(data); + } else { + if (data !== undefined) { + var filteredItems = data.filter(function (i) { + return selectedItems.indexOf(i) < 0; + }); + ctrl.setItemsFn(filteredItems); + } + } + }; + + // See https://github.com/angular/angular.js/blob/v1.2.15/src/ng/directive/ngRepeat.js#L259 + $scope.$watchCollection(ctrl.parserResult.source, function (items) { + if (items === undefined || items === null) { + // If the user specifies undefined or null => reset the collection + // Special case: items can be undefined if the user did not initialized the collection on the scope + // i.e $scope.addresses = [] is missing + ctrl.items = []; + } else { + if (!angular.isArray(items)) { + throw uiSelectMinErr('items', "Expected an array but got '{0}'.", items); + } else { + // Remove already selected items (ex: while searching) + // TODO Should add a test + ctrl.refreshItems(items); + // Force scope model value and ngModel value to be out of sync to re-run formatters + ctrl.ngModel.$modelValue = null; + } + } + }); + }; + + ctrl.setActiveItem = function (item) { + ctrl.activeIndex = ctrl.items.indexOf(item); + }; + + /** + * Checks if the item is active + * @param itemScope the item + * @returns {boolean} true if active + */ + ctrl.isActive = function (itemScope) { + if (!ctrl.open) { + return false; + } + // Get the index of this item - returns -1 if the item isn't in the current list + var itemIndex = ctrl.items.indexOf(itemScope[ctrl.itemProperty]); + + // Is this the active index? + // If the itemIndex is -1, then the item wasn't in the list so let's ensure we're not active + // otherwise we can end up with all items being selected as active! + var isActive = itemIndex === -1 ? false : itemIndex === ctrl.activeIndex; + + // If this is active, and we've defined a callback, do it! + // TODO: Is this needed? If it is, then implement properly. +// if (isActive && !angular.isUndefined(ctrl.onHighlightCallback)) { +// itemScope.$eval(ctrl.onHighlightCallback); +// } + + return isActive; + }; + + /** + * Checks if the item is disabled + * @param itemScope the item + * @return {boolean} true if the item is disabled + */ + ctrl.isDisabled = function (itemScope) { + if (!ctrl.open) { + return false; + } + + var itemIndex = ctrl.items.indexOf(itemScope[ctrl.itemProperty]); + var isDisabled = false; + var item; + + if (itemIndex >= 0 && !angular.isUndefined(ctrl.disableChoiceExpression)) { + item = ctrl.items[itemIndex]; + // Force the boolean value + isDisabled = !!(itemScope.$eval(ctrl.disableChoiceExpression)); + // Store this for later reference + item._uiSelectChoiceDisabled = isDisabled; + } + + return isDisabled; + }; + + /** + * Selects an item. Calls the onBeforeSelect and onSelect callbacks + * onBeforeSelect is called to allow the user to alter or abort the selection + * onSelect is called to notify the user of the selection + * + * Called when the user selects an item with ENTER or clicks the dropdown + */ + ctrl.select = function (item, skipFocusser, $event) { + if (item !== undefined && item._uiSelectChoiceDisabled) { + return; + } + + // If no items in the list, and no search, then return + if (!ctrl.items && !ctrl.search) { + return; + } + + function completeCallback() { + $scope.$broadcast('uis:select', item); + + $timeout(function () { + ctrl.afterSelect(item); + }); + + if (ctrl.closeOnSelect) { + ctrl.close(skipFocusser); + } + if ($event && $event.type === 'click') { + ctrl.clickTriggeredSelect = true; + } + } + + // Call the beforeSelect method + // Allowable responses are -: + // false: Abort the selection + // true: Complete selection + // promise: Wait for response + // object: Add the returned object + var result = ctrl.beforeSelect(item); + if (angular.isFunction(result.then)) { + // Promise returned - wait for it to complete before completing the selection + result.then(function (response) { + if (!response) { + return; + } + if (response === true) { + completeCallback(item); + } else if (response) { + completeCallback(response); + } + }); + } else if (result === true) { + completeCallback(item); + } else if (result) { + completeCallback(result); + } + }; + + /** + * Close the dropdown + */ + ctrl.close = function (skipFocusser) { + if (!ctrl.open) { + return; + } + + function completeCallback() { + if (ctrl.ngModel && ctrl.ngModel.$setTouched) { + ctrl.ngModel.$setTouched(); + } + _resetSearchInput(); + ctrl.open = false; + if (!ctrl.searchEnabled) { + angular.element(ctrl.searchInput[0]).removeClass('ui-select-offscreen'); + } + + $scope.$broadcast('uis:close', skipFocusser); + } + + var result = ctrl.beforeDropdownClose(); + if (angular.isFunction(result.then)) { + // Promise returned - wait for it to complete before completing the selection + result.then(function (result) { + if (result === true) { + completeCallback(); + } + }); + } else if (result === true) { + completeCallback(); + } + }; + + /** + * Set focus on the control + */ + ctrl.setFocus = function () { + if (!ctrl.focus) { + ctrl.focusInput[0].focus(); + } + }; + + /** + * Clears the selection + * @param $event + */ + ctrl.clear = function ($event) { + ctrl.select(undefined); + $event.stopPropagation(); + $timeout(function () { + ctrl.focusser[0].focus(); + }, 0, false); + }; + + /** + * Toggle the dropdown open and closed + */ + ctrl.toggle = function (e) { + if (ctrl.open) { + ctrl.close(); + e.preventDefault(); + e.stopPropagation(); + } else { + ctrl.activate(); + } + }; + + ctrl.isLocked = function (itemScope, itemIndex) { + var isLocked, item = ctrl.selected[itemIndex]; + + if (item && !angular.isUndefined(ctrl.lockChoiceExpression)) { + // Force the boolean value + isLocked = !!(itemScope.$eval(ctrl.lockChoiceExpression)); + // Store this for later reference + item._uiSelectChoiceLocked = isLocked; + } + + return isLocked; + }; + + var sizeWatch = null; + ctrl.sizeSearchInput = function () { + var input = ctrl.searchInput[0], + container = ctrl.searchInput.parent().parent()[0], + calculateContainerWidth = function () { + // Return the container width only if the search input is visible + return container.clientWidth * !!input.offsetParent; + }, + updateIfVisible = function (containerWidth) { + if (containerWidth === 0) { + return false; + } + var inputWidth = containerWidth - input.offsetLeft - ctrl.searchInput.parent()[0].offsetLeft - + 5; + if (inputWidth < 50) { + inputWidth = containerWidth; + } + ctrl.searchInput.css('width', inputWidth + 'px'); + return true; + }; + + ctrl.searchInput.css('width', '10px'); + $timeout(function () { + // Give time to render correctly + if (sizeWatch === null && !updateIfVisible(calculateContainerWidth())) { + sizeWatch = $scope.$watch(calculateContainerWidth, function (containerWidth) { + if (updateIfVisible(containerWidth)) { + sizeWatch(); + sizeWatch = null; + } + }); + } + }); + }; + + function _handleDropDownSelection(key) { + var processed = true; + switch (key) { + case ctrl.KEY.DOWN: + if (!ctrl.open && ctrl.multiple) { + // In case its the search input in 'multiple' mode + ctrl.activate(false, true); + } + else if (ctrl.activeIndex < ctrl.items.length - 1) { + ctrl.activeIndex++; + } + break; + case ctrl.KEY.UP: + if (!ctrl.open && ctrl.multiple) { + ctrl.activate(false, true); + } //In case its the search input in 'multiple' mode + else if (ctrl.activeIndex > 0) { + ctrl.activeIndex--; + } + break; + case ctrl.KEY.TAB: + if (!ctrl.multiple || ctrl.open) { + ctrl.select(ctrl.items[ctrl.activeIndex], true); + } + break; + case ctrl.KEY.ENTER: + if (ctrl.open) { + // Make sure at least one dropdown item is highlighted before adding + if (ctrl.items[ctrl.activeIndex] !== undefined) { + ctrl.select(ctrl.items[ctrl.activeIndex]); + } + } else { + // In case its the search input in 'multiple' mode + ctrl.activate(false, true); + } + break; + case ctrl.KEY.ESC: + ctrl.close(); + break; + default: + processed = false; + } + return processed; } - } - // search ctrl.selected for dupes potentially caused by tagging and return early if found - if ( ctrl.selected && angular.isArray(ctrl.selected) && ctrl.selected.filter( function (selection) { return angular.equals(selection, item); }).length > 0 ) { - ctrl.close(skipFocusser); - return; - } - } - - $scope.$broadcast('uis:select', item); - - var locals = {}; - locals[ctrl.parserResult.itemName] = item; - - $timeout(function(){ - ctrl.onSelectCallback($scope, { - $item: item, - $model: ctrl.parserResult.modelMapper($scope, locals) - }); - }); - - if (ctrl.closeOnSelect) { - ctrl.close(skipFocusser); - } - if ($event && $event.type === 'click') { - ctrl.clickTriggeredSelect = true; - } - } - } - }; - - // Closes the dropdown - ctrl.close = function(skipFocusser) { - if (!ctrl.open) return; - if (ctrl.ngModel && ctrl.ngModel.$setTouched) ctrl.ngModel.$setTouched(); - _resetSearchInput(); - ctrl.open = false; - - $scope.$broadcast('uis:close', skipFocusser); - - }; - - ctrl.setFocus = function(){ - if (!ctrl.focus) ctrl.focusInput[0].focus(); - }; - - ctrl.clear = function($event) { - ctrl.select(undefined); - $event.stopPropagation(); - $timeout(function() { - ctrl.focusser[0].focus(); - }, 0, false); - }; - - // Toggle dropdown - ctrl.toggle = function(e) { - if (ctrl.open) { - ctrl.close(); - e.preventDefault(); - e.stopPropagation(); - } else { - ctrl.activate(); - } - }; - - ctrl.isLocked = function(itemScope, itemIndex) { - var isLocked, item = ctrl.selected[itemIndex]; - - if (item && !angular.isUndefined(ctrl.lockChoiceExpression)) { - isLocked = !!(itemScope.$eval(ctrl.lockChoiceExpression)); // force the boolean value - item._uiSelectChoiceLocked = isLocked; // store this for later reference - } - - return isLocked; - }; - - var sizeWatch = null; - ctrl.sizeSearchInput = function() { - - var input = ctrl.searchInput[0], - container = ctrl.searchInput.parent().parent()[0], - calculateContainerWidth = function() { - // Return the container width only if the search input is visible - return container.clientWidth * !!input.offsetParent; - }, - updateIfVisible = function(containerWidth) { - if (containerWidth === 0) { - return false; - } - var inputWidth = containerWidth - input.offsetLeft - 10; - if (inputWidth < 50) inputWidth = containerWidth; - ctrl.searchInput.css('width', inputWidth+'px'); - return true; - }; - - ctrl.searchInput.css('width', '10px'); - $timeout(function() { //Give tags time to render correctly - if (sizeWatch === null && !updateIfVisible(calculateContainerWidth())) { - sizeWatch = $scope.$watch(calculateContainerWidth, function(containerWidth) { - if (updateIfVisible(containerWidth)) { - sizeWatch(); - sizeWatch = null; - } - }); - } - }); - }; - - function _handleDropDownSelection(key) { - var processed = true; - switch (key) { - case KEY.DOWN: - if (!ctrl.open && ctrl.multiple) ctrl.activate(false, true); //In case its the search input in 'multiple' mode - else if (ctrl.activeIndex < ctrl.items.length - 1) { ctrl.activeIndex++; } - break; - case KEY.UP: - if (!ctrl.open && ctrl.multiple) ctrl.activate(false, true); //In case its the search input in 'multiple' mode - else if (ctrl.activeIndex > 0 || (ctrl.search.length === 0 && ctrl.tagging.isActivated && ctrl.activeIndex > -1)) { ctrl.activeIndex--; } - break; - case KEY.TAB: - if (!ctrl.multiple || ctrl.open) ctrl.select(ctrl.items[ctrl.activeIndex], true); - break; - case KEY.ENTER: - if(ctrl.open && (ctrl.tagging.isActivated || ctrl.activeIndex >= 0)){ - ctrl.select(ctrl.items[ctrl.activeIndex]); // Make sure at least one dropdown item is highlighted before adding if not in tagging mode - } else { - ctrl.activate(false, true); //In case its the search input in 'multiple' mode - } - break; - case KEY.ESC: - ctrl.close(); - break; - default: - processed = false; - } - return processed; - } - - // Bind to keyboard shortcuts - ctrl.searchInput.on('keydown', function(e) { - - var key = e.which; - - // if(~[KEY.ESC,KEY.TAB].indexOf(key)){ - // //TODO: SEGURO? - // ctrl.close(); - // } - - $scope.$apply(function() { - - var tagged = false; - - if (ctrl.items.length > 0 || ctrl.tagging.isActivated) { - _handleDropDownSelection(key); - if ( ctrl.taggingTokens.isActivated ) { - for (var i = 0; i < ctrl.taggingTokens.tokens.length; i++) { - if ( ctrl.taggingTokens.tokens[i] === KEY.MAP[e.keyCode] ) { - // make sure there is a new value to push via tagging - if ( ctrl.search.length > 0 ) { - tagged = true; - } + + // Bind to keyboard shortcuts + ctrl.searchInput.on('keydown', function (e) { + var key = e.which; + + if (~[ctrl.KEY.ESC, ctrl.KEY.TAB].indexOf(key)) { + // TODO: SEGURO? + ctrl.close(); + } + + $scope.$apply(function () { + _handleDropDownSelection(key); + }); + + if (ctrl.KEY.isVerticalMovement(key) && ctrl.items.length > 0) { + _ensureHighlightVisible(); + } + + if (key === ctrl.KEY.ENTER || key === ctrl.KEY.ESC) { + e.preventDefault(); + e.stopPropagation(); + } + }); + + ctrl.searchInput.on('keyup', function (e) { + // return early with these keys + if (e.which === ctrl.KEY.TAB || ctrl.KEY.isControl(e) || ctrl.KEY.isFunctionKey(e) || + e.which === ctrl.KEY.ESC || + ctrl.KEY.isVerticalMovement(e.which)) { + return; + } + + // Let the users process the data + // TODO: Is this needed, or just let the user bind to the event themselves! + ctrl.afterKeypress(e); + }); + + // See https://github.com/ivaynberg/select2/blob/3.4.6/select2.js#L1431 + function _ensureHighlightVisible() { + var container = $element.querySelectorAll('.ui-select-choices-content'); + var choices = container.querySelectorAll('.ui-select-choices-row'); + if (choices.length < 1) { + throw uiSelectMinErr('choices', "Expected multiple .ui-select-choices-row but got '{0}'.", + choices.length); + } + + if (ctrl.activeIndex < 0) { + return; + } + + var highlighted = choices[ctrl.activeIndex]; + var posY = highlighted.offsetTop + highlighted.clientHeight - container[0].scrollTop; + var height = container[0].offsetHeight; + + if (posY > height) { + container[0].scrollTop += posY - height; + } else if (posY < highlighted.clientHeight) { + if (ctrl.isGrouped && ctrl.activeIndex === 0) { + // To make group header visible when going all the way up + container[0].scrollTop = 0; + } + else { + container[0].scrollTop -= highlighted.clientHeight - posY; + } + } } - } - if ( tagged ) { - $timeout(function() { - ctrl.searchInput.triggerHandler('tagged'); - var newItem = ctrl.search.replace(KEY.MAP[e.keyCode],'').trim(); - if ( ctrl.tagging.fct ) { - newItem = ctrl.tagging.fct( newItem ); - } - if (newItem) ctrl.select(newItem, true); + + $scope.$on('$destroy', function () { + ctrl.searchInput.off('keyup keydown blur paste'); }); - } - } - } - - }); - - if(KEY.isVerticalMovement(key) && ctrl.items.length > 0){ - _ensureHighlightVisible(); - } - - if (key === KEY.ENTER || key === KEY.ESC) { - e.preventDefault(); - e.stopPropagation(); - } - - }); - - // If tagging try to split by tokens and add items - ctrl.searchInput.on('paste', function (e) { - var data = e.originalEvent.clipboardData.getData('text/plain'); - if (data && data.length > 0 && ctrl.taggingTokens.isActivated && ctrl.tagging.fct) { - var items = data.split(ctrl.taggingTokens.tokens[0]); // split by first token only - if (items && items.length > 0) { - angular.forEach(items, function (item) { - var newItem = ctrl.tagging.fct(item); - if (newItem) { - ctrl.select(newItem, true); - } - }); - e.preventDefault(); - e.stopPropagation(); - } - } - }); - - ctrl.searchInput.on('tagged', function() { - $timeout(function() { - _resetSearchInput(); - }); - }); - - // See https://github.com/ivaynberg/select2/blob/3.4.6/select2.js#L1431 - function _ensureHighlightVisible() { - var container = $element.querySelectorAll('.ui-select-choices-content'); - var choices = container.querySelectorAll('.ui-select-choices-row'); - if (choices.length < 1) { - throw uiSelectMinErr('choices', "Expected multiple .ui-select-choices-row but got '{0}'.", choices.length); - } - - if (ctrl.activeIndex < 0) { - return; - } - - var highlighted = choices[ctrl.activeIndex]; - var posY = highlighted.offsetTop + highlighted.clientHeight - container[0].scrollTop; - var height = container[0].offsetHeight; - - if (posY > height) { - container[0].scrollTop += posY - height; - } else if (posY < highlighted.clientHeight) { - if (ctrl.isGrouped && ctrl.activeIndex === 0) - container[0].scrollTop = 0; //To make group header visible when going all the way up - else - container[0].scrollTop -= highlighted.clientHeight - posY; - } - } - - $scope.$on('$destroy', function() { - ctrl.searchInput.off('keyup keydown tagged blur paste'); - }); - -}]); + + /** + * Keypress callback. Overridable. + * @param event the keypress event + */ + /* jshint unused:false */ + ctrl.afterKeypress = function (event) { + }; + + /** + * Method called before a selection is made. This can be overridden to allow + * the selection to be aborted, or a modified version of the selected item to be + * returned. + * + * Allowable responses are -: + * false: Abort the selection + * true: Complete selection with the selected object + * object: Complete the selection with the returned object + * promise: Wait for response - response from promise is as above + * + * @param item the item that has been selected + * @returns {*} + */ + ctrl.beforeSelect = function (item) { + return true; + }; + + /** + * Method called after a selection is confirmed. This can be overridden to allow + * the application to be notified of a newly selected item. + * No return is required. + * + * @param item the item that has been selected + */ + ctrl.afterSelect = function (item) { + }; + + /** + * Method called before an item is removed from the selected list. This can be overridden + * to allow the removal to be aborted + * + * Allowable responses are -: + * false: Abort the selection + * true: Complete selection with the selected object + * object: Complete the selection with the returned object + * promise: Wait for response - response from promise is as above + * + * @param item the item that has been selected + * @returns {*} + */ + ctrl.beforeRemove = function (item) { + return true; + }; + + /** + * Method called after a item is removed. This can be overridden to allow + * the application to be notified of a removed item. + * No return is required. + * + * @param item the item that has been removed + */ + ctrl.afterRemove = function (item) { + }; + + /** + * Method called before the dropdown is opened. This can be overridden to allow + * the application to process data before the dropdown is displayed. + * The method may return a promise, or true to allow the dropdown, or false to abort. + * @returns {boolean} + */ + ctrl.beforeDropdownOpen = function () { + return true; + }; + + /** + * Method called before the dropdown is closed. This can be overridden to allow + * the application to prevent the dropdown from closing. + * The method may return a promise, or true to allow the dropdown to close, or false to abort. + * @returns {boolean} + */ + ctrl.beforeDropdownClose = function () { + return true; + }; + + }]); diff --git a/src/uiSelectDirective.js b/src/uiSelectDirective.js index 3d391825c..903794476 100644 --- a/src/uiSelectDirective.js +++ b/src/uiSelectDirective.js @@ -1,299 +1,262 @@ uis.directive('uiSelect', - ['$document', 'uiSelectConfig', 'uiSelectMinErr', 'uisOffset', '$compile', '$parse', '$timeout', - function($document, uiSelectConfig, uiSelectMinErr, uisOffset, $compile, $parse, $timeout) { - - return { - restrict: 'EA', - templateUrl: function(tElement, tAttrs) { - var theme = tAttrs.theme || uiSelectConfig.theme; - return theme + (angular.isDefined(tAttrs.multiple) ? '/select-multiple.tpl.html' : '/select.tpl.html'); - }, - replace: true, - transclude: true, - require: ['uiSelect', '^ngModel'], - scope: true, - - controller: 'uiSelectCtrl', - controllerAs: '$select', - compile: function(tElement, tAttrs) { - - //Multiple or Single depending if multiple attribute presence - if (angular.isDefined(tAttrs.multiple)) - tElement.append("").removeAttr('multiple'); - else - tElement.append(""); - - return function(scope, element, attrs, ctrls, transcludeFn) { - - var $select = ctrls[0]; - var ngModel = ctrls[1]; - - $select.generatedId = uiSelectConfig.generateId(); - $select.baseTitle = attrs.title || 'Select box'; - $select.focusserTitle = $select.baseTitle + ' focus'; - $select.focusserId = 'focusser-' + $select.generatedId; - - $select.closeOnSelect = function() { - if (angular.isDefined(attrs.closeOnSelect)) { - return $parse(attrs.closeOnSelect)(); - } else { - return uiSelectConfig.closeOnSelect; - } - }(); - - $select.onSelectCallback = $parse(attrs.onSelect); - $select.onRemoveCallback = $parse(attrs.onRemove); - - //Limit the number of selections allowed - $select.limit = (angular.isDefined(attrs.limit)) ? parseInt(attrs.limit, 10) : undefined; - - //Set reference to ngModel from uiSelectCtrl - $select.ngModel = ngModel; - - $select.choiceGrouped = function(group){ - return $select.isGrouped && group && group.name; - }; - - if(attrs.tabindex){ - attrs.$observe('tabindex', function(value) { - $select.focusInput.attr("tabindex", value); - element.removeAttr("tabindex"); - }); - } - - scope.$watch('searchEnabled', function() { - var searchEnabled = scope.$eval(attrs.searchEnabled); - $select.searchEnabled = searchEnabled !== undefined ? searchEnabled : uiSelectConfig.searchEnabled; - }); - - scope.$watch('sortable', function() { - var sortable = scope.$eval(attrs.sortable); - $select.sortable = sortable !== undefined ? sortable : uiSelectConfig.sortable; - }); - - attrs.$observe('disabled', function() { - // No need to use $eval() (thanks to ng-disabled) since we already get a boolean instead of a string - $select.disabled = attrs.disabled !== undefined ? attrs.disabled : false; - }); - - attrs.$observe('resetSearchInput', function() { - // $eval() is needed otherwise we get a string instead of a boolean - var resetSearchInput = scope.$eval(attrs.resetSearchInput); - $select.resetSearchInput = resetSearchInput !== undefined ? resetSearchInput : true; - }); - - attrs.$observe('tagging', function() { - if(attrs.tagging !== undefined) - { - // $eval() is needed otherwise we get a string instead of a boolean - var taggingEval = scope.$eval(attrs.tagging); - $select.tagging = {isActivated: true, fct: taggingEval !== true ? taggingEval : undefined}; - } - else - { - $select.tagging = {isActivated: false, fct: undefined}; - } - }); - - attrs.$observe('taggingLabel', function() { - if(attrs.tagging !== undefined ) - { - // check eval for FALSE, in this case, we disable the labels - // associated with tagging - if ( attrs.taggingLabel === 'false' ) { - $select.taggingLabel = false; - } - else - { - $select.taggingLabel = attrs.taggingLabel !== undefined ? attrs.taggingLabel : '(new)'; - } - } - }); - - attrs.$observe('taggingTokens', function() { - if (attrs.tagging !== undefined) { - var tokens = attrs.taggingTokens !== undefined ? attrs.taggingTokens.split('|') : [',','ENTER']; - $select.taggingTokens = {isActivated: true, tokens: tokens }; - } - }); - - //Automatically gets focus when loaded - if (angular.isDefined(attrs.autofocus)){ - $timeout(function(){ - $select.setFocus(); - }); - } - - //Gets focus based on scope event name (e.g. focus-on='SomeEventName') - if (angular.isDefined(attrs.focusOn)){ - scope.$on(attrs.focusOn, function() { - $timeout(function(){ - $select.setFocus(); - }); - }); - } - - function onDocumentClick(e) { - if (!$select.open) return; //Skip it if dropdown is close - - var contains = false; - - if (window.jQuery) { - // Firefox 3.6 does not support element.contains() - // See Node.contains https://developer.mozilla.org/en-US/docs/Web/API/Node.contains - contains = window.jQuery.contains(element[0], e.target); - } else { - contains = element[0].contains(e.target); - } - - if (!contains && !$select.clickTriggeredSelect) { - //Will lose focus only with certain targets - var focusableControls = ['input','button','textarea']; - var targetScope = angular.element(e.target).scope(); //To check if target is other ui-select - var skipFocusser = targetScope && targetScope.$select && targetScope.$select !== $select; //To check if target is other ui-select - if (!skipFocusser) skipFocusser = ~focusableControls.indexOf(e.target.tagName.toLowerCase()); //Check if target is input, button or textarea - $select.close(skipFocusser); - scope.$digest(); - } - $select.clickTriggeredSelect = false; - } - - // See Click everywhere but here event http://stackoverflow.com/questions/12931369 - $document.on('click', onDocumentClick); - - scope.$on('$destroy', function() { - $document.off('click', onDocumentClick); - }); - - // Move transcluded elements to their correct position in main template - transcludeFn(scope, function(clone) { - // See Transclude in AngularJS http://blog.omkarpatil.com/2012/11/transclude-in-angularjs.html - - // One day jqLite will be replaced by jQuery and we will be able to write: - // var transcludedElement = clone.filter('.my-class') - // instead of creating a hackish DOM element: - var transcluded = angular.element('
').append(clone); - - var transcludedMatch = transcluded.querySelectorAll('.ui-select-match'); - transcludedMatch.removeAttr('ui-select-match'); //To avoid loop in case directive as attr - transcludedMatch.removeAttr('data-ui-select-match'); // Properly handle HTML5 data-attributes - if (transcludedMatch.length !== 1) { - throw uiSelectMinErr('transcluded', "Expected 1 .ui-select-match but got '{0}'.", transcludedMatch.length); - } - element.querySelectorAll('.ui-select-match').replaceWith(transcludedMatch); - - var transcludedChoices = transcluded.querySelectorAll('.ui-select-choices'); - transcludedChoices.removeAttr('ui-select-choices'); //To avoid loop in case directive as attr - transcludedChoices.removeAttr('data-ui-select-choices'); // Properly handle HTML5 data-attributes - if (transcludedChoices.length !== 1) { - throw uiSelectMinErr('transcluded', "Expected 1 .ui-select-choices but got '{0}'.", transcludedChoices.length); - } - element.querySelectorAll('.ui-select-choices').replaceWith(transcludedChoices); - }); - - // Support for appending the select field to the body when its open - var appendToBody = scope.$eval(attrs.appendToBody); - if (appendToBody !== undefined ? appendToBody : uiSelectConfig.appendToBody) { - scope.$watch('$select.open', function(isOpen) { - if (isOpen) { - positionDropdown(); - } else { - resetDropdown(); - } - }); - - // Move the dropdown back to its original location when the scope is destroyed. Otherwise - // it might stick around when the user routes away or the select field is otherwise removed - scope.$on('$destroy', function() { - resetDropdown(); - }); - } - - // Hold on to a reference to the .ui-select-container element for appendToBody support - var placeholder = null, - originalWidth = ''; - - function positionDropdown() { - // Remember the absolute position of the element - var offset = uisOffset(element); - - // Clone the element into a placeholder element to take its original place in the DOM - placeholder = angular.element('
'); - placeholder[0].style.width = offset.width + 'px'; - placeholder[0].style.height = offset.height + 'px'; - element.after(placeholder); - - // Remember the original value of the element width inline style, so it can be restored - // when the dropdown is closed - originalWidth = element[0].style.width; - - // Now move the actual dropdown element to the end of the body - $document.find('body').append(element); - - element[0].style.position = 'absolute'; - element[0].style.left = offset.left + 'px'; - element[0].style.top = offset.top + 'px'; - element[0].style.width = offset.width + 'px'; - } - - function resetDropdown() { - if (placeholder === null) { - // The dropdown has not actually been display yet, so there's nothing to reset - return; - } - - // Move the dropdown element back to its original location in the DOM - placeholder.replaceWith(element); - placeholder = null; - - element[0].style.position = ''; - element[0].style.left = ''; - element[0].style.top = ''; - element[0].style.width = originalWidth; - } - - // Hold on to a reference to the .ui-select-dropdown element for direction support. - var dropdown = null, - directionUpClassName = 'direction-up'; - - // Support changing the direction of the dropdown if there isn't enough space to render it. - scope.$watch('$select.open', function(isOpen) { - if (isOpen) { - dropdown = angular.element(element).querySelectorAll('.ui-select-dropdown'); - if (dropdown === null) { - return; - } - - // Hide the dropdown so there is no flicker until $timeout is done executing. - dropdown[0].style.opacity = 0; - - // Delay positioning the dropdown until all choices have been added so its height is correct. - $timeout(function(){ - var offset = uisOffset(element); - var offsetDropdown = uisOffset(dropdown); - - // Determine if the direction of the dropdown needs to be changed. - if (offset.top + offset.height + offsetDropdown.height > $document[0].documentElement.scrollTop + $document[0].documentElement.clientHeight) { - dropdown[0].style.position = 'absolute'; - dropdown[0].style.top = (offsetDropdown.height * -1) + 'px'; - element.addClass(directionUpClassName); - } - - // Display the dropdown once it has been positioned. - dropdown[0].style.opacity = 1; - }); - } else { - if (dropdown === null) { - return; - } - - // Reset the position of the dropdown. - dropdown[0].style.position = ''; - dropdown[0].style.top = ''; - element.removeClass(directionUpClassName); - } - }); - }; - } - }; -}]); + ['$document', '$window', 'uiSelectConfig', 'uiSelectMinErr', 'uisOffset', '$compile', '$parse', '$timeout', + function ($document, $window, uiSelectConfig, uiSelectMinErr, uisOffset, $compile, $parse, $timeout) { + + return { + restrict: 'EA', + templateUrl: function (tElement, tAttrs) { + var theme = tAttrs.theme || uiSelectConfig.theme; + return theme + + (angular.isDefined(tAttrs.multiple) ? '/select-multiple.tpl.html' : '/select.tpl.html'); + }, + replace: true, + transclude: true, + require: ['uiSelect', '^ngModel'], + scope: true, + controller: 'uiSelectCtrl', + controllerAs: '$select', + compile: function (tElement, tAttrs) { + + // Multiple or Single depending if multiple attribute presence + if (angular.isDefined(tAttrs.multiple)) { + tElement.append("").removeAttr('multiple'); + } + else { + tElement.append(""); + } + + return function (scope, element, attrs, ctrls, transcludeFn) { + var $select = ctrls[0]; + var ngModel = ctrls[1]; + + $select.generatedId = uiSelectConfig.generateId(); + $select.baseTitle = attrs.title || 'Select box'; + $select.focusserTitle = $select.baseTitle + ' focus'; + $select.focusserId = 'focusser-' + $select.generatedId; + + $select.closeOnSelect = function () { + if (angular.isDefined(attrs.closeOnSelect)) { + return $parse(attrs.closeOnSelect)(); + } else { + return uiSelectConfig.closeOnSelect; + } + }(); + + // Limit the number of selections allowed + $select.limit = (angular.isDefined(attrs.limit)) ? parseInt(attrs.limit, 10) : undefined; + + // Set reference to ngModel from uiSelectCtrl + $select.ngModel = ngModel; + + $select.choiceGrouped = function (group) { + return $select.isGrouped && group && group.name; + }; + + if (attrs.tabindex) { + attrs.$observe('tabindex', function (value) { + $select.focusInput.attr("tabindex", value); + element.removeAttr("tabindex"); + }); + } + + var searchEnabled = scope.$eval(attrs.searchEnabled); + $select.searchEnabled = + searchEnabled !== undefined ? searchEnabled : uiSelectConfig.searchEnabled; + + var sortable = scope.$eval(attrs.sortable); + $select.sortable = sortable !== undefined ? sortable : uiSelectConfig.sortable; + + attrs.$observe('disabled', function () { + // No need to use $eval() (thanks to ng-disabled) since we already get a boolean instead of a string + $select.disabled = attrs.disabled !== undefined ? attrs.disabled : false; + }); + + + //Automatically gets focus when loaded + if (angular.isDefined(attrs.autofocus)) { + $timeout(function () { + $select.setFocus(); + }); + } + + // Gets focus based on scope event name (e.g. focus-on='SomeEventName') + if (angular.isDefined(attrs.focusOn)) { + scope.$on(attrs.focusOn, function () { + $timeout(function () { + $select.setFocus(); + }); + }); + } + + function onDocumentClick(e) { + //Skip it if dropdown is close + if (!$select.open) { + return; + } + + var contains = false; + + if (window.jQuery) { + // Firefox 3.6 does not support element.contains() + // See Node.contains https://developer.mozilla.org/en-US/docs/Web/API/Node.contains + contains = window.jQuery.contains(element[0], e.target); + } else { + contains = element[0].contains(e.target); + } + + if (!contains && !$select.clickTriggeredSelect) { + // Will lose focus only with certain targets + var focusableControls = ['input', 'button', 'textarea']; + // To check if target is other ui-select + var targetController = angular.element(e.target).controller('uiSelect'); + // To check if target is other ui-select + var skipFocusser = targetController && targetController !== $select; + // Check if target is input, button or textarea + if (!skipFocusser) { + skipFocusser = ~focusableControls.indexOf(e.target.tagName.toLowerCase()); + } + $select.close(skipFocusser); + scope.$digest(); + } + $select.clickTriggeredSelect = false; + } + + // See Click everywhere but here event http://stackoverflow.com/questions/12931369 + $document.on('click', onDocumentClick); + + scope.$on('$destroy', function () { + $document.off('click', onDocumentClick); + }); + + // Move transcluded elements to their correct position in main template + transcludeFn(scope, function (clone) { + // See Transclude in AngularJS http://blog.omkarpatil.com/2012/11/transclude-in-angularjs.html + + // One day jqLite will be replaced by jQuery and we will be able to write: + // var transcludedElement = clone.filter('.my-class') + // instead of creating a hackish DOM element: + var transcluded = angular.element('
').append(clone); + + var transcludedMatch = transcluded.querySelectorAll('.ui-select-match'); + transcludedMatch.removeAttr('ui-select-match'); //To avoid loop in case directive as attr + transcludedMatch.removeAttr('data-ui-select-match'); // Properly handle HTML5 data-attributes + if (transcludedMatch.length !== 1) { + throw uiSelectMinErr('transcluded', "Expected 1 .ui-select-match but got '{0}'.", + transcludedMatch.length); + } + element.querySelectorAll('.ui-select-match').replaceWith(transcludedMatch); + + var transcludedChoices = transcluded.querySelectorAll('.ui-select-choices'); + transcludedChoices.removeAttr('ui-select-choices'); //To avoid loop in case directive as attr + transcludedChoices.removeAttr('data-ui-select-choices'); // Properly handle HTML5 data-attributes + if (transcludedChoices.length !== 1) { + throw uiSelectMinErr('transcluded', "Expected 1 .ui-select-choices but got '{0}'.", + transcludedChoices.length); + } + element.querySelectorAll('.ui-select-choices').replaceWith(transcludedChoices); + }); + + // Support for appending the select field to the body when its open + var appendToBody = scope.$eval(attrs.appendToBody); + if (appendToBody !== undefined ? appendToBody : uiSelectConfig.appendToBody) { + scope.$watch('$select.open', function (isOpen) { + if (isOpen) { + positionDropdown(); + } else { + resetDropdown(); + } + }); + + // Move the dropdown back to its original location when the scope is destroyed. Otherwise + // it might stick around when the user routes away or the select field is otherwise removed + scope.$on('$destroy', function () { + resetDropdown(); + }); + } + + // Hold on to a reference to the .ui-select-container element for appendToBody support + var placeholder = null, + originalWidth = ''; + + function positionDropdown() { + // Remember the absolute position of the element + var offset = uisOffset(element); + + // Clone the element into a placeholder element to take its original place in the DOM + placeholder = angular.element('
'); + placeholder[0].style.width = offset.width + 'px'; + placeholder[0].style.height = offset.height + 'px'; + element.after(placeholder); + + // Remember the original value of the element width inline style, so it can be restored + // when the dropdown is closed + originalWidth = element[0].style.width; + + // Now move the actual dropdown element to the end of the body + $document.find('body').append(element); + + element[0].style.position = 'absolute'; + element[0].style.left = offset.left + 'px'; + element[0].style.top = offset.top + 'px'; + element[0].style.width = offset.width + 'px'; + } + + function resetDropdown() { + if (placeholder === null) { + // The dropdown has not actually been display yet, so there's nothing to reset + return; + } + + // Move the dropdown element back to its original location in the DOM + placeholder.replaceWith(element); + placeholder = null; + + element[0].style.position = ''; + element[0].style.left = ''; + element[0].style.top = ''; + element[0].style.width = originalWidth; + } + + // Hold on to a reference to the .ui-select-dropdown element for direction support. + var dropdown = null, + directionUpClassName = 'direction-up'; + + // Support changing the direction of the dropdown if there isn't enough space to render it. + scope.$watch('$select.open', function (isOpen) { + if (isOpen) { + // Get the dropdown element + dropdown = angular.element(element).querySelectorAll('.ui-select-dropdown'); + if (dropdown === null) { + return; + } + + // Hide the dropdown so there is no flicker until $timeout is done executing. + dropdown[0].style.opacity = 0; + + // Delay positioning the dropdown until all choices have been added so its height is correct. + $timeout(function () { + var offset = uisOffset(element); + var offsetDropdown = uisOffset(dropdown); + + // Determine if the direction of the dropdown needs to be changed. + if (offset.top + offset.height + offsetDropdown.height > + $window.pageYOffset + $document[0].documentElement.clientHeight) { + element.addClass(directionUpClassName); + } + + // Display the dropdown once it has been positioned. + dropdown[0].style.opacity = 1; + }); + } else { + if (dropdown === null) { + return; + } + + // Reset the position of the dropdown. + element.removeClass(directionUpClassName); + } + }); + }; + } + }; + }]); diff --git a/src/uiSelectMatchDirective.js b/src/uiSelectMatchDirective.js index b8102c7ad..9dbfec7d8 100644 --- a/src/uiSelectMatchDirective.js +++ b/src/uiSelectMatchDirective.js @@ -1,32 +1,35 @@ -uis.directive('uiSelectMatch', ['uiSelectConfig', function(uiSelectConfig) { - return { - restrict: 'EA', - require: '^uiSelect', - replace: true, - transclude: true, - templateUrl: function(tElement) { - // Gets theme attribute from parent (ui-select) - var theme = tElement.parent().attr('theme') || uiSelectConfig.theme; - var multi = tElement.parent().attr('multiple'); - return theme + (multi ? '/match-multiple.tpl.html' : '/match.tpl.html'); - }, - link: function(scope, element, attrs, $select) { - $select.lockChoiceExpression = attrs.uiLockChoice; - attrs.$observe('placeholder', function(placeholder) { - $select.placeholder = placeholder !== undefined ? placeholder : uiSelectConfig.placeholder; - }); +uis.directive('uiSelectMatch', ['uiSelectConfig', function (uiSelectConfig) { + return { + restrict: 'EA', + require: '^uiSelect', + replace: true, + transclude: true, + templateUrl: function (tElement) { + // Gets theme attribute from parent (ui-select) + var theme = tElement.parent().attr('theme') || uiSelectConfig.theme; + var multi = tElement.parent().attr('multiple'); + return theme + (multi ? '/match-multiple.tpl.html' : '/match.tpl.html'); + }, + link: function (scope, element, attrs, $select) { + $select.lockChoiceExpression = attrs.uiLockChoice; - function setAllowClear(allow) { - $select.allowClear = (angular.isDefined(allow)) ? (allow === '') ? true : (allow.toLowerCase() === 'true') : false; - } + // TODO: observe required? + attrs.$observe('placeholder', function (placeholder) { + $select.placeholder = placeholder !== undefined ? placeholder : uiSelectConfig.placeholder; + }); - attrs.$observe('allowClear', setAllowClear); - setAllowClear(attrs.allowClear); + function setAllowClear(allow) { + $select.allowClear = + (angular.isDefined(allow)) ? (allow === '') ? true : (allow.toLowerCase() === 'true') : false; + } - if($select.multiple){ - $select.sizeSearchInput(); - } + // TODO: observe required? + attrs.$observe('allowClear', setAllowClear); + setAllowClear(attrs.allowClear); - } - }; + if ($select.multiple) { + $select.sizeSearchInput(); + } + } + }; }]); diff --git a/src/uiSelectMultipleDirective.js b/src/uiSelectMultipleDirective.js index 48a2480f9..3784a5568 100644 --- a/src/uiSelectMultipleDirective.js +++ b/src/uiSelectMultipleDirective.js @@ -1,404 +1,309 @@ -uis.directive('uiSelectMultiple', ['uiSelectMinErr','$timeout', function(uiSelectMinErr, $timeout) { - return { - restrict: 'EA', - require: ['^uiSelect', '^ngModel'], - - controller: ['$scope','$timeout', function($scope, $timeout){ - - var ctrl = this, - $select = $scope.$select, - ngModel; - - //Wait for link fn to inject it - $scope.$evalAsync(function(){ ngModel = $scope.ngModel; }); - - ctrl.activeMatchIndex = -1; - - ctrl.updateModel = function(){ - ngModel.$setViewValue(Date.now()); //Set timestamp as a unique string to force changes - ctrl.refreshComponent(); - }; - - ctrl.refreshComponent = function(){ - //Remove already selected items - //e.g. When user clicks on a selection, the selected array changes and - //the dropdown should remove that item - $select.refreshItems(); - $select.sizeSearchInput(); - }; - - // Remove item from multiple select - ctrl.removeChoice = function(index){ - - var removedChoice = $select.selected[index]; - - // if the choice is locked, can't remove it - if(removedChoice._uiSelectChoiceLocked) return; +uis.directive('uiSelectMultiple', ['uiSelectMinErr', '$timeout', function (uiSelectMinErr, $timeout) { + return { + restrict: 'EA', + require: ['^uiSelect', '^ngModel'], + controller: ['$scope', '$timeout', function ($scope, $timeout) { + var ctrl = this, + $select = $scope.$select, + ngModel; + + //Wait for link fn to inject it + $scope.$evalAsync(function () { + ngModel = $scope.ngModel; + }); - var locals = {}; - locals[$select.parserResult.itemName] = removedChoice; + ctrl.activeMatchIndex = -1; + + ctrl.updateModel = function () { + ngModel.$setViewValue(Date.now()); //Set timestamp as a unique string to force changes + ctrl.refreshComponent(); + }; + + ctrl.refreshComponent = function () { + // Remove already selected items + // e.g. When user clicks on a selection, the selected array changes and + // the dropdown should remove that item + $select.refreshItems(); + $select.sizeSearchInput(); + }; + + /** + * Remove item from multiple select + * Calls onBeforeRemove to allow the user to prevent the removal of the item + * Then calls onRemove to notify the user the item has been removed + */ + ctrl.removeChoice = function (index) { + // Get the removed choice + var removedChoice = $select.selected[index]; + + // If the choice is locked, can't remove it + if (removedChoice._uiSelectChoiceLocked) { + return; + } - $select.selected.splice(index, 1); - ctrl.activeMatchIndex = -1; - $select.sizeSearchInput(); + // Give some time for scope propagation. + function completeCallback() { + $select.selected.splice(index, 1); + ctrl.activeMatchIndex = -1; + $select.sizeSearchInput(); - // Give some time for scope propagation. - $timeout(function(){ - $select.onRemoveCallback($scope, { - $item: removedChoice, - $model: $select.parserResult.modelMapper($scope, locals) - }); - }); + $timeout(function () { + $select.afterRemove(removedChoice); + }); - ctrl.updateModel(); + ctrl.updateModel(); + } - }; + // Call the beforeRemove callback + // Allowable responses are -: + // false: Abort the removal + // true: Complete removal + // promise: Wait for response + var result = $select.beforeRemove(removedChoice); + if (angular.isFunction(result.then)) { + // Promise returned - wait for it to complete before completing the selection + result.then(function (result) { + if (result === true) { + completeCallback(); + } + }); + } else if (result === true) { + completeCallback(); + } + }; - ctrl.getPlaceholder = function(){ - //Refactor single? - if($select.selected.length) return; - return $select.placeholder; - }; + ctrl.getPlaceholder = function () { + // Refactor single? + if ($select.selected && $select.selected.length) { + return; + } + return $select.placeholder; + }; + }], + controllerAs: '$selectMultiple', + + link: function (scope, element, attrs, ctrls) { + var $select = ctrls[0]; + var ngModel = scope.ngModel = ctrls[1]; + var $selectMultiple = scope.$selectMultiple; + + //$select.selected = raw selected objects (ignoring any property binding) + + $select.multiple = true; + $select.removeSelected = true; + + //Input that will handle focus + $select.focusInput = $select.searchInput; + + //From view --> model + ngModel.$parsers.unshift(function () { + var locals = {}, + result, + resultMultiple = []; + for (var j = $select.selected.length - 1; j >= 0; j--) { + locals = {}; + locals[$select.parserResult.itemName] = $select.selected[j]; + result = $select.parserResult.modelMapper(scope, locals); + resultMultiple.unshift(result); + } + return resultMultiple; + }); + // From model --> view + ngModel.$formatters.unshift(function (inputValue) { + var data = $select.parserResult.source(scope, {$select: {search: ''}}), //Overwrite $search + locals = {}, + result; + if (!data) { + return inputValue; + } + var resultMultiple = []; + var checkFnMultiple = function (list, value) { + if (!list || !list.length) { + return; + } + for (var p = list.length - 1; p >= 0; p--) { + locals[$select.parserResult.itemName] = list[p]; + result = $select.parserResult.modelMapper(scope, locals); + if ($select.parserResult.trackByExp) { + var matches = /\.(.+)/.exec($select.parserResult.trackByExp); + if (matches.length > 0 && result[matches[1]] == value[matches[1]]) { + resultMultiple.unshift(list[p]); + return true; + } + } + if (angular.equals(result, value)) { + resultMultiple.unshift(list[p]); + return true; + } + } + return false; + }; + if (!inputValue) return resultMultiple; //If ngModel was undefined + for (var k = inputValue.length - 1; k >= 0; k--) { + //Check model array of currently selected items + if (!checkFnMultiple($select.selected, inputValue[k])) { + //Check model array of all items available + if (!checkFnMultiple(data, inputValue[k])) { + //If not found on previous lists, just add it directly to resultMultiple + resultMultiple.unshift(inputValue[k]); + } + } + } + return resultMultiple; + }); - }], - controllerAs: '$selectMultiple', + //Watch for external model changes + scope.$watchCollection(function () { + return ngModel.$modelValue; + }, function (newValue, oldValue) { + if (oldValue != newValue) { + ngModel.$modelValue = null; //Force scope model value and ngModel value to be out of sync to re-run formatters + $selectMultiple.refreshComponent(); + } + }); - link: function(scope, element, attrs, ctrls) { + ngModel.$render = function () { + // Make sure that model value is array + if (!angular.isArray(ngModel.$viewValue)) { + // Have tolerance for null or undefined values + if (angular.isUndefined(ngModel.$viewValue) || ngModel.$viewValue === null) { + $select.selected = []; + } else { + throw uiSelectMinErr('multiarr', "Expected model value to be array but got '{0}'", + ngModel.$viewValue); + } + } + $select.selected = ngModel.$viewValue; + scope.$evalAsync(); //To force $digest + }; - var $select = ctrls[0]; - var ngModel = scope.ngModel = ctrls[1]; - var $selectMultiple = scope.$selectMultiple; + scope.$on('uis:select', function (event, item) { + if ($select.selected.length >= $select.limit) { + return; + } + $select.selected.push(item); + $selectMultiple.updateModel(); + }); - //$select.selected = raw selected objects (ignoring any property binding) + scope.$on('uis:activate', function () { + $selectMultiple.activeMatchIndex = -1; + }); - $select.multiple = true; - $select.removeSelected = true; + scope.$watch('$select.disabled', function (newValue, oldValue) { + // As the search input field may now become visible, it may be necessary to recompute its size + if (oldValue && !newValue) { + $select.sizeSearchInput(); + } + }); - //Input that will handle focus - $select.focusInput = $select.searchInput; + $select.searchInput.on('keydown', function (e) { + var key = e.which; + scope.$apply(function () { + var processed = false; + if ($select.KEY.isHorizontalMovement(key)) { + processed = _handleMatchSelection(key); + } + if (processed && key != $select.KEY.TAB) { + // TODO Check si el tab selecciona aun correctamente + //Creat test +// e.preventDefault(); + // e.stopPropagation(); + } + }); + }); - //From view --> model - ngModel.$parsers.unshift(function () { - var locals = {}, - result, - resultMultiple = []; - for (var j = $select.selected.length - 1; j >= 0; j--) { - locals = {}; - locals[$select.parserResult.itemName] = $select.selected[j]; - result = $select.parserResult.modelMapper(scope, locals); - resultMultiple.unshift(result); - } - return resultMultiple; - }); - - // From model --> view - ngModel.$formatters.unshift(function (inputValue) { - var data = $select.parserResult.source (scope, { $select : {search:''}}), //Overwrite $search - locals = {}, - result; - if (!data) return inputValue; - var resultMultiple = []; - var checkFnMultiple = function(list, value){ - if (!list || !list.length) return; - for (var p = list.length - 1; p >= 0; p--) { - locals[$select.parserResult.itemName] = list[p]; - result = $select.parserResult.modelMapper(scope, locals); - if($select.parserResult.trackByExp){ - var matches = /\.(.+)/.exec($select.parserResult.trackByExp); - if(matches.length>0 && result[matches[1]] == value[matches[1]]){ - resultMultiple.unshift(list[p]); - return true; + function _getCaretPosition(el) { + if (angular.isNumber(el.selectionStart)) { + return el.selectionStart; + } + // selectionStart is not supported in IE8 and we don't want hacky workarounds so we compromise + else { + return el.value.length; } } - if (angular.equals(result,value)){ - resultMultiple.unshift(list[p]); - return true; - } - } - return false; - }; - if (!inputValue) return resultMultiple; //If ngModel was undefined - for (var k = inputValue.length - 1; k >= 0; k--) { - //Check model array of currently selected items - if (!checkFnMultiple($select.selected, inputValue[k])){ - //Check model array of all items available - if (!checkFnMultiple(data, inputValue[k])){ - //If not found on previous lists, just add it directly to resultMultiple - resultMultiple.unshift(inputValue[k]); - } - } - } - return resultMultiple; - }); - - //Watch for external model changes - scope.$watchCollection(function(){ return ngModel.$modelValue; }, function(newValue, oldValue) { - if (oldValue != newValue){ - ngModel.$modelValue = null; //Force scope model value and ngModel value to be out of sync to re-run formatters - $selectMultiple.refreshComponent(); - } - }); - - ngModel.$render = function() { - // Make sure that model value is array - if(!angular.isArray(ngModel.$viewValue)){ - // Have tolerance for null or undefined values - if(angular.isUndefined(ngModel.$viewValue) || ngModel.$viewValue === null){ - $select.selected = []; - } else { - throw uiSelectMinErr('multiarr', "Expected model value to be array but got '{0}'", ngModel.$viewValue); - } - } - $select.selected = ngModel.$viewValue; - scope.$evalAsync(); //To force $digest - }; - scope.$on('uis:select', function (event, item) { - if($select.selected.length >= $select.limit) { - return; - } - $select.selected.push(item); - $selectMultiple.updateModel(); - }); - - scope.$on('uis:activate', function () { - $selectMultiple.activeMatchIndex = -1; - }); - - scope.$watch('$select.disabled', function(newValue, oldValue) { - // As the search input field may now become visible, it may be necessary to recompute its size - if (oldValue && !newValue) $select.sizeSearchInput(); - }); - - $select.searchInput.on('keydown', function(e) { - var key = e.which; - scope.$apply(function() { - var processed = false; - // var tagged = false; //Checkme - if(KEY.isHorizontalMovement(key)){ - processed = _handleMatchSelection(key); - } - if (processed && key != KEY.TAB) { - //TODO Check si el tab selecciona aun correctamente - //Crear test - e.preventDefault(); - e.stopPropagation(); - } - }); - }); - function _getCaretPosition(el) { - if(angular.isNumber(el.selectionStart)) return el.selectionStart; - // selectionStart is not supported in IE8 and we don't want hacky workarounds so we compromise - else return el.value.length; - } - // Handles selected options in "multiple" mode - function _handleMatchSelection(key){ - var caretPosition = _getCaretPosition($select.searchInput[0]), - length = $select.selected.length, - // none = -1, - first = 0, - last = length-1, - curr = $selectMultiple.activeMatchIndex, - next = $selectMultiple.activeMatchIndex+1, - prev = $selectMultiple.activeMatchIndex-1, - newIndex = curr; - - if(caretPosition > 0 || ($select.search.length && key == KEY.RIGHT)) return false; - - $select.close(); - - function getNewActiveMatchIndex(){ - switch(key){ - case KEY.LEFT: - // Select previous/first item - if(~$selectMultiple.activeMatchIndex) return prev; - // Select last item - else return last; - break; - case KEY.RIGHT: - // Open drop-down - if(!~$selectMultiple.activeMatchIndex || curr === last){ - $select.activate(); - return false; - } - // Select next/last item - else return next; - break; - case KEY.BACKSPACE: - // Remove selected item and select previous/first - if(~$selectMultiple.activeMatchIndex){ - $selectMultiple.removeChoice(curr); - return prev; - } - // Select last item - else return last; - break; - case KEY.DELETE: - // Remove selected item and select next item - if(~$selectMultiple.activeMatchIndex){ - $selectMultiple.removeChoice($selectMultiple.activeMatchIndex); - return curr; - } - else return false; - } - } - - newIndex = getNewActiveMatchIndex(); + // Handles selected options in "multiple" mode + function _handleMatchSelection(key) { + var caretPosition = _getCaretPosition($select.searchInput[0]), + length = $select.selected.length, + first = 0, + last = length - 1, + curr = $selectMultiple.activeMatchIndex, + next = $selectMultiple.activeMatchIndex + 1, + prev = $selectMultiple.activeMatchIndex - 1, + newIndex = curr; + + if (caretPosition > 0 || ($select.search.length && key == $select.KEY.RIGHT)) { + return false; + } - if(!$select.selected.length || newIndex === false) $selectMultiple.activeMatchIndex = -1; - else $selectMultiple.activeMatchIndex = Math.min(last,Math.max(first,newIndex)); + $select.close(); + + function getNewActiveMatchIndex() { + switch (key) { + case $select.KEY.LEFT: + // Select previous/first item + if (~$selectMultiple.activeMatchIndex) { + return prev; + } + // Select last item + else { + return last; + } + break; + case $select.KEY.RIGHT: + // Open drop-down + if (!~$selectMultiple.activeMatchIndex || curr === last) { + $select.activate(); + return false; + } + // Select next/last item + else { + return next; + } + break; + case $select.KEY.BACKSPACE: + // Remove selected item and select previous/first + if (~$selectMultiple.activeMatchIndex) { + $selectMultiple.removeChoice(curr); + return prev; + } + // Select last item + else { + return last; + } + break; + case $select.KEY.DELETE: + // Remove selected item and select next item + if (~$selectMultiple.activeMatchIndex) { + $selectMultiple.removeChoice($selectMultiple.activeMatchIndex); + return curr; + } + else { + return false; + } + } + } - return true; - } + newIndex = getNewActiveMatchIndex(); - $select.searchInput.on('keyup', function(e) { + if (!$select.selected.length || newIndex === false) { + $selectMultiple.activeMatchIndex = -1; + } + else { + $selectMultiple.activeMatchIndex = Math.min(last, Math.max(first, newIndex)); + } - if ( ! KEY.isVerticalMovement(e.which) ) { - scope.$evalAsync( function () { - $select.activeIndex = $select.taggingLabel === false ? -1 : 0; - }); - } - // Push a "create new" item into array if there is a search string - if ( $select.tagging.isActivated && $select.search.length > 0 ) { - - // return early with these keys - if (e.which === KEY.TAB || KEY.isControl(e) || KEY.isFunctionKey(e) || e.which === KEY.ESC || KEY.isVerticalMovement(e.which) ) { - return; - } - // always reset the activeIndex to the first item when tagging - $select.activeIndex = $select.taggingLabel === false ? -1 : 0; - // taggingLabel === false bypasses all of this - if ($select.taggingLabel === false) return; - - var items = angular.copy( $select.items ); - var stashArr = angular.copy( $select.items ); - var newItem; - var item; - var hasTag = false; - var dupeIndex = -1; - var tagItems; - var tagItem; - - // case for object tagging via transform `$select.tagging.fct` function - if ( $select.tagging.fct !== undefined) { - tagItems = $select.$filter('filter')(items,{'isTag': true}); - if ( tagItems.length > 0 ) { - tagItem = tagItems[0]; + return true; } - // remove the first element, if it has the `isTag` prop we generate a new one with each keyup, shaving the previous - if ( items.length > 0 && tagItem ) { - hasTag = true; - items = items.slice(1,items.length); - stashArr = stashArr.slice(1,stashArr.length); - } - newItem = $select.tagging.fct($select.search); - newItem.isTag = true; - // verify the the tag doesn't match the value of an existing item - if ( stashArr.filter( function (origItem) { return angular.equals( origItem, $select.tagging.fct($select.search) ); } ).length > 0 ) { - return; - } - newItem.isTag = true; - // handle newItem string and stripping dupes in tagging string context - } else { - // find any tagging items already in the $select.items array and store them - tagItems = $select.$filter('filter')(items,function (item) { - return item.match($select.taggingLabel); - }); - if ( tagItems.length > 0 ) { - tagItem = tagItems[0]; - } - item = items[0]; - // remove existing tag item if found (should only ever be one tag item) - if ( item !== undefined && items.length > 0 && tagItem ) { - hasTag = true; - items = items.slice(1,items.length); - stashArr = stashArr.slice(1,stashArr.length); - } - newItem = $select.search+' '+$select.taggingLabel; - if ( _findApproxDupe($select.selected, $select.search) > -1 ) { - return; - } - // verify the the tag doesn't match the value of an existing item from - // the searched data set or the items already selected - if ( _findCaseInsensitiveDupe(stashArr.concat($select.selected)) ) { - // if there is a tag from prev iteration, strip it / queue the change - // and return early - if ( hasTag ) { - items = stashArr; - scope.$evalAsync( function () { - $select.activeIndex = 0; - $select.items = items; + + $select.searchInput.on('blur', function () { + $timeout(function () { + $selectMultiple.activeMatchIndex = -1; }); - } - return; - } - if ( _findCaseInsensitiveDupe(stashArr) ) { - // if there is a tag from prev iteration, strip it - if ( hasTag ) { - $select.items = stashArr.slice(1,stashArr.length); - } - return; - } - } - if ( hasTag ) dupeIndex = _findApproxDupe($select.selected, newItem); - // dupe found, shave the first item - if ( dupeIndex > -1 ) { - items = items.slice(dupeIndex+1,items.length-1); - } else { - items = []; - items.push(newItem); - items = items.concat(stashArr); - } - scope.$evalAsync( function () { - $select.activeIndex = 0; - $select.items = items; - }); - } - }); - function _findCaseInsensitiveDupe(arr) { - if ( arr === undefined || $select.search === undefined ) { - return false; - } - var hasDupe = arr.filter( function (origItem) { - if ( $select.search.toUpperCase() === undefined || origItem === undefined ) { - return false; - } - return origItem.toUpperCase() === $select.search.toUpperCase(); - }).length > 0; - - return hasDupe; - } - function _findApproxDupe(haystack, needle) { - var dupeIndex = -1; - if(angular.isArray(haystack)) { - var tempArr = angular.copy(haystack); - for (var i = 0; i model - ngModel.$parsers.unshift(function (inputValue) { - var locals = {}, - result; - locals[$select.parserResult.itemName] = inputValue; - result = $select.parserResult.modelMapper(scope, locals); - return result; - }); - - //From model --> view - ngModel.$formatters.unshift(function (inputValue) { - var data = $select.parserResult.source (scope, { $select : {search:''}}), //Overwrite $search - locals = {}, - result; - if (data){ - var checkFnSingle = function(d){ - locals[$select.parserResult.itemName] = d; - result = $select.parserResult.modelMapper(scope, locals); - return result == inputValue; - }; - //If possible pass same object stored in $select.selected - if ($select.selected && checkFnSingle($select.selected)) { - return $select.selected; - } - for (var i = data.length - 1; i >= 0; i--) { - if (checkFnSingle(data[i])) return data[i]; - } +uis.directive('uiSelectSingle', ['$timeout', '$compile', function ($timeout, $compile) { + return { + restrict: 'EA', + require: ['^uiSelect', '^ngModel'], + link: function (scope, element, attrs, ctrls) { + + var $select = ctrls[0]; + var ngModel = ctrls[1]; + + // From view --> model + ngModel.$parsers.unshift(function (inputValue) { + var locals = {}, + result; + locals[$select.parserResult.itemName] = inputValue; + result = $select.parserResult.modelMapper(scope, locals); + return result; + }); + + // From model --> view + ngModel.$formatters.unshift(function (inputValue) { + var data = $select.parserResult.source(scope, {$select: {search: ''}}), //Overwrite $search + locals = {}, + result; + if (data) { + var checkFnSingle = function (d) { + locals[$select.parserResult.itemName] = d; + result = $select.parserResult.modelMapper(scope, locals); + return result == inputValue; + }; + // If possible pass same object stored in $select.selected + if ($select.selected && checkFnSingle($select.selected)) { + return $select.selected; + } + for (var i = data.length - 1; i >= 0; i--) { + if (checkFnSingle(data[i])) { + return data[i]; + } + } + } + return inputValue; + }); + + // Update viewValue if model change + scope.$watch('$select.selected', function (newValue) { + if (ngModel.$viewValue !== newValue) { + ngModel.$setViewValue(newValue); + } + }); + + ngModel.$render = function () { + $select.selected = ngModel.$viewValue; + }; + + scope.$on('uis:select', function (event, item) { + $select.selected = item; + }); + + scope.$on('uis:close', function (event, skipFocusser) { + $timeout(function () { + $select.focusser.prop('disabled', false); + if (!skipFocusser) $select.focusser[0].focus(); + }, 0, false); + }); + + scope.$on('uis:activate', function () { + // Will reactivate it on .close() + focusser.prop('disabled', true); + }); + + // Idea from: https://github.com/ivaynberg/select2/blob/79b5bf6db918d7560bdd959109b7bcfb47edaf43/select2.js#L1954 + var focusser = angular.element(""); + $compile(focusser)(scope); + $select.focusser = focusser; + + // Input that will handle focus + $select.focusInput = focusser; + + element.parent().append(focusser); + focusser.bind("focus", function () { + scope.$evalAsync(function () { + $select.focus = true; + }); + }); + focusser.bind("blur", function () { + scope.$evalAsync(function () { + $select.focus = false; + }); + }); + + focusser.bind("keydown", function (e) { + if (e.which === $select.KEY.BACKSPACE) { + e.preventDefault(); + e.stopPropagation(); + $select.select(undefined); + scope.$apply(); + return; + } + + if (e.which === $select.KEY.TAB || $select.KEY.isControl(e) || $select.KEY.isFunctionKey(e) || e.which === $select.KEY.ESC) { + return; + } + + if (e.which == $select.KEY.DOWN || e.which == $select.KEY.UP || e.which == $select.KEY.ENTER || e.which == $select.KEY.SPACE) { + e.preventDefault(); + e.stopPropagation(); + $select.activate(); + } + + scope.$digest(); + }); + + focusser.bind("keyup input", function (e) { + if (e.which === $select.KEY.TAB || $select.KEY.isControl(e) || $select.KEY.isFunctionKey(e) || e.which === $select.KEY.ESC || + e.which == $select.KEY.ENTER || e.which === $select.KEY.BACKSPACE) { + return; + } + + // User pressed some regular key, so we pass it to the search input + $select.activate(focusser.val()); + focusser.val(''); + scope.$digest(); + }); } - return inputValue; - }); - - //Update viewValue if model change - scope.$watch('$select.selected', function(newValue) { - if (ngModel.$viewValue !== newValue) { - ngModel.$setViewValue(newValue); - } - }); - - ngModel.$render = function() { - $select.selected = ngModel.$viewValue; - }; - - scope.$on('uis:select', function (event, item) { - $select.selected = item; - }); - - scope.$on('uis:close', function (event, skipFocusser) { - $timeout(function(){ - $select.focusser.prop('disabled', false); - if (!skipFocusser) $select.focusser[0].focus(); - },0,false); - }); - - scope.$on('uis:activate', function () { - focusser.prop('disabled', true); //Will reactivate it on .close() - }); - - //Idea from: https://github.com/ivaynberg/select2/blob/79b5bf6db918d7560bdd959109b7bcfb47edaf43/select2.js#L1954 - var focusser = angular.element(""); - $compile(focusser)(scope); - $select.focusser = focusser; - - //Input that will handle focus - $select.focusInput = focusser; - - element.parent().append(focusser); - focusser.bind("focus", function(){ - scope.$evalAsync(function(){ - $select.focus = true; - }); - }); - focusser.bind("blur", function(){ - scope.$evalAsync(function(){ - $select.focus = false; - }); - }); - focusser.bind("keydown", function(e){ - - if (e.which === KEY.BACKSPACE) { - e.preventDefault(); - e.stopPropagation(); - $select.select(undefined); - scope.$apply(); - return; - } - - if (e.which === KEY.TAB || KEY.isControl(e) || KEY.isFunctionKey(e) || e.which === KEY.ESC) { - return; - } - - if (e.which == KEY.DOWN || e.which == KEY.UP || e.which == KEY.ENTER || e.which == KEY.SPACE){ - e.preventDefault(); - e.stopPropagation(); - $select.activate(); - } - - scope.$digest(); - }); - - focusser.bind("keyup input", function(e){ - - if (e.which === KEY.TAB || KEY.isControl(e) || KEY.isFunctionKey(e) || e.which === KEY.ESC || e.which == KEY.ENTER || e.which === KEY.BACKSPACE) { - return; - } - - $select.activate(focusser.val()); //User pressed some regular key, so we pass it to the search input - focusser.val(''); - scope.$digest(); - - }); - - - } - }; + }; }]); \ No newline at end of file diff --git a/src/uiSelectSortDirective.js b/src/uiSelectSortDirective.js deleted file mode 100644 index b01b21a9f..000000000 --- a/src/uiSelectSortDirective.js +++ /dev/null @@ -1,136 +0,0 @@ -// Make multiple matches sortable -uis.directive('uiSelectSort', ['$timeout', 'uiSelectConfig', 'uiSelectMinErr', function($timeout, uiSelectConfig, uiSelectMinErr) { - return { - require: '^uiSelect', - link: function(scope, element, attrs, $select) { - if (scope[attrs.uiSelectSort] === null) { - throw uiSelectMinErr('sort', "Expected a list to sort"); - } - - var options = angular.extend({ - axis: 'horizontal' - }, - scope.$eval(attrs.uiSelectSortOptions)); - - var axis = options.axis, - draggingClassName = 'dragging', - droppingClassName = 'dropping', - droppingBeforeClassName = 'dropping-before', - droppingAfterClassName = 'dropping-after'; - - scope.$watch(function(){ - return $select.sortable; - }, function(n){ - if (n) { - element.attr('draggable', true); - } else { - element.removeAttr('draggable'); - } - }); - - element.on('dragstart', function(e) { - element.addClass(draggingClassName); - - (e.dataTransfer || e.originalEvent.dataTransfer).setData('text/plain', scope.$index); - }); - - element.on('dragend', function() { - element.removeClass(draggingClassName); - }); - - var move = function(from, to) { - /*jshint validthis: true */ - this.splice(to, 0, this.splice(from, 1)[0]); - }; - - var dragOverHandler = function(e) { - e.preventDefault(); - - var offset = axis === 'vertical' ? e.offsetY || e.layerY || (e.originalEvent ? e.originalEvent.offsetY : 0) : e.offsetX || e.layerX || (e.originalEvent ? e.originalEvent.offsetX : 0); - - if (offset < (this[axis === 'vertical' ? 'offsetHeight' : 'offsetWidth'] / 2)) { - element.removeClass(droppingAfterClassName); - element.addClass(droppingBeforeClassName); - - } else { - element.removeClass(droppingBeforeClassName); - element.addClass(droppingAfterClassName); - } - }; - - var dropTimeout; - - var dropHandler = function(e) { - e.preventDefault(); - - var droppedItemIndex = parseInt((e.dataTransfer || e.originalEvent.dataTransfer).getData('text/plain'), 10); - - // prevent event firing multiple times in firefox - $timeout.cancel(dropTimeout); - dropTimeout = $timeout(function() { - _dropHandler(droppedItemIndex); - }, 20); - }; - - var _dropHandler = function(droppedItemIndex) { - var theList = scope.$eval(attrs.uiSelectSort), - itemToMove = theList[droppedItemIndex], - newIndex = null; - - if (element.hasClass(droppingBeforeClassName)) { - if (droppedItemIndex < scope.$index) { - newIndex = scope.$index - 1; - } else { - newIndex = scope.$index; - } - } else { - if (droppedItemIndex < scope.$index) { - newIndex = scope.$index; - } else { - newIndex = scope.$index + 1; - } - } - - move.apply(theList, [droppedItemIndex, newIndex]); - - scope.$apply(function() { - scope.$emit('uiSelectSort:change', { - array: theList, - item: itemToMove, - from: droppedItemIndex, - to: newIndex - }); - }); - - element.removeClass(droppingClassName); - element.removeClass(droppingBeforeClassName); - element.removeClass(droppingAfterClassName); - - element.off('drop', dropHandler); - }; - - element.on('dragenter', function() { - if (element.hasClass(draggingClassName)) { - return; - } - - element.addClass(droppingClassName); - - element.on('dragover', dragOverHandler); - element.on('drop', dropHandler); - }); - - element.on('dragleave', function(e) { - if (e.target != element) { - return; - } - element.removeClass(droppingClassName); - element.removeClass(droppingBeforeClassName); - element.removeClass(droppingAfterClassName); - - element.off('dragover', dragOverHandler); - element.off('drop', dropHandler); - }); - } - }; -}]); diff --git a/src/uisRepeatParserService.js b/src/uisRepeatParserService.js index 7ed9955f1..63b7fed0e 100644 --- a/src/uisRepeatParserService.js +++ b/src/uisRepeatParserService.js @@ -8,43 +8,44 @@ * https://github.com/angular-ui/ui-select/commit/5dd63ad#commitcomment-5504697 */ -uis.service('uisRepeatParser', ['uiSelectMinErr','$parse', function(uiSelectMinErr, $parse) { - var self = this; - - /** - * Example: - * expression = "address in addresses | filter: {street: $select.search} track by $index" - * itemName = "address", - * source = "addresses | filter: {street: $select.search}", - * trackByExp = "$index", - */ - self.parse = function(expression) { - - var match = expression.match(/^\s*(?:([\s\S]+?)\s+as\s+)?([\S]+?)\s+in\s+([\s\S]+?)(?:\s+track\s+by\s+([\s\S]+?))?\s*$/); - - if (!match) { - throw uiSelectMinErr('iexp', "Expected expression in form of '_item_ in _collection_[ track by _id_]' but got '{0}'.", - expression); - } - - return { - itemName: match[2], // (lhs) Left-hand side, - source: $parse(match[3]), - trackByExp: match[4], - modelMapper: $parse(match[1] || match[2]) - }; +uis.service('uisRepeatParser', ['uiSelectMinErr', '$parse', function (uiSelectMinErr, $parse) { + var self = this; + + /** + * Example: + * expression = "address in addresses | filter: {street: $select.search} track by $index" + * itemName = "address", + * source = "addresses | filter: {street: $select.search}", + * trackByExp = "$index", + */ + self.parse = function (expression) { + + var match = expression.match(/^\s*(?:([\s\S]+?)\s+as\s+)?([\S]+?)\s+in\s+([\s\S]+?)(?:\s+track\s+by\s+([\s\S]+?))?\s*$/); + + if (!match) { + throw uiSelectMinErr('iexp', + "Expected expression in form of '_item_ in _collection_[ track by _id_]' but got '{0}'.", + expression); + } + + return { + itemName: match[2], // (lhs) Left-hand side, + source: $parse(match[3]), + trackByExp: match[4], + modelMapper: $parse(match[1] || match[2]) + }; - }; + }; - self.getGroupNgRepeatExpression = function() { - return '$group in $select.groups'; - }; + self.getGroupNgRepeatExpression = function () { + return '$group in $select.groups'; + }; - self.getNgRepeatExpression = function(itemName, source, trackByExp, grouped) { - var expression = itemName + ' in ' + (grouped ? '$group.items' : source); - if (trackByExp) { - expression += ' track by ' + trackByExp; - } - return expression; - }; + self.getNgRepeatExpression = function (itemName, source, trackByExp, grouped) { + var expression = itemName + ' in ' + (grouped ? '$group.items' : source); + if (trackByExp) { + expression += ' track by ' + trackByExp; + } + return expression; + }; }]); diff --git a/test/select.spec.js b/test/select.spec.js index 80f953c46..8b2541589 100644 --- a/test/select.spec.js +++ b/test/select.spec.js @@ -1,736 +1,710 @@ 'use strict'; -describe('ui-select tests', function() { - var scope, $rootScope, $compile, $timeout, $injector; - - var Key = { - Enter: 13, - Tab: 9, - Up: 38, - Down: 40, - Left: 37, - Right: 39, - Backspace: 8, - Delete: 46, - Escape: 27 - }; - - //create a directive that wraps ui-select - angular.module('wrapperDirective',['ui.select']); - angular.module('wrapperDirective').directive('wrapperUiSelect', function(){ - return { - restrict: 'EA', - template: ' \ +describe('ui-select tests', function () { + var scope, $rootScope, $compile, $timeout, $injector; + + var Key = { + Enter: 13, + Tab: 9, + Up: 38, + Down: 40, + Left: 37, + Right: 39, + Backspace: 8, + Delete: 46, + Escape: 27 + }; + + //create a directive that wraps ui-select + angular.module('wrapperDirective', ['ui.select']); + angular.module('wrapperDirective').directive('wrapperUiSelect', function () { + return { + restrict: 'EA', + template: ' \ {{$select.selected.name}} \ \
\
\
', - require: 'ngModel', - scope: true, + require: 'ngModel', + scope: true, - link: function (scope, element, attrs, ctrl) { + link: function (scope, element, attrs, ctrl) { - } - }; + } + }; - }); + }); - beforeEach(module('ngSanitize', 'ui.select', 'wrapperDirective')); + beforeEach(module('ngSanitize', 'ui.select', 'ui.select.tagging', 'wrapperDirective')); - beforeEach(function() { - module(function($provide) { - $provide.factory('uisOffset', function() { - return function(el) { - return {top: 100, left: 200, width: 300, height: 400}; - }; - }); + beforeEach(function () { + module(function ($provide) { + $provide.factory('uisOffset', function () { + return function (el) { + return {top: 100, left: 200, width: 300, height: 400}; + }; + }); + }); }); - }); - - beforeEach(inject(function(_$rootScope_, _$compile_, _$timeout_, _$injector_) { - $rootScope = _$rootScope_; - scope = $rootScope.$new(); - $compile = _$compile_; - $timeout = _$timeout_; - $injector = _$injector_; - scope.selection = {}; - - scope.getGroupLabel = function(person) { - return person.age % 2 ? 'even' : 'odd'; - }; - scope.filterInvertOrder = function(groups) { - return groups.sort(function(groupA, groupB){ - return groupA.name.toLocaleLowerCase() < groupB.name.toLocaleLowerCase(); - }); - }; + beforeEach(inject(function (_$rootScope_, _$compile_, _$timeout_, _$injector_) { + $rootScope = _$rootScope_; + scope = $rootScope.$new(); + $compile = _$compile_; + $timeout = _$timeout_; + $injector = _$injector_; + scope.selection = {}; + scope.getGroupLabel = function (person) { + return person.age % 2 ? 'even' : 'odd'; + }; - scope.people = [ - { name: 'Adam', email: 'adam@email.com', group: 'Foo', age: 12 }, - { name: 'Amalie', email: 'amalie@email.com', group: 'Foo', age: 12 }, - { name: 'Estefanía', email: 'estefanía@email.com', group: 'Foo', age: 21 }, - { name: 'Adrian', email: 'adrian@email.com', group: 'Foo', age: 21 }, - { name: 'Wladimir', email: 'wladimir@email.com', group: 'Foo', age: 30 }, - { name: 'Samantha', email: 'samantha@email.com', group: 'bar', age: 30 }, - { name: 'Nicole', email: 'nicole@email.com', group: 'bar', age: 43 }, - { name: 'Natasha', email: 'natasha@email.com', group: 'Baz', age: 54 } - ]; - - scope.someObject = {}; - scope.someObject.people = [ - { name: 'Adam', email: 'adam@email.com', group: 'Foo', age: 12 }, - { name: 'Amalie', email: 'amalie@email.com', group: 'Foo', age: 12 }, - { name: 'Estefanía', email: 'estefanía@email.com', group: 'Foo', age: 21 }, - { name: 'Adrian', email: 'adrian@email.com', group: 'Foo', age: 21 }, - { name: 'Wladimir', email: 'wladimir@email.com', group: 'Foo', age: 30 }, - { name: 'Samantha', email: 'samantha@email.com', group: 'bar', age: 30 }, - { name: 'Nicole', email: 'nicole@email.com', group: 'bar', age: 43 }, - { name: 'Natasha', email: 'natasha@email.com', group: 'Baz', age: 54 } - ]; - })); - - - // DSL (domain-specific language) - - function compileTemplate(template) { - var el = $compile(angular.element(template))(scope); - scope.$digest(); - return el; - } - - function createUiSelect(attrs) { - var attrsHtml = '', - matchAttrsHtml = ''; - if (attrs !== undefined) { - if (attrs.disabled !== undefined) { attrsHtml += ' ng-disabled="' + attrs.disabled + '"'; } - if (attrs.required !== undefined) { attrsHtml += ' ng-required="' + attrs.required + '"'; } - if (attrs.theme !== undefined) { attrsHtml += ' theme="' + attrs.theme + '"'; } - if (attrs.tabindex !== undefined) { attrsHtml += ' tabindex="' + attrs.tabindex + '"'; } - if (attrs.tagging !== undefined) { attrsHtml += ' tagging="' + attrs.tagging + '"'; } - if (attrs.taggingTokens !== undefined) { attrsHtml += ' tagging-tokens="' + attrs.taggingTokens + '"'; } - if (attrs.title !== undefined) { attrsHtml += ' title="' + attrs.title + '"'; } - if (attrs.appendToBody !== undefined) { attrsHtml += ' append-to-body="' + attrs.appendToBody + '"'; } - if (attrs.allowClear !== undefined) { matchAttrsHtml += ' allow-clear="' + attrs.allowClear + '"';} + scope.filterInvertOrder = function (groups) { + return groups.sort(function (groupA, groupB) { + return groupA.name.toLocaleLowerCase() < groupB.name.toLocaleLowerCase(); + }); + }; + + + scope.people = [ + {name: 'Adam', email: 'adam@email.com', group: 'Foo', age: 12}, + {name: 'Amalie', email: 'amalie@email.com', group: 'Foo', age: 12}, + {name: 'Estefanía', email: 'estefanía@email.com', group: 'Foo', age: 21}, + {name: 'Adrian', email: 'adrian@email.com', group: 'Foo', age: 21}, + {name: 'Wladimir', email: 'wladimir@email.com', group: 'Foo', age: 30}, + {name: 'Samantha', email: 'samantha@email.com', group: 'bar', age: 30}, + {name: 'Nicole', email: 'nicole@email.com', group: 'bar', age: 43}, + {name: 'Natasha', email: 'natasha@email.com', group: 'Baz', age: 54} + ]; + + scope.someObject = {}; + scope.someObject.people = [ + {name: 'Adam', email: 'adam@email.com', group: 'Foo', age: 12}, + {name: 'Amalie', email: 'amalie@email.com', group: 'Foo', age: 12}, + {name: 'Estefanía', email: 'estefanía@email.com', group: 'Foo', age: 21}, + {name: 'Adrian', email: 'adrian@email.com', group: 'Foo', age: 21}, + {name: 'Wladimir', email: 'wladimir@email.com', group: 'Foo', age: 30}, + {name: 'Samantha', email: 'samantha@email.com', group: 'bar', age: 30}, + {name: 'Nicole', email: 'nicole@email.com', group: 'bar', age: 43}, + {name: 'Natasha', email: 'natasha@email.com', group: 'Baz', age: 54} + ]; + })); + + + // DSL (domain-specific language) + + function compileTemplate(template) { + var el = $compile(angular.element(template))(scope); + scope.$digest(); + return el; } - return compileTemplate( - ' \ + function createUiSelect(attrs) { + var attrsHtml = '', + matchAttrsHtml = ''; + if (attrs !== undefined) { + if (attrs.disabled !== undefined) { + attrsHtml += ' ng-disabled="' + attrs.disabled + '"'; + } + if (attrs.required !== undefined) { + attrsHtml += ' ng-required="' + attrs.required + '"'; + } + if (attrs.theme !== undefined) { + attrsHtml += ' theme="' + attrs.theme + '"'; + } + if (attrs.tabindex !== undefined) { + attrsHtml += ' tabindex="' + attrs.tabindex + '"'; + } + if (attrs.tagging !== undefined) { + attrsHtml += ' ui-select-tagging="' + attrs.tagging + '"'; + } + if (attrs.taggingTokens !== undefined) { + attrsHtml += ' tagging-tokens="' + attrs.taggingTokens + '"'; + } + if (attrs.title !== undefined) { + attrsHtml += ' title="' + attrs.title + '"'; + } + if (attrs.appendToBody !== undefined) { + attrsHtml += ' append-to-body="' + attrs.appendToBody + '"'; + } + if (attrs.allowClear !== undefined) { + matchAttrsHtml += ' allow-clear="' + attrs.allowClear + '"'; + } + } + + return compileTemplate( + ' \ {{$select.selected.name}} \ \
\
\
\
' - ); - } - - function getMatchLabel(el) { - return $(el).find('.ui-select-match > span:first > span[ng-transclude]:not(.ng-hide)').text(); - } - - function clickItem(el, text) { + ); + } - if (!isDropdownOpened(el)){ - openDropdown(el); + function getMatchLabel(el) { + return $(el).find('.ui-select-match > span:first > span[ng-transclude]:not(.ng-hide)').text(); } - $(el).find('.ui-select-choices-row div:contains("' + text + '")').click(); - scope.$digest(); - } - - function clickMatch(el) { - $(el).find('.ui-select-match > span:first').click(); - scope.$digest(); - } - - function isDropdownOpened(el) { - // Does not work with jQuery 2.*, have to use jQuery 1.11.* - // This will be fixed in AngularJS 1.3 - // See issue with unit-testing directive using karma https://github.com/angular/angular.js/issues/4640#issuecomment-35002427 - return el.scope().$select.open && el.hasClass('open'); - } - - function triggerKeydown(element, keyCode) { - var e = jQuery.Event("keydown"); - e.which = keyCode; - e.keyCode = keyCode; - element.trigger(e); - } - function triggerPaste(element, text) { - var e = jQuery.Event("paste"); - e.originalEvent = { - clipboardData : { - getData : function() { - return text; - } + function clickItem(el, text) { + + if (!isDropdownOpened(el)) { + openDropdown(el); } - }; - element.trigger(e); - } - function setSearchText(el, text) { - el.scope().$select.search = text; - scope.$digest(); - $timeout.flush(); - } + $(el).find('.ui-select-choices-row div:contains("' + text + '")').click(); + scope.$digest(); + } - function openDropdown(el) { - var $select = el.scope().$select; - $select.open = true; - scope.$digest(); - } + function clickMatch(el) { + $(el).find('.ui-select-match > span:first').click(); + scope.$digest(); + } - function closeDropdown(el) { - var $select = el.scope().$select; - $select.open = false; - scope.$digest(); - } + function isDropdownOpened(el) { + // Does not work with jQuery 2.*, have to use jQuery 1.11.* + // This will be fixed in AngularJS 1.3 + // See issue with unit-testing directive using karma https://github.com/angular/angular.js/issues/4640#issuecomment-35002427 + return el.scope().$select.open && el.hasClass('open'); + } + function triggerKeydown(element, keyCode) { + var e = jQuery.Event("keydown"); + e.which = keyCode; + e.keyCode = keyCode; + element.trigger(e); + } - // Tests + function triggerPaste(element, text) { + var e = jQuery.Event("paste"); + e.clipboardData = { + getData: function () { + return text; + } - it('should compile child directives', function() { - var el = createUiSelect(); + }; + element.trigger(e); + } - var searchEl = $(el).find('.ui-select-search'); - expect(searchEl.length).toEqual(1); + function setSearchText(el, text) { + el.scope().$select.search = text; + scope.$digest(); + $timeout.flush(); + } - var matchEl = $(el).find('.ui-select-match'); - expect(matchEl.length).toEqual(1); + function openDropdown(el) { + var $select = el.scope().$select; + $select.open = true; + scope.$digest(); + } - var choicesContentEl = $(el).find('.ui-select-choices-content'); - expect(choicesContentEl.length).toEqual(1); + function closeDropdown(el) { + var $select = el.scope().$select; + $select.open = false; + scope.$digest(); + } - var choicesContainerEl = $(el).find('.ui-select-choices'); - expect(choicesContainerEl.length).toEqual(1); - openDropdown(el); - var choicesEls = $(el).find('.ui-select-choices-row'); - expect(choicesEls.length).toEqual(8); - }); + // Tests - it('should correctly render initial state', function() { - scope.selection.selected = scope.people[0]; + it('should compile child directives', function () { + var el = createUiSelect(); - var el = createUiSelect(); + var searchEl = $(el).find('.ui-select-search'); + expect(searchEl.length).toEqual(1); - expect(getMatchLabel(el)).toEqual('Adam'); - }); - - it('should correctly render initial state with track by feature', function() { - var el = compileTemplate( - ' \ - {{$select.selected.name}} \ - \ -
\ -
\ -
\ -
' - ); - scope.selection.selected = { name: 'Samantha', email: 'something different than array source', group: 'bar', age: 30 }; - scope.$digest(); - expect(getMatchLabel(el)).toEqual('Samantha'); - }); + var matchEl = $(el).find('.ui-select-match'); + expect(matchEl.length).toEqual(1); - it('should utilize wrapper directive ng-model', function() { - var el = compileTemplate(''); - scope.selection.selected = { name: 'Samantha', email: 'something different than array source', group: 'bar', age: 30 }; - scope.$digest(); - expect($(el).find('.ui-select-container > .ui-select-match > span:first > span[ng-transclude]:not(.ng-hide)').text()).toEqual('Samantha'); - }); + var choicesContentEl = $(el).find('.ui-select-choices-content'); + expect(choicesContentEl.length).toEqual(1); - it('should display the choices when activated', function() { - var el = createUiSelect(); + var choicesContainerEl = $(el).find('.ui-select-choices'); + expect(choicesContainerEl.length).toEqual(1); - expect(isDropdownOpened(el)).toEqual(false); + openDropdown(el); + var choicesEls = $(el).find('.ui-select-choices-row'); + expect(choicesEls.length).toEqual(8); + }); - clickMatch(el); + it('should correctly render initial state', function () { + scope.selection.selected = scope.people[0]; - expect(isDropdownOpened(el)).toEqual(true); - }); + var el = createUiSelect(); - it('should select an item', function() { - var el = createUiSelect(); + expect(getMatchLabel(el)).toEqual('Adam'); + }); - clickItem(el, 'Samantha'); + it('should correctly render initial state with track by feature', function () { + var el = compileTemplate( + ' \ + {{$select.selected.name}} \ + \ +
\ +
\ +
\ +
' + ); + scope.selection.selected = + {name: 'Samantha', email: 'something different than array source', group: 'bar', age: 30}; + scope.$digest(); + expect(getMatchLabel(el)).toEqual('Samantha'); + }); - expect(getMatchLabel(el)).toEqual('Samantha'); - }); + it('should utilize wrapper directive ng-model', function () { + var el = compileTemplate(''); + scope.selection.selected = + {name: 'Samantha', email: 'something different than array source', group: 'bar', age: 30}; + scope.$digest(); + expect($(el).find('.ui-select-container > .ui-select-match > span:first > span[ng-transclude]:not(.ng-hide)').text()).toEqual('Samantha'); + }); - it('should select an item (controller)', function() { - var el = createUiSelect(); + it('should display the choices when activated', function () { + var el = createUiSelect(); - el.scope().$select.select(scope.people[1]); - scope.$digest(); + expect(isDropdownOpened(el)).toEqual(false); - expect(getMatchLabel(el)).toEqual('Amalie'); - }); + clickMatch(el); - it('should not select a non existing item', function() { - var el = createUiSelect(); + expect(isDropdownOpened(el)).toEqual(true); + }); - clickItem(el, "I don't exist"); + it('should select an item', function () { + var el = createUiSelect(); - expect(getMatchLabel(el)).toEqual(''); - }); + clickItem(el, 'Samantha'); - it('should close the choices when an item is selected', function() { - var el = createUiSelect(); + expect(getMatchLabel(el)).toEqual('Samantha'); + }); - clickMatch(el); + it('should select an item (controller)', function () { + var el = createUiSelect(); - expect(isDropdownOpened(el)).toEqual(true); + el.scope().$select.select(scope.people[1]); + scope.$digest(); - clickItem(el, 'Samantha'); + expect(getMatchLabel(el)).toEqual('Amalie'); + }); - expect(isDropdownOpened(el)).toEqual(false); - }); + it('should not select a non existing item', function () { + var el = createUiSelect(); + clickItem(el, "I don't exist"); - it('should open/close dropdown when clicking caret icon', function() { + expect(getMatchLabel(el)).toEqual(''); + }); - var el = createUiSelect({theme : 'select2'}); - var searchInput = el.find('.ui-select-search'); - var $select = el.scope().$select; + it('should close the choices when an item is selected', function () { + var el = createUiSelect(); - expect($select.open).toEqual(false); + clickMatch(el); - el.find(".ui-select-toggle").click(); - expect($select.open).toEqual(true); + expect(isDropdownOpened(el)).toEqual(true); + clickItem(el, 'Samantha'); - el.find(".ui-select-toggle").click(); - expect($select.open).toEqual(false); - }); + expect(isDropdownOpened(el)).toEqual(false); + }); - it('should clear selection', function() { - scope.selection.selected = scope.people[0]; - var el = createUiSelect({theme : 'select2', allowClear: 'true'}); - var $select = el.scope().$select; + it('should open/close dropdown when clicking caret icon', function () { - // allowClear should be true. - expect($select.allowClear).toEqual(true); + var el = createUiSelect({theme: 'select2'}); + var searchInput = el.find('.ui-select-search'); + var $select = el.scope().$select; - // Trigger clear. - el.find('.select2-search-choice-close').click(); - expect(scope.selection.selected).toEqual(undefined); + expect($select.open).toEqual(false); - // If there is no selection it the X icon should be gone. - expect(el.find('.select2-search-choice-close').length).toEqual(0); + el.find(".ui-select-toggle").click(); + expect($select.open).toEqual(true); - }); - it('should toggle allow-clear directive', function() { - scope.selection.selected = scope.people[0]; - scope.isClearAllowed = false; - - var el = createUiSelect({theme : 'select2', allowClear: '{{isClearAllowed}}'}); - var $select = el.scope().$select; + el.find(".ui-select-toggle").click(); + expect($select.open).toEqual(false); + }); - expect($select.allowClear).toEqual(false); - expect(el.find('.select2-search-choice-close').length).toEqual(0); - - // Turn clear on - scope.isClearAllowed = true; - scope.$digest(); + it('should clear selection', function () { + scope.selection.selected = scope.people[0]; - expect($select.allowClear).toEqual(true); - expect(el.find('.select2-search-choice-close').length).toEqual(1); - }); + var el = createUiSelect({theme: 'select2', allowClear: 'true'}); + var $select = el.scope().$select; + // allowClear should be true. + expect($select.allowClear).toEqual(true); - it('should pass tabindex to focusser', function() { - var el = createUiSelect({tabindex: 5}); + // Trigger clear. + el.find('.select2-search-choice-close').click(); + expect(scope.selection.selected).toEqual(undefined); - expect($(el).find('.ui-select-focusser').attr('tabindex')).toEqual('5'); - expect($(el).attr('tabindex')).toEqual(undefined); - }); + // If there is no selection it the X icon should be gone. + expect(el.find('.select2-search-choice-close').length).toEqual(0); - it('should pass tabindex to focusser when tabindex is an expression', function() { - scope.tabValue = 22; - var el = createUiSelect({tabindex: '{{tabValue + 10}}'}); + }); - expect($(el).find('.ui-select-focusser').attr('tabindex')).toEqual('32'); - expect($(el).attr('tabindex')).toEqual(undefined); - }); + it('should toggle allow-clear directive', function () { + scope.selection.selected = scope.people[0]; + scope.isClearAllowed = false; - it('should not give focusser a tabindex when ui-select does not have one', function() { - var el = createUiSelect(); + var el = createUiSelect({theme: 'select2', allowClear: '{{isClearAllowed}}'}); + var $select = el.scope().$select; - expect($(el).find('.ui-select-focusser').attr('tabindex')).toEqual(undefined); - expect($(el).attr('tabindex')).toEqual(undefined); - }); + expect($select.allowClear).toEqual(false); + expect(el.find('.select2-search-choice-close').length).toEqual(0); - it('should be disabled if the attribute says so', function() { - var el1 = createUiSelect({disabled: true}); - expect(el1.scope().$select.disabled).toEqual(true); - clickMatch(el1); - expect(isDropdownOpened(el1)).toEqual(false); + // Turn clear on + scope.isClearAllowed = true; + scope.$digest(); - var el2 = createUiSelect({disabled: false}); - expect(el2.scope().$select.disabled).toEqual(false); - clickMatch(el2); - expect(isDropdownOpened(el2)).toEqual(true); + expect($select.allowClear).toEqual(true); + expect(el.find('.select2-search-choice-close').length).toEqual(1); + }); - var el3 = createUiSelect(); - expect(el3.scope().$select.disabled).toBeFalsy(); - clickMatch(el3); - expect(isDropdownOpened(el3)).toEqual(true); - }); - it('should allow decline tags when tagging function returns null', function() { - scope.taggingFunc = function (name) { - return null; - }; + it('should pass tabindex to focusser', function () { + var el = createUiSelect({tabindex: 5}); - var el = createUiSelect({tagging: 'taggingFunc'}); - clickMatch(el); + expect($(el).find('.ui-select-focusser').attr('tabindex')).toEqual('5'); + expect($(el).attr('tabindex')).toEqual(undefined); + }); - $(el).scope().$select.search = 'idontexist'; - $(el).scope().$select.activeIndex = 0; - $(el).scope().$select.select('idontexist'); + it('should pass tabindex to focusser when tabindex is an expression', function () { + scope.tabValue = 22; + var el = createUiSelect({tabindex: '{{tabValue + 10}}'}); - expect($(el).scope().$select.selected).not.toBeDefined(); - }); + expect($(el).find('.ui-select-focusser').attr('tabindex')).toEqual('32'); + expect($(el).attr('tabindex')).toEqual(undefined); + }); - it('should allow tagging if the attribute says so', function() { - var el = createUiSelect({tagging: true}); - clickMatch(el); + it('should not give focusser a tabindex when ui-select does not have one', function () { + var el = createUiSelect(); - $(el).scope().$select.select("I don't exist"); + expect($(el).find('.ui-select-focusser').attr('tabindex')).toEqual(undefined); + expect($(el).attr('tabindex')).toEqual(undefined); + }); - expect($(el).scope().$select.selected).toEqual("I don't exist"); - }); + it('should be disabled if the attribute says so', function () { + var el1 = createUiSelect({disabled: true}); + expect(el1.scope().$select.disabled).toEqual(true); + clickMatch(el1); + expect(isDropdownOpened(el1)).toEqual(false); + + var el2 = createUiSelect({disabled: false}); + expect(el2.scope().$select.disabled).toEqual(false); + clickMatch(el2); + expect(isDropdownOpened(el2)).toEqual(true); + + var el3 = createUiSelect(); + expect(el3.scope().$select.disabled).toBeFalsy(); + clickMatch(el3); + expect(isDropdownOpened(el3)).toEqual(true); + }); - it('should format new items using the tagging function when the attribute is a function', function() { - scope.taggingFunc = function (name) { - return { - name: name, - email: name + '@email.com', - group: 'Foo', - age: 12 - }; - }; + // See when an item that evaluates to false (such as "false" or "no") is selected, the placeholder is shown https://github.com/angular-ui/ui-select/pull/32 + it('should not display the placeholder when item evaluates to false', function () { + scope.items = ['false']; - var el = createUiSelect({tagging: 'taggingFunc'}); - clickMatch(el); + var el = compileTemplate( + ' \ + {{$select.selected}} \ + \ +
\ +
\ +
' + ); + expect(el.scope().$select.selected).toEqual(undefined); - $(el).scope().$select.search = 'idontexist'; - $(el).scope().$select.activeIndex = 0; - $(el).scope().$select.select('idontexist'); + clickItem(el, 'false'); - expect($(el).scope().$select.selected).toEqual({ - name: 'idontexist', - email: 'idontexist@email.com', - group: 'Foo', - age: 12 + expect(el.scope().$select.selected).toEqual('false'); + expect(getMatchLabel(el)).toEqual('false'); }); - }); - // See when an item that evaluates to false (such as "false" or "no") is selected, the placeholder is shown https://github.com/angular-ui/ui-select/pull/32 - it('should not display the placeholder when item evaluates to false', function() { - scope.items = ['false']; + it('should close an opened select when another one is opened', function () { + var el1 = createUiSelect(); + var el2 = createUiSelect(); + el1.appendTo(document.body); + el2.appendTo(document.body); + + expect(isDropdownOpened(el1)).toEqual(false); + expect(isDropdownOpened(el2)).toEqual(false); + clickMatch(el1); + expect(isDropdownOpened(el1)).toEqual(true); + expect(isDropdownOpened(el2)).toEqual(false); + clickMatch(el2); + expect(isDropdownOpened(el1)).toEqual(false); + expect(isDropdownOpened(el2)).toEqual(true); + + el1.remove(); + el2.remove(); + }); - var el = compileTemplate( - ' \ - {{$select.selected}} \ - \ -
\ -
\ -
' - ); - expect(el.scope().$select.selected).toEqual(undefined); - - clickItem(el, 'false'); - - expect(el.scope().$select.selected).toEqual('false'); - expect(getMatchLabel(el)).toEqual('false'); - }); - - it('should close an opened select when another one is opened', function() { - var el1 = createUiSelect(); - var el2 = createUiSelect(); - el1.appendTo(document.body); - el2.appendTo(document.body); - - expect(isDropdownOpened(el1)).toEqual(false); - expect(isDropdownOpened(el2)).toEqual(false); - clickMatch(el1); - expect(isDropdownOpened(el1)).toEqual(true); - expect(isDropdownOpened(el2)).toEqual(false); - clickMatch(el2); - expect(isDropdownOpened(el1)).toEqual(false); - expect(isDropdownOpened(el2)).toEqual(true); - - el1.remove(); - el2.remove(); - }); - - describe('disabled options', function() { - function createUiSelect(attrs) { - var attrsDisabled = ''; - if (attrs !== undefined) { - if (attrs.disabled !== undefined) { - attrsDisabled = ' ui-disable-choice="' + attrs.disabled + '"'; - } else { - attrsDisabled = ''; - } - } + describe('disabled options', function () { + function createUiSelect(attrs) { + var attrsDisabled = ''; + if (attrs !== undefined) { + if (attrs.disabled !== undefined) { + attrsDisabled = ' ui-disable-choice="' + attrs.disabled + '"'; + } else { + attrsDisabled = ''; + } + } - return compileTemplate( - ' \ - {{$select.selected.name}} \ - \ + return compileTemplate( + ' \ + {{$select.selected.name}} \ + \
\
\
\
' - ); - } - - function disablePerson(opts) { - opts = opts || {}; - - var key = opts.key || 'people', - disableAttr = opts.disableAttr || 'disabled', - disableBool = opts.disableBool === undefined ? true : opts.disableBool, - matchAttr = opts.match || 'name', - matchVal = opts.matchVal || 'Wladimir'; + ); + } - scope['_' + key] = angular.copy(scope[key]); - scope[key].map(function (model) { - if (model[matchAttr] == matchVal) { - model[disableAttr] = disableBool; + function disablePerson(opts) { + opts = opts || {}; + + var key = opts.key || 'people', + disableAttr = opts.disableAttr || 'disabled', + disableBool = opts.disableBool === undefined ? true : opts.disableBool, + matchAttr = opts.match || 'name', + matchVal = opts.matchVal || 'Wladimir'; + + scope['_' + key] = angular.copy(scope[key]); + scope[key].map(function (model) { + if (model[matchAttr] == matchVal) { + model[disableAttr] = disableBool; + } + return model; + }); } - return model; - }); - } - function resetScope(opts) { - opts = opts || {}; - var key = opts.key || 'people'; - scope[key] = angular.copy(scope['_' + key]); - } + function resetScope(opts) { + opts = opts || {}; + var key = opts.key || 'people'; + scope[key] = angular.copy(scope['_' + key]); + } - describe('without disabling expression', function () { - beforeEach(function() { - disablePerson(); - this.el = createUiSelect(); - }); + describe('without disabling expression', function () { + beforeEach(function () { + disablePerson(); + this.el = createUiSelect(); + }); - it('should not allow disabled options to be selected', function() { - clickItem(this.el, 'Wladimir'); + it('should not allow disabled options to be selected', function () { + clickItem(this.el, 'Wladimir'); - expect(getMatchLabel(this.el)).toEqual('Wladimir'); - }); + expect(getMatchLabel(this.el)).toEqual('Wladimir'); + }); - it('should set a disabled class on the option', function() { - var option = $(this.el).find('.ui-select-choices-row div:contains("Wladimir")'); - var container = option.closest('.ui-select-choices-row'); + it('should set a disabled class on the option', function () { + var option = $(this.el).find('.ui-select-choices-row div:contains("Wladimir")'); + var container = option.closest('.ui-select-choices-row'); - expect(container.hasClass('disabled')).toBeFalsy(); - }); - }); - - describe('disable on truthy property', function () { - beforeEach(function() { - disablePerson({ - disableAttr : 'inactive', - disableBool : true - }); - this.el = createUiSelect({ - disabled: 'person.inactive' + expect(container.hasClass('disabled')).toBeFalsy(); + }); }); - }); - it('should allow the user to define the selected option', function () { - expect($(this.el).find('.ui-select-choices').attr('ui-disable-choice')).toBe('person.inactive'); - }); + describe('disable on truthy property', function () { + beforeEach(function () { + disablePerson({ + disableAttr: 'inactive', + disableBool: true + }); + this.el = createUiSelect({ + disabled: 'person.inactive' + }); + }); - it('should not allow disabled options to be selected', function() { - clickItem(this.el, 'Wladimir'); + it('should allow the user to define the selected option', function () { + expect($(this.el).find('.ui-select-choices').attr('ui-disable-choice')).toBe('person.inactive'); + }); - expect(getMatchLabel(this.el)).not.toEqual('Wladimir'); - }); + it('should not allow disabled options to be selected', function () { + clickItem(this.el, 'Wladimir'); - it('should set a disabled class on the option', function() { + expect(getMatchLabel(this.el)).not.toEqual('Wladimir'); + }); - openDropdown(this.el); + it('should set a disabled class on the option', function () { - var option = $(this.el).find('.ui-select-choices-row div:contains("Wladimir")'); - var container = option.closest('.ui-select-choices-row'); + openDropdown(this.el); - expect(container.hasClass('disabled')).toBeTruthy(); + var option = $(this.el).find('.ui-select-choices-row div:contains("Wladimir")'); + var container = option.closest('.ui-select-choices-row'); - }); - }); + expect(container.hasClass('disabled')).toBeTruthy(); - describe('disable on inverse property check', function () { - beforeEach(function() { - disablePerson({ - disableAttr : 'active', - disableBool : false + }); }); - this.el = createUiSelect({ - disabled: '!person.active' - }); - }); - it('should allow the user to define the selected option', function () { - expect($(this.el).find('.ui-select-choices').attr('ui-disable-choice')).toBe('!person.active'); - }); + describe('disable on inverse property check', function () { + beforeEach(function () { + disablePerson({ + disableAttr: 'active', + disableBool: false + }); + this.el = createUiSelect({ + disabled: '!person.active' + }); + }); - it('should not allow disabled options to be selected', function() { - clickItem(this.el, 'Wladimir'); + it('should allow the user to define the selected option', function () { + expect($(this.el).find('.ui-select-choices').attr('ui-disable-choice')).toBe('!person.active'); + }); - expect(getMatchLabel(this.el)).not.toEqual('Wladimir'); - }); + it('should not allow disabled options to be selected', function () { + clickItem(this.el, 'Wladimir'); - it('should set a disabled class on the option', function() { - openDropdown(this.el); + expect(getMatchLabel(this.el)).not.toEqual('Wladimir'); + }); - var option = $(this.el).find('.ui-select-choices-row div:contains("Wladimir")'); - var container = option.closest('.ui-select-choices-row'); + it('should set a disabled class on the option', function () { + openDropdown(this.el); - expect(container.hasClass('disabled')).toBeTruthy(); - }); - }); + var option = $(this.el).find('.ui-select-choices-row div:contains("Wladimir")'); + var container = option.closest('.ui-select-choices-row'); - describe('disable on expression', function () { - beforeEach(function() { - disablePerson({ - disableAttr : 'status', - disableBool : 'inactive' - }); - this.el = createUiSelect({ - disabled: "person.status == 'inactive'" + expect(container.hasClass('disabled')).toBeTruthy(); + }); }); - }); - it('should allow the user to define the selected option', function () { - expect($(this.el).find('.ui-select-choices').attr('ui-disable-choice')).toBe("person.status == 'inactive'"); - }); + describe('disable on expression', function () { + beforeEach(function () { + disablePerson({ + disableAttr: 'status', + disableBool: 'inactive' + }); + this.el = createUiSelect({ + disabled: "person.status == 'inactive'" + }); + }); - it('should not allow disabled options to be selected', function() { - clickItem(this.el, 'Wladimir'); + it('should allow the user to define the selected option', function () { + expect($(this.el).find('.ui-select-choices').attr('ui-disable-choice')).toBe("person.status == 'inactive'"); + }); - expect(getMatchLabel(this.el)).not.toEqual('Wladimir'); - }); + it('should not allow disabled options to be selected', function () { + clickItem(this.el, 'Wladimir'); - it('should set a disabled class on the option', function() { - openDropdown(this.el); + expect(getMatchLabel(this.el)).not.toEqual('Wladimir'); + }); - var option = $(this.el).find('.ui-select-choices-row div:contains("Wladimir")'); - var container = option.closest('.ui-select-choices-row'); + it('should set a disabled class on the option', function () { + openDropdown(this.el); - expect(container.hasClass('disabled')).toBeTruthy(); - }); - }); + var option = $(this.el).find('.ui-select-choices-row div:contains("Wladimir")'); + var container = option.closest('.ui-select-choices-row'); + + expect(container.hasClass('disabled')).toBeTruthy(); + }); + }); - afterEach(function() { - resetScope(); + afterEach(function () { + resetScope(); + }); }); - }); - describe('choices group', function() { - function getGroupLabel(item) { - return item.parent('.ui-select-choices-group').find('.ui-select-choices-group-label'); - } - function createUiSelect() { - return compileTemplate( - ' \ - {{$select.selected.name}} \ - \ -
\ -
\ -
\ -
' - ); - } + describe('choices group', function () { + function getGroupLabel(item) { + return item.parent('.ui-select-choices-group').find('.ui-select-choices-group-label'); + } - it('should create items group', function() { - var el = createUiSelect(); - expect(el.find('.ui-select-choices-group').length).toBe(3); - }); + function createUiSelect() { + return compileTemplate( + ' \ + {{$select.selected.name}} \ + \ +
\ +
\ +
\ +
' + ); + } - it('should show label before each group', function() { - var el = createUiSelect(); - expect(el.find('.ui-select-choices-group .ui-select-choices-group-label').map(function() { - return this.textContent; - }).toArray()).toEqual(['Foo', 'bar', 'Baz']); - }); + it('should create items group', function () { + var el = createUiSelect(); + expect(el.find('.ui-select-choices-group').length).toBe(3); + }); - it('should hide empty groups', function() { - var el = createUiSelect(); - el.scope().$select.search = 'd'; - scope.$digest(); + it('should show label before each group', function () { + var el = createUiSelect(); + expect(el.find('.ui-select-choices-group .ui-select-choices-group-label').map(function () { + return this.textContent; + }).toArray()).toEqual(['Foo', 'bar', 'Baz']); + }); - expect(el.find('.ui-select-choices-group .ui-select-choices-group-label').map(function() { - return this.textContent; - }).toArray()).toEqual(['Foo']); - }); + it('should hide empty groups', function () { + var el = createUiSelect(); + el.scope().$select.search = 'd'; + scope.$digest(); + + expect(el.find('.ui-select-choices-group .ui-select-choices-group-label').map(function () { + return this.textContent; + }).toArray()).toEqual(['Foo']); + }); - it('should change activeItem through groups', function() { - var el = createUiSelect(); - el.scope().$select.search = 't'; - scope.$digest(); - openDropdown(el); - var choices = el.find('.ui-select-choices-row'); + it('should change activeItem through groups', function () { + var el = createUiSelect(); + el.scope().$select.search = 't'; + scope.$digest(); + openDropdown(el); + var choices = el.find('.ui-select-choices-row'); - expect(choices.eq(0)).toHaveClass('active'); - expect(getGroupLabel(choices.eq(0)).text()).toBe('Foo'); + expect(choices.eq(0)).toHaveClass('active'); + expect(getGroupLabel(choices.eq(0)).text()).toBe('Foo'); - triggerKeydown(el.find('input'), 40 /*Down*/); - scope.$digest(); - expect(choices.eq(1)).toHaveClass('active'); - expect(getGroupLabel(choices.eq(1)).text()).toBe('bar'); + triggerKeydown(el.find('input'), 40 /*Down*/); + scope.$digest(); + expect(choices.eq(1)).toHaveClass('active'); + expect(getGroupLabel(choices.eq(1)).text()).toBe('bar'); + }); }); - }); - - describe('choices group by function', function() { - function createUiSelect() { - return compileTemplate( - ' \ - {{$select.selected.name}} \ - \ -
\ -
\ -
' - ); - } - it("should extract group value through function", function () { - var el = createUiSelect(); - expect(el.find('.ui-select-choices-group .ui-select-choices-group-label').map(function() { - return this.textContent; - }).toArray()).toEqual(['odd', 'even']); + + describe('choices group by function', function () { + function createUiSelect() { + return compileTemplate( + ' \ + {{$select.selected.name}} \ + \ +
\ +
\ +
' + ); + } + + it("should extract group value through function", function () { + var el = createUiSelect(); + expect(el.find('.ui-select-choices-group .ui-select-choices-group-label').map(function () { + return this.textContent; + }).toArray()).toEqual(['odd', 'even']); + }); }); - }); - describe('choices group filter function', function() { - function createUiSelect() { - return compileTemplate('\ + describe('choices group filter function', function () { + function createUiSelect() { + return compileTemplate('\ \ {{$select.selected.name}} \ \
\
\
' - ); - } - it("should sort groups using filter", function () { - var el = createUiSelect(); - expect(el.find('.ui-select-choices-group .ui-select-choices-group-label').map(function() { - return this.textContent; - }).toArray()).toEqual(["Foo", "Baz", "bar"]); + ); + } + + it("should sort groups using filter", function () { + var el = createUiSelect(); + expect(el.find('.ui-select-choices-group .ui-select-choices-group-label').map(function () { + return this.textContent; + }).toArray()).toEqual(["Foo", "Baz", "bar"]); + }); }); - }); - describe('choices group filter array', function() { - function createUiSelect() { - return compileTemplate('\ + describe('choices group filter array', function () { + function createUiSelect() { + return compileTemplate('\ \ {{$select.selected.name}} \
\ \ ' - ); - } - it("should sort groups using filter", function () { - var el = createUiSelect(); - expect(el.find('.ui-select-choices-group .ui-select-choices-group-label').map(function() { - return this.textContent; - }).toArray()).toEqual(["Foo"]); + ); + } + + it("should sort groups using filter", function () { + var el = createUiSelect(); + expect(el.find('.ui-select-choices-group .ui-select-choices-group-label').map(function () { + return this.textContent; + }).toArray()).toEqual(["Foo"]); + }); }); - }); - it('should throw when no ui-select-choices found', function() { - expect(function() { - compileTemplate( - ' \ - \ - ' - ); - }).toThrow(new Error('[ui.select:transcluded] Expected 1 .ui-select-choices but got \'0\'.')); - }); - - it('should throw when no repeat attribute is provided to ui-select-choices', function() { - expect(function() { - compileTemplate( - ' \ - \ - ' - ); - }).toThrow(new Error('[ui.select:repeat] Expected \'repeat\' expression.')); - }); - - it('should throw when repeat attribute has incorrect format ', function() { - expect(function() { - compileTemplate( - ' \ - \ - \ - ' - ); - }).toThrow(new Error('[ui.select:iexp] Expected expression in form of \'_item_ in _collection_[ track by _id_]\' but got \'incorrect format people\'.')); - }); - - it('should throw when no ui-select-match found', function() { - expect(function() { - compileTemplate( - ' \ - \ - ' - ); - }).toThrow(new Error('[ui.select:transcluded] Expected 1 .ui-select-match but got \'0\'.')); - }); - - it('should format the model correctly using alias', function() { - var el = compileTemplate( - ' \ - {{$select.selected.name}} \ - \ -
\ -
\ -
\ -
' - ); - clickItem(el, 'Samantha'); - expect(scope.selection.selected).toBe(scope.people[5]); - }); - - it('should parse the model correctly using alias', function() { - var el = compileTemplate( - ' \ - {{$select.selected.name}} \ - \ -
\ -
\ -
\ -
' - ); - scope.selection.selected = scope.people[5]; - scope.$digest(); - expect(getMatchLabel(el)).toEqual('Samantha'); - }); - - it('should format the model correctly using property of alias', function() { - var el = compileTemplate( - ' \ - {{$select.selected.name}} \ - \ -
\ -
\ -
\ -
' - ); - clickItem(el, 'Samantha'); - expect(scope.selection.selected).toBe('Samantha'); - }); - - it('should parse the model correctly using property of alias', function() { - var el = compileTemplate( - ' \ - {{$select.selected.name}} \ - \ -
\ -
\ -
\ -
' - ); - scope.selection.selected = 'Samantha'; - scope.$digest(); - expect(getMatchLabel(el)).toEqual('Samantha'); - }); - - it('should parse the model correctly using property of alias with async choices data', function() { - var el = compileTemplate( - ' \ - {{$select.selected.name}} \ - \ -
\ -
\ -
\ -
' - ); - $timeout(function() { - scope.peopleAsync = scope.people; + it('should throw when no ui-select-choices found', function () { + expect(function () { + compileTemplate( + ' \ + \ + ' + ); + }).toThrow(new Error('[ui.select:transcluded] Expected 1 .ui-select-choices but got \'0\'.')); }); - scope.selection.selected = 'Samantha'; - scope.$digest(); - expect(getMatchLabel(el)).toEqual(''); + it('should throw when no repeat attribute is provided to ui-select-choices', function () { + expect(function () { + compileTemplate( + ' \ + \ + ' + ); + }).toThrow(new Error('[ui.select:repeat] Expected \'repeat\' expression.')); + }); - $timeout.flush(); //After choices populated (async), it should show match correctly - expect(getMatchLabel(el)).toEqual('Samantha'); + it('should throw when repeat attribute has incorrect format ', function () { + expect(function () { + compileTemplate( + ' \ + \ + \ + ' + ); + }).toThrow(new Error('[ui.select:iexp] Expected expression in form of \'_item_ in _collection_[ track by _id_]\' but got \'incorrect format people\'.')); + }); - }); + it('should throw when no ui-select-match found', function () { + expect(function () { + compileTemplate( + ' \ + \ + ' + ); + }).toThrow(new Error('[ui.select:transcluded] Expected 1 .ui-select-match but got \'0\'.')); + }); - //TODO Is this really something we should expect? - it('should parse the model correctly using property of alias but passed whole object', function() { - var el = compileTemplate( - ' \ - {{$select.selected.name}} \ - \ -
\ -
\ -
\ -
' - ); - scope.selection.selected = scope.people[5]; - scope.$digest(); - expect(getMatchLabel(el)).toEqual('Samantha'); - }); - - it('should format the model correctly without alias', function() { - var el = createUiSelect(); - clickItem(el, 'Samantha'); - expect(scope.selection.selected).toBe(scope.people[5]); - }); - - it('should parse the model correctly without alias', function() { - var el = createUiSelect(); - scope.selection.selected = scope.people[5]; - scope.$digest(); - expect(getMatchLabel(el)).toEqual('Samantha'); - }); - - it('should display choices correctly with child array', function() { - var el = compileTemplate( - ' \ - {{$select.selected.name}} \ - \ -
\ -
\ -
\ -
' - ); - scope.selection.selected = scope.people[5]; - scope.$digest(); - expect(getMatchLabel(el)).toEqual('Samantha'); - }); - - it('should format the model correctly using property of alias and when using child array for choices', function() { - var el = compileTemplate( - ' \ - {{$select.selected.name}} \ - \ -
\ -
\ -
\ -
' - ); - clickItem(el, 'Samantha'); - expect(scope.selection.selected).toBe('Samantha'); - }); + it('should format the model correctly using alias', function () { + var el = compileTemplate( + ' \ + {{$select.selected.name}} \ + \ +
\ +
\ +
\ +
' + ); + clickItem(el, 'Samantha'); + expect(scope.selection.selected).toBe(scope.people[5]); + }); - it('should invoke select callback on select', function () { + it('should parse the model correctly using alias', function () { + var el = compileTemplate( + ' \ + {{$select.selected.name}} \ + \ +
\ +
\ +
\ +
' + ); + scope.selection.selected = scope.people[5]; + scope.$digest(); + expect(getMatchLabel(el)).toEqual('Samantha'); + }); - scope.onSelectFn = function ($item, $model, $label) { - scope.$item = $item; - scope.$model = $model; - }; - var el = compileTemplate( - ' \ - {{$select.selected.name}} \ - \ -
\ -
\ -
\ -
' - ); + it('should format the model correctly using property of alias', function () { + var el = compileTemplate( + ' \ + {{$select.selected.name}} \ + \ +
\ +
\ +
\ +
' + ); + clickItem(el, 'Samantha'); + expect(scope.selection.selected).toBe('Samantha'); + }); - expect(scope.$item).toBeFalsy(); - expect(scope.$model).toBeFalsy(); + it('should parse the model correctly using property of alias', function () { + var el = compileTemplate( + ' \ + {{$select.selected.name}} \ + \ +
\ +
\ +
\ +
' + ); + scope.selection.selected = 'Samantha'; + scope.$digest(); + expect(getMatchLabel(el)).toEqual('Samantha'); + }); - clickItem(el, 'Samantha'); - $timeout.flush(); + it('should parse the model correctly using property of alias with async choices data', function () { + var el = compileTemplate( + ' \ + {{$select.selected.name}} \ + \ +
\ +
\ +
\ +
' + ); + $timeout(function () { + scope.peopleAsync = scope.people; + }); + scope.selection.selected = 'Samantha'; + scope.$digest(); + expect(getMatchLabel(el)).toEqual(''); - expect(scope.selection.selected).toBe('Samantha'); + $timeout.flush(); //After choices populated (async), it should show match correctly + expect(getMatchLabel(el)).toEqual('Samantha'); - expect(scope.$item).toEqual(scope.people[5]); - expect(scope.$model).toEqual('Samantha'); + }); - }); + //TODO Is this really something we should expect? + it('should parse the model correctly using property of alias but passed whole object', function () { + var el = compileTemplate( + ' \ + {{$select.selected.name}} \ + \ +
\ +
\ +
\ +
' + ); + scope.selection.selected = scope.people[5]; + scope.$digest(); + expect(getMatchLabel(el)).toEqual('Samantha'); + }); - it('should invoke hover callback', function(){ + it('should format the model correctly without alias', function () { + var el = createUiSelect(); + clickItem(el, 'Samantha'); + expect(scope.selection.selected).toBe(scope.people[5]); + }); - var highlighted; - scope.onHighlightFn = function ($item) { - highlighted = $item; - }; + it('should parse the model correctly without alias', function () { + var el = createUiSelect(); + scope.selection.selected = scope.people[5]; + scope.$digest(); + expect(getMatchLabel(el)).toEqual('Samantha'); + }); - var el = compileTemplate( - ' \ - {{$select.selected.name}} \ - \ -
\ -
\ -
\ -
' - ); + it('should display choices correctly with child array', function () { + var el = compileTemplate( + ' \ + {{$select.selected.name}} \ + \ +
\ +
\ +
\ +
' + ); + scope.selection.selected = scope.people[5]; + scope.$digest(); + expect(getMatchLabel(el)).toEqual('Samantha'); + }); - expect(highlighted).toBeFalsy(); + it('should format the model correctly using property of alias and when using child array for choices', function () { + var el = compileTemplate( + ' \ + {{$select.selected.name}} \ + \ +
\ +
\ +
\ +
' + ); + clickItem(el, 'Samantha'); + expect(scope.selection.selected).toBe('Samantha'); + }); - if (!isDropdownOpened(el)){ - openDropdown(el); - } + it('should invoke select callback on select', function () { - $(el).find('.ui-select-choices-row div:contains("Samantha")').trigger('mouseover'); - scope.$digest(); + var el = compileTemplate( + ' \ + {{$select.selected.name}} \ + \ +
\ +
\ +
\ +
' + ); - expect(highlighted).toBe(scope.people[5]); - }); + el.scope().$select.afterSelect = function ($item) { + scope.$item = $item; + }; - it('should set $item & $model correctly when invoking callback on select and no single prop. binding', function () { + expect(scope.$item).toBeFalsy(); + expect(scope.$model).toBeFalsy(); - scope.onSelectFn = function ($item, $model, $label) { - scope.$item = $item; - scope.$model = $model; - }; + clickItem(el, 'Samantha'); + $timeout.flush(); - var el = compileTemplate( - ' \ - {{$select.selected.name}} \ - \ -
\ -
\ -
\ -
' - ); + expect(scope.selection.selected).toBe('Samantha'); - expect(scope.$item).toBeFalsy(); - expect(scope.$model).toBeFalsy(); + expect(scope.$item).toEqual(scope.people[5]); - clickItem(el, 'Samantha'); - expect(scope.$item).toEqual(scope.$model); + }); - }); + it('should highlight matched value correctly when it is a number', function () { + var el = compileTemplate( + ' \ + {{$select.selected.age}} \ + \ +
\ +
\ +
' + ); + openDropdown(el); + setSearchText(el, '43'); - it('should invoke remove callback on remove', function () { + var choices = $(el).find('.ui-select-choices-row'); + expect(choices.length).toEqual(1); - scope.onRemoveFn = function ($item, $model, $label) { - scope.$item = $item; - scope.$model = $model; - }; + clickItem(el, '43'); + expect(scope.selection.selected).toBe(43); + }); - var el = compileTemplate( - ' \ - {{$select.selected.name}} \ - \ -
\ -
\ -
\ -
' - ); + it('should invoke before-select callback before select callback synchronously', function () { + var order = []; + var el = compileTemplate( + ' \ + {{$select.selected.name}} \ + \ +
\ +
\ +
\ +
' + ); - expect(scope.$item).toBeFalsy(); - expect(scope.$model).toBeFalsy(); + el.scope().$select.beforeSelect = function ($item) { + order.push('beforeSelectFn'); + return true; + }; + el.scope().$select.afterSelect = function ($item) { + order.push('afterSelectFn'); + }; - clickItem(el, 'Samantha'); - clickItem(el, 'Adrian'); - el.find('.ui-select-match-item').first().find('.ui-select-match-close').click(); - $timeout.flush(); + clickItem(el, 'Samantha'); + $timeout.flush(); - expect(scope.$item).toBe(scope.people[5]); - expect(scope.$model).toBe('Samantha'); + expect(order[0]).toEqual('beforeSelectFn'); + expect(order[1]).toEqual('afterSelectFn'); + }); - }); + it('should invoke before-select callback before select callback when promised', inject(function ($q) { + var order = []; + var el = compileTemplate( + ' \ + {{$select.selected.name}} \ + \ +
\ +
\ +
\ +
' + ); - it('should set $item & $model correctly when invoking callback on remove and no single prop. binding', function () { + el.scope().$select.beforeSelect = function ($item) { + var deferred = $q.defer(); + $timeout(function () { + order.push('beforeSelectFn'); + deferred.resolve(order); + }); + return deferred.promise; + }; + el.scope().$select.afterSelect = function ($item) { + order.push('afterSelectFn'); + }; - scope.onRemoveFn = function ($item, $model, $label) { - scope.$item = $item; - scope.$model = $model; - }; + clickItem(el, 'Samantha'); + $timeout.flush(); - var el = compileTemplate( - ' \ - {{$select.selected.name}} \ - \ -
\ -
\ -
\ -
' - ); + expect(order[0]).toEqual('beforeSelectFn'); + expect(order[1]).toEqual('afterSelectFn'); + })); - expect(scope.$item).toBeFalsy(); - expect(scope.$model).toBeFalsy(); + it('should complete on-select if before-select callback promise is resolved', inject(function ($q) { + var el = compileTemplate( + ' \ + {{$select.selected.name}} \ + \ +
\ +
\ +
\ +
' + ); - clickItem(el, 'Samantha'); - clickItem(el, 'Adrian'); - el.find('.ui-select-match-item').first().find('.ui-select-match-close').click(); - $timeout.flush(); + el.scope().$select.beforeSelect = function ($item) { + var deferred = $q.defer(); + $timeout(function () { + deferred.resolve(true); + }); + return deferred.promise; + }; + el.scope().$select.afterSelect = function ($item) { + scope.$item = $item; + }; - expect(scope.$item).toBe(scope.people[5]); - expect(scope.$model).toBe(scope.$item); - }); + expect(scope.$item).toBeFalsy(); +// expect(scope.$model).toBeFalsy(); - it('should allow creating tag in single select mode with tagging enabled', function() { + clickItem(el, 'Samantha'); + $timeout.flush(); - scope.taggingFunc = function (name) { - return name; - }; + expect(scope.selection.selected).toBe('Samantha'); - var el = compileTemplate( - ' \ - {{$select.selected.name}} \ - \ -
\ -
\ -
\ -
' - ); + expect(scope.$item).toEqual(scope.people[5]); +// expect(scope.$model).toEqual('Samantha'); + })); - clickMatch(el); + it('should abort selection if before-select callback returns falsy', function () { + var el = compileTemplate( + ' \ + {{$select.selected.name}} \ + \ +
\ +
\ +
\ +
' + ); - var searchInput = el.find('.ui-select-search'); + el.scope().$select.beforeSelect = function ($item) { + return false; + }; + el.scope().$select.afterSelect = function ($item) { + scope.$item = $item; + }; - setSearchText(el, 'idontexist'); + expect(scope.$item).toBeFalsy(); +// expect(scope.$model).toBeFalsy(); - triggerKeydown(searchInput, Key.Enter); + clickItem(el, 'Samantha'); + $timeout.flush(); - expect($(el).scope().$select.selected).toEqual('idontexist'); - }); + expect(scope.$item).toBeFalsy(); +// expect(scope.$model).toBeFalsy(); + }); - it('should allow creating tag on ENTER in multiple select mode with tagging enabled, no labels', function() { + it('should abort selection if before-select callback rejects promise', inject(function ($q) { + var el = compileTemplate( + ' \ + {{$select.selected.name}} \ + \ +
\ +
\ +
\ +
' + ); - scope.taggingFunc = function (name) { - return name; - }; + el.scope().$select.beforeSelect = function ($item) { + var deferred = $q.defer(); + $timeout(function () { + deferred.reject(); + }); + return deferred.promise; + }; + el.scope().$select.afterSelect = function ($item) { + scope.$item = $item; + }; - var el = compileTemplate( - ' \ - {{$select.selected.name}} \ - \ -
\ -
\ -
\ -
' - ); + expect(scope.$item).toBeFalsy(); - var searchInput = el.find('.ui-select-search'); + clickItem(el, 'Samantha'); + $timeout.flush(); - setSearchText(el, 'idontexist'); + expect(scope.$item).toBeFalsy(); - triggerKeydown(searchInput, Key.Enter); + })); - expect($(el).scope().$select.selected).toEqual(['idontexist']); - }); + it('should keep reference to current selection and incoming selection within before-select callback', function () { + var currentSelection, incomingSelection; - it('should append/transclude content (with correct scope) that users add at tag', function () { + var el = compileTemplate( + ' \ + {{$select.selected.name}} \ + \ +
\ +
\ +
\ +
' + ); - var el = compileTemplate( - ' \ - \ - {{$select.selected.name}}\ - {{$select.selected.name | uppercase}}\ - \ - \ -
\ -
\ -
' - ); + el.scope().$select.beforeSelect = function ($item) { + incomingSelection = $item; + currentSelection = scope.selection.selected; + return true; + }; + + clickItem(el, 'Samantha'); + $timeout.flush(); + + expect(currentSelection).toBeFalsy(); + expect(incomingSelection.name).toBe('Samantha'); + + clickItem(el, 'Adam'); + $timeout.flush(); + + expect(currentSelection).toBe('Samantha'); + expect(incomingSelection.name).toBe('Adam'); + + }); + + it('should invoke highlight callback', function () { + var highlighted; + scope.onHighlightFn = function ($item) { + highlighted = $item; + }; + + var el = compileTemplate( + ' \ + {{$select.selected.name}} \ + \ +
\ +
\ +
\ +
' + ); - clickItem(el, 'Samantha'); - expect(getMatchLabel(el).trim()).toEqual('Samantha'); + expect(highlighted).toBeFalsy(); - clickItem(el, 'Wladimir'); - expect(getMatchLabel(el).trim()).not.toEqual('Wladimir'); - expect(getMatchLabel(el).trim()).toEqual('WLADIMIR'); + if (!isDropdownOpened(el)) { + openDropdown(el); + } - }); - it('should append/transclude content (with correct scope) that users add at tag', function () { + $(el).find('.ui-select-choices-row div:contains("Samantha")').trigger('mouseover'); + scope.$digest(); - var el = compileTemplate( - ' \ - \ - \ - \ -
\ -
\ - I should appear only once\ -
\ -
\ -
' - ); + expect(highlighted).toBe(scope.people[5]); + }); - openDropdown(el); - expect($(el).find('.only-once').length).toEqual(1); + it('should set $item & $model correctly when invoking callback on select and no single prop. binding', function () { + var el = compileTemplate( + ' \ + {{$select.selected.name}} \ + \ +
\ +
\ +
\ +
' + ); + el.scope().$select.beforeSelect = function ($item) { + scope.$item = $item; + return true; + }; - }); + expect(scope.$item).toBeFalsy(); - it('should call refresh function when search text changes', function () { + clickItem(el, 'Samantha'); + expect(scope.$item).toEqual(scope.selection.selected); + }); - var el = compileTemplate( - ' \ - \ - \ - \ -
\ -
\ - I should appear only once\ -
\ -
\ -
' - ); + it('should invoke remove callback on remove', function () { + var el = compileTemplate( + ' \ + {{$select.selected.name}} \ + \ +
\ +
\ +
\ +
' + ); - scope.fetchFromServer = function(){}; + el.scope().$select.afterRemove = function ($item) { + scope.$item = $item; + }; - spyOn(scope, 'fetchFromServer'); + expect(scope.$item).toBeFalsy(); - el.scope().$select.search = 'r'; - scope.$digest(); - $timeout.flush(); + clickItem(el, 'Samantha'); + clickItem(el, 'Adrian'); + el.find('.ui-select-match-item').first().find('.ui-select-match-close').click(); + $timeout.flush(); - expect(scope.fetchFromServer).toHaveBeenCalledWith('r'); + expect(scope.$item.name).toBe(scope.people[5].name); + expect(scope.selection.selected[0]).toBe(scope.people[3].name); + }); - }); + it('should set $item correctly when invoking callback on remove and no single prop. binding', function () { + var el = compileTemplate( + ' \ + {{$select.selected.name}} \ + \ +
\ +
\ +
\ +
' + ); - it('should call refresh function when search text changes', function () { + el.scope().$select.afterRemove = function ($item) { + scope.$item = $item; + }; - var el = compileTemplate( - ' \ - \ - \ - \ -
\ -
\ - I should appear only once\ -
\ -
\ -
' - ); + expect(scope.$item).toBeFalsy(); - scope.fetchFromServer = function(){}; + clickItem(el, 'Samantha'); + clickItem(el, 'Adrian'); + el.find('.ui-select-match-item').first().find('.ui-select-match-close').click(); + $timeout.flush(); - spyOn(scope, 'fetchFromServer'); + expect(scope.$item.name).toBe(scope.people[5].name); + expect(scope.selection.selected[0].name).toBe(scope.people[3].name); + }); - el.scope().$select.search = 'r'; - scope.$digest(); - $timeout.flush(); + it('should append/transclude content (with correct scope) that users add at tag', function () { + var el = compileTemplate( + ' \ + \ + {{$select.selected.name}}\ + {{$select.selected.name | uppercase}}\ + \ + \ +
\ +
\ +
' + ); - expect(scope.fetchFromServer).toHaveBeenCalledWith('r'); + clickItem(el, 'Samantha'); + expect(getMatchLabel(el).trim()).toEqual('Samantha'); - }); + clickItem(el, 'Wladimir'); + expect(getMatchLabel(el).trim()).not.toEqual('Wladimir'); + expect(getMatchLabel(el).trim()).toEqual('WLADIMIR'); + }); - it('should format view value correctly when using single property binding and refresh function', function () { + it('should append/transclude content (with correct scope) that users add at tag', function () { + var el = compileTemplate( + ' \ + \ + \ + \ +
\ +
\ + I should appear only once\ +
\ +
\ +
' + ); - var el = compileTemplate( - ' \ - {{$select.selected.name}} \ - \ -
\ -
\ - I should appear only once\ -
\ -
\ -
' - ); + openDropdown(el); + expect($(el).find('.only-once').length).toEqual(1); + }); - scope.fetchFromServer = function(searching){ + it('should format view value correctly when using single property binding and refresh function', function () { + var el = compileTemplate( + ' \ + {{$select.selected.name}} \ + \ +
\ +
\ + I should appear only once\ +
\ +
\ +
' + ); - if (searching == 's') - return scope.people; + scope.fetchFromServer = function (searching) { - if (searching == 'o'){ - scope.people = []; //To simulate cases were previously selected item isnt in the list anymore - } + if (searching == 's') + return scope.people; - }; + if (searching == 'o') { + scope.people = []; //To simulate cases were previously selected item isnt in the list anymore + } - setSearchText(el, 'r'); - clickItem(el, 'Samantha'); - expect(getMatchLabel(el)).toBe('Samantha'); + }; - setSearchText(el, 'o'); - expect(getMatchLabel(el)).toBe('Samantha'); + setSearchText(el, 'r'); + clickItem(el, 'Samantha'); + expect(getMatchLabel(el)).toBe('Samantha'); - }); + setSearchText(el, 'o'); + expect(getMatchLabel(el)).toBe('Samantha'); + }); - describe('search-enabled option', function() { + describe('search-enabled option', function () { - var el; + var el; - function setupSelectComponent(searchEnabled, theme) { - el = compileTemplate( - ' \ + function setupSelectComponent(searchEnabled, theme) { + el = compileTemplate( + ' \ {{$select.selected.name}} \ \
\
\
\
' - ); - } - - describe('selectize theme', function() { - - it('should show search input when true', function() { - setupSelectComponent(true, 'selectize'); - expect($(el).find('.ui-select-search')).not.toHaveClass('ng-hide'); - }); + ); + } - it('should hide search input when false', function() { - setupSelectComponent(false, 'selectize'); - expect($(el).find('.ui-select-search')).toHaveClass('ng-hide'); - }); + describe('selectize theme', function () { + it('should show search input when true', function () { + setupSelectComponent(true, 'selectize'); + expect($(el).find('.ui-select-search')).not.toHaveClass('ng-hide'); + }); - }); + it('should hide search input when false', function () { + setupSelectComponent(false, 'selectize'); + expect($(el).find('.ui-select-search')).toHaveClass('ng-hide'); + }); - describe('select2 theme', function() { + }); - it('should show search input when true', function() { - setupSelectComponent('true', 'select2'); - expect($(el).find('.select2-search')).not.toHaveClass('ng-hide'); - }); + describe('select2 theme', function () { + it('should show search input when true', function () { + setupSelectComponent('true', 'select2'); + expect($(el).find('.select2-search')).not.toHaveClass('ng-hide'); + }); - it('should hide search input when false', function() { - setupSelectComponent('false', 'select2'); - expect($(el).find('.select2-search')).toHaveClass('ng-hide'); - }); + it('should hide search input when false', function () { + setupSelectComponent('false', 'select2'); + expect($(el).find('.select2-search')).toHaveClass('ng-hide'); + }); - }); + }); - describe('bootstrap theme', function() { + describe('bootstrap theme', function () { + it('should show search input when true', function () { + setupSelectComponent('true', 'bootstrap'); + clickMatch(el); + expect($(el).find('.ui-select-search')).not.toHaveClass('ui-select-offscreen'); + }); - it('should show search input when true', function() { - setupSelectComponent('true', 'bootstrap'); - clickMatch(el); - expect($(el).find('.ui-select-search')).not.toHaveClass('ng-hide'); - }); + it('should hide search input when false', function () { + setupSelectComponent('false', 'bootstrap'); + clickMatch(el); + expect($(el).find('.ui-select-search')).toHaveClass('ui-select-offscreen'); + }); - it('should hide search input when false', function() { - setupSelectComponent('false', 'bootstrap'); - clickMatch(el); - expect($(el).find('.ui-select-search')).toHaveClass('ng-hide'); - }); + }); }); - }); - - describe('multi selection', function() { - - function createUiSelectMultiple(attrs) { - var attrsHtml = ''; - if (attrs !== undefined) { - if (attrs.disabled !== undefined) { attrsHtml += ' ng-disabled="' + attrs.disabled + '"'; } - if (attrs.required !== undefined) { attrsHtml += ' ng-required="' + attrs.required + '"'; } - if (attrs.tabindex !== undefined) { attrsHtml += ' tabindex="' + attrs.tabindex + '"'; } - if (attrs.closeOnSelect !== undefined) { attrsHtml += ' close-on-select="' + attrs.closeOnSelect + '"'; } - if (attrs.tagging !== undefined) { attrsHtml += ' tagging="' + attrs.tagging + '"'; } - if (attrs.taggingTokens !== undefined) { attrsHtml += ' tagging-tokens="' + attrs.taggingTokens + '"'; } - } + describe('multi selection', function () { + function createUiSelectMultiple(attrs) { + var attrsHtml = ''; + if (attrs !== undefined) { + if (attrs.disabled !== undefined) { + attrsHtml += ' ng-disabled="' + attrs.disabled + '"'; + } + if (attrs.required !== undefined) { + attrsHtml += ' ng-required="' + attrs.required + '"'; + } + if (attrs.tabindex !== undefined) { + attrsHtml += ' tabindex="' + attrs.tabindex + '"'; + } + if (attrs.closeOnSelect !== undefined) { + attrsHtml += ' close-on-select="' + attrs.closeOnSelect + '"'; + } + if (attrs.tagging !== undefined) { + attrsHtml += ' ui-select-tagging="' + attrs.tagging + '"'; + } + if (attrs.taggingTokens !== undefined) { + attrsHtml += ' tagging-tokens="' + attrs.taggingTokens + '"'; + } + } - return compileTemplate( - ' \ + return compileTemplate( + ' \ {{$item.name}} <{{$item.email}}> \ \
\
\
\
' - ); - } - - it('should render initial state', function() { - var el = createUiSelectMultiple(); - expect(el).toHaveClass('ui-select-multiple'); - expect(el.scope().$select.selected.length).toBe(0); - expect(el.find('.ui-select-match-item').length).toBe(0); - }); - - it('should set model as an empty array if ngModel isnt defined after an item is selected', function () { + ); + } - // scope.selection.selectedMultiple = []; - var el = createUiSelectMultiple(); - expect(scope.selection.selectedMultiple instanceof Array).toBe(false); - clickItem(el, 'Samantha'); - expect(scope.selection.selectedMultiple instanceof Array).toBe(true); - }); + it('should render initial state', function () { + var el = createUiSelectMultiple(); + expect(el).toHaveClass('ui-select-multiple'); + expect(el.scope().$select.selected.length).toBe(0); + expect(el.find('.ui-select-match-item').length).toBe(0); + }); - it('should render initial selected items', function() { - scope.selection.selectedMultiple = [scope.people[4], scope.people[5]]; //Wladimir & Samantha - var el = createUiSelectMultiple(); - expect(el.scope().$select.selected.length).toBe(2); - expect(el.find('.ui-select-match-item').length).toBe(2); - }); + it('should set model as an empty array if ngModel isnt defined after an item is selected', function () { + // scope.selection.selectedMultiple = []; + var el = createUiSelectMultiple(); + expect(scope.selection.selectedMultiple instanceof Array).toBe(false); + clickItem(el, 'Samantha'); + expect(scope.selection.selectedMultiple instanceof Array).toBe(true); + }); - it('should remove item by pressing X icon', function() { - scope.selection.selectedMultiple = [scope.people[4], scope.people[5]]; //Wladimir & Samantha - var el = createUiSelectMultiple(); - expect(el.scope().$select.selected.length).toBe(2); - el.find('.ui-select-match-item').first().find('.ui-select-match-close').click(); - expect(el.scope().$select.selected.length).toBe(1); - // $timeout.flush(); - }); + it('should render initial selected items', function () { + scope.selection.selectedMultiple = [scope.people[4], scope.people[5]]; //Wladimir & Samantha + var el = createUiSelectMultiple(); + expect(el.scope().$select.selected.length).toBe(2); + expect(el.find('.ui-select-match-item').length).toBe(2); + }); - it('should pass tabindex to searchInput', function() { - var el = createUiSelectMultiple({tabindex: 5}); - var searchInput = el.find('.ui-select-search'); + it('should remove item by pressing X icon', function () { + scope.selection.selectedMultiple = [scope.people[4], scope.people[5]]; //Wladimir & Samantha + var el = createUiSelectMultiple(); + expect(el.scope().$select.selected.length).toBe(2); + el.find('.ui-select-match-item').first().find('.ui-select-match-close').click(); + expect(el.scope().$select.selected.length).toBe(1); + // $timeout.flush(); + }); - expect(searchInput.attr('tabindex')).toEqual('5'); - expect($(el).attr('tabindex')).toEqual(undefined); - }); + it('should pass tabindex to searchInput', function () { + var el = createUiSelectMultiple({tabindex: 5}); + var searchInput = el.find('.ui-select-search'); - it('should pass tabindex to searchInput when tabindex is an expression', function() { - scope.tabValue = 22; - var el = createUiSelectMultiple({tabindex: '{{tabValue + 10}}'}); - var searchInput = el.find('.ui-select-search'); + expect(searchInput.attr('tabindex')).toEqual('5'); + expect($(el).attr('tabindex')).toEqual(undefined); + }); - expect(searchInput.attr('tabindex')).toEqual('32'); - expect($(el).attr('tabindex')).toEqual(undefined); - }); + it('should pass tabindex to searchInput when tabindex is an expression', function () { + scope.tabValue = 22; + var el = createUiSelectMultiple({tabindex: '{{tabValue + 10}}'}); + var searchInput = el.find('.ui-select-search'); - it('should not give searchInput a tabindex when ui-select does not have one', function() { - var el = createUiSelectMultiple(); - var searchInput = el.find('.ui-select-search'); + expect(searchInput.attr('tabindex')).toEqual('32'); + expect($(el).attr('tabindex')).toEqual(undefined); + }); - expect(searchInput.attr('tabindex')).toEqual(undefined); - expect($(el).attr('tabindex')).toEqual(undefined); - }); + it('should not give searchInput a tabindex when ui-select does not have one', function () { + var el = createUiSelectMultiple(); + var searchInput = el.find('.ui-select-search'); - it('should update size of search input after removing an item', function() { - scope.selection.selectedMultiple = [scope.people[4], scope.people[5]]; //Wladimir & Samantha - var el = createUiSelectMultiple(); + expect(searchInput.attr('tabindex')).toEqual(undefined); + expect($(el).attr('tabindex')).toEqual(undefined); + }); - spyOn(el.scope().$select, 'sizeSearchInput'); + it('should update size of search input after removing an item', function () { + scope.selection.selectedMultiple = [scope.people[4], scope.people[5]]; //Wladimir & Samantha + var el = createUiSelectMultiple(); - var searchInput = el.find('.ui-select-search'); - var oldWidth = searchInput.css('width'); + spyOn(el.scope().$select, 'sizeSearchInput'); - el.find('.ui-select-match-item').first().find('.ui-select-match-close').click(); - expect(el.scope().$select.sizeSearchInput).toHaveBeenCalled(); + var searchInput = el.find('.ui-select-search'); + var oldWidth = searchInput.css('width'); - }); + el.find('.ui-select-match-item').first().find('.ui-select-match-close').click(); + expect(el.scope().$select.sizeSearchInput).toHaveBeenCalled(); - it('should move to last match when pressing BACKSPACE key from search', function() { + }); - var el = createUiSelectMultiple(); - var searchInput = el.find('.ui-select-search'); + it('should move to last match when pressing BACKSPACE key from search', function () { - expect(isDropdownOpened(el)).toEqual(false); - triggerKeydown(searchInput, Key.Backspace); - expect(isDropdownOpened(el)).toEqual(false); - expect(el.scope().$selectMultiple.activeMatchIndex).toBe(el.scope().$select.selected.length - 1); + var el = createUiSelectMultiple(); + var searchInput = el.find('.ui-select-search'); - }); + expect(isDropdownOpened(el)).toEqual(false); + triggerKeydown(searchInput, Key.Backspace); + expect(isDropdownOpened(el)).toEqual(false); + expect(el.scope().$selectMultiple.activeMatchIndex).toBe(el.scope().$select.selected.length - 1); - it('should remove highlighted match when pressing BACKSPACE key from search and decrease activeMatchIndex', function() { + }); - scope.selection.selectedMultiple = [scope.people[4], scope.people[5], scope.people[6]]; //Wladimir, Samantha & Nicole - var el = createUiSelectMultiple(); - var searchInput = el.find('.ui-select-search'); + it('should remove highlighted match when pressing BACKSPACE key from search and decrease activeMatchIndex', + function () { - expect(isDropdownOpened(el)).toEqual(false); - triggerKeydown(searchInput, Key.Left); - triggerKeydown(searchInput, Key.Left); - triggerKeydown(searchInput, Key.Backspace); - expect(el.scope().$select.selected).toEqual([scope.people[4], scope.people[6]]); //Wladimir & Nicole + scope.selection.selectedMultiple = [scope.people[4], scope.people[5], scope.people[6]]; //Wladimir, Samantha & Nicole + var el = createUiSelectMultiple(); + var searchInput = el.find('.ui-select-search'); - expect(el.scope().$selectMultiple.activeMatchIndex).toBe(0); + expect(isDropdownOpened(el)).toEqual(false); + triggerKeydown(searchInput, Key.Left); + triggerKeydown(searchInput, Key.Left); + triggerKeydown(searchInput, Key.Backspace); + expect(el.scope().$select.selected).toEqual([scope.people[4], scope.people[6]]); //Wladimir & Nicole - }); + expect(el.scope().$selectMultiple.activeMatchIndex).toBe(0); - it('should remove highlighted match when pressing DELETE key from search and keep same activeMatchIndex', function() { + }); - scope.selection.selectedMultiple = [scope.people[4], scope.people[5], scope.people[6]]; //Wladimir, Samantha & Nicole - var el = createUiSelectMultiple(); - var searchInput = el.find('.ui-select-search'); + it('should remove highlighted match when pressing DELETE key from search and keep same activeMatchIndex', + function () { - expect(isDropdownOpened(el)).toEqual(false); - triggerKeydown(searchInput, Key.Left); - triggerKeydown(searchInput, Key.Left); - triggerKeydown(searchInput, Key.Delete); - expect(el.scope().$select.selected).toEqual([scope.people[4], scope.people[6]]); //Wladimir & Nicole + scope.selection.selectedMultiple = [scope.people[4], scope.people[5], scope.people[6]]; //Wladimir, Samantha & Nicole + var el = createUiSelectMultiple(); + var searchInput = el.find('.ui-select-search'); - expect(el.scope().$selectMultiple.activeMatchIndex).toBe(1); + expect(isDropdownOpened(el)).toEqual(false); + triggerKeydown(searchInput, Key.Left); + triggerKeydown(searchInput, Key.Left); + triggerKeydown(searchInput, Key.Delete); + expect(el.scope().$select.selected).toEqual([scope.people[4], scope.people[6]]); //Wladimir & Nicole - }); + expect(el.scope().$selectMultiple.activeMatchIndex).toBe(1); - it('should move to last match when pressing LEFT key from search', function() { + }); - var el = createUiSelectMultiple(); - var searchInput = el.find('.ui-select-search'); + it('should move to last match when pressing LEFT key from search', function () { - expect(isDropdownOpened(el)).toEqual(false); - triggerKeydown(searchInput, Key.Left); - expect(isDropdownOpened(el)).toEqual(false); - expect(el.scope().$selectMultiple.activeMatchIndex).toBe(el.scope().$select.selected.length - 1); + var el = createUiSelectMultiple(); + var searchInput = el.find('.ui-select-search'); - }); + expect(isDropdownOpened(el)).toEqual(false); + triggerKeydown(searchInput, Key.Left); + expect(isDropdownOpened(el)).toEqual(false); + expect(el.scope().$selectMultiple.activeMatchIndex).toBe(el.scope().$select.selected.length - 1); - it('should move between matches when pressing LEFT key from search', function() { + }); - scope.selection.selectedMultiple = [scope.people[4], scope.people[5], scope.people[6]]; //Wladimir, Samantha & Nicole - var el = createUiSelectMultiple(); - var searchInput = el.find('.ui-select-search'); + it('should move between matches when pressing LEFT key from search', function () { - expect(isDropdownOpened(el)).toEqual(false); - triggerKeydown(searchInput, Key.Left); - triggerKeydown(searchInput, Key.Left); - expect(isDropdownOpened(el)).toEqual(false); - expect(el.scope().$selectMultiple.activeMatchIndex).toBe(el.scope().$select.selected.length - 2); - triggerKeydown(searchInput, Key.Left); - triggerKeydown(searchInput, Key.Left); - triggerKeydown(searchInput, Key.Left); - expect(el.scope().$selectMultiple.activeMatchIndex).toBe(0); + scope.selection.selectedMultiple = [scope.people[4], scope.people[5], scope.people[6]]; //Wladimir, Samantha & Nicole + var el = createUiSelectMultiple(); + var searchInput = el.find('.ui-select-search'); - }); + expect(isDropdownOpened(el)).toEqual(false); + triggerKeydown(searchInput, Key.Left); + triggerKeydown(searchInput, Key.Left); + expect(isDropdownOpened(el)).toEqual(false); + expect(el.scope().$selectMultiple.activeMatchIndex).toBe(el.scope().$select.selected.length - 2); + triggerKeydown(searchInput, Key.Left); + triggerKeydown(searchInput, Key.Left); + triggerKeydown(searchInput, Key.Left); + expect(el.scope().$selectMultiple.activeMatchIndex).toBe(0); - it('should decrease $selectMultiple.activeMatchIndex when pressing LEFT key', function() { + }); - scope.selection.selectedMultiple = [scope.people[4], scope.people[5], scope.people[6]]; //Wladimir, Samantha & Nicole - var el = createUiSelectMultiple(); - var searchInput = el.find('.ui-select-search'); + it('should decrease $selectMultiple.activeMatchIndex when pressing LEFT key', function () { - el.scope().$selectMultiple.activeMatchIndex = 3; - triggerKeydown(searchInput, Key.Left); - triggerKeydown(searchInput, Key.Left); - expect(el.scope().$selectMultiple.activeMatchIndex).toBe(1); + scope.selection.selectedMultiple = [scope.people[4], scope.people[5], scope.people[6]]; //Wladimir, Samantha & Nicole + var el = createUiSelectMultiple(); + var searchInput = el.find('.ui-select-search'); - }); + el.scope().$selectMultiple.activeMatchIndex = 3; + triggerKeydown(searchInput, Key.Left); + triggerKeydown(searchInput, Key.Left); + expect(el.scope().$selectMultiple.activeMatchIndex).toBe(1); - it('should increase $selectMultiple.activeMatchIndex when pressing RIGHT key', function() { + }); - scope.selection.selectedMultiple = [scope.people[4], scope.people[5], scope.people[6]]; //Wladimir, Samantha & Nicole - var el = createUiSelectMultiple(); - var searchInput = el.find('.ui-select-search'); + it('should increase $selectMultiple.activeMatchIndex when pressing RIGHT key', function () { - el.scope().$selectMultiple.activeMatchIndex = 0; - triggerKeydown(searchInput, Key.Right); - triggerKeydown(searchInput, Key.Right); - expect(el.scope().$selectMultiple.activeMatchIndex).toBe(2); + scope.selection.selectedMultiple = [scope.people[4], scope.people[5], scope.people[6]]; //Wladimir, Samantha & Nicole + var el = createUiSelectMultiple(); + var searchInput = el.find('.ui-select-search'); - }); + el.scope().$selectMultiple.activeMatchIndex = 0; + triggerKeydown(searchInput, Key.Right); + triggerKeydown(searchInput, Key.Right); + expect(el.scope().$selectMultiple.activeMatchIndex).toBe(2); - it('should open dropdown when pressing DOWN key', function() { + }); - scope.selection.selectedMultiple = [scope.people[4], scope.people[5]]; //Wladimir & Samantha - var el = createUiSelectMultiple(); - var searchInput = el.find('.ui-select-search'); + it('should open dropdown when pressing DOWN key', function () { - expect(isDropdownOpened(el)).toEqual(false); - triggerKeydown(searchInput, Key.Down); - expect(isDropdownOpened(el)).toEqual(true); + scope.selection.selectedMultiple = [scope.people[4], scope.people[5]]; //Wladimir & Samantha + var el = createUiSelectMultiple(); + var searchInput = el.find('.ui-select-search'); - }); + expect(isDropdownOpened(el)).toEqual(false); + triggerKeydown(searchInput, Key.Down); + expect(isDropdownOpened(el)).toEqual(true); - it('should search/open dropdown when writing to search input', function() { + }); - scope.selection.selectedMultiple = [scope.people[5]]; //Wladimir & Samantha - var el = createUiSelectMultiple(); - var searchInput = el.find('.ui-select-search'); + it('should search/open dropdown when writing to search input', function () { - el.scope().$select.search = 'r'; - scope.$digest(); - expect(isDropdownOpened(el)).toEqual(true); + scope.selection.selectedMultiple = [scope.people[5]]; //Wladimir & Samantha + var el = createUiSelectMultiple(); + var searchInput = el.find('.ui-select-search'); - }); + el.scope().$select.search = 'r'; + scope.$digest(); + expect(isDropdownOpened(el)).toEqual(true); - it('should add selected match to selection array', function() { + }); - scope.selection.selectedMultiple = [scope.people[5]]; //Samantha - var el = createUiSelectMultiple(); - var searchInput = el.find('.ui-select-search'); + it('should add selected match to selection array', function () { - clickItem(el, 'Wladimir'); - expect(scope.selection.selectedMultiple).toEqual([scope.people[5], scope.people[4]]); //Samantha & Wladimir + scope.selection.selectedMultiple = [scope.people[5]]; //Samantha + var el = createUiSelectMultiple(); + var searchInput = el.find('.ui-select-search'); - }); + clickItem(el, 'Wladimir'); + expect(scope.selection.selectedMultiple).toEqual([scope.people[5], scope.people[4]]); //Samantha & Wladimir - it('should close dropdown after selecting', function() { + }); - scope.selection.selectedMultiple = [scope.people[5]]; //Samantha - var el = createUiSelectMultiple(); - var searchInput = el.find('.ui-select-search'); + it('should close dropdown after selecting', function () { - expect(isDropdownOpened(el)).toEqual(false); - triggerKeydown(searchInput, Key.Down); - expect(isDropdownOpened(el)).toEqual(true); + scope.selection.selectedMultiple = [scope.people[5]]; //Samantha + var el = createUiSelectMultiple(); + var searchInput = el.find('.ui-select-search'); - clickItem(el, 'Wladimir'); + expect(isDropdownOpened(el)).toEqual(false); + triggerKeydown(searchInput, Key.Down); + expect(isDropdownOpened(el)).toEqual(true); - expect(isDropdownOpened(el)).toEqual(false); + clickItem(el, 'Wladimir'); - }); + expect(isDropdownOpened(el)).toEqual(false); - it('should not close dropdown after selecting if closeOnSelect=false', function() { + }); - scope.selection.selectedMultiple = [scope.people[5]]; //Samantha - var el = createUiSelectMultiple({closeOnSelect: false}); - var searchInput = el.find('.ui-select-search'); + it('should not close dropdown after selecting if closeOnSelect=false', function () { - expect(isDropdownOpened(el)).toEqual(false); - triggerKeydown(searchInput, Key.Down); - expect(isDropdownOpened(el)).toEqual(true); + scope.selection.selectedMultiple = [scope.people[5]]; //Samantha + var el = createUiSelectMultiple({closeOnSelect: false}); + var searchInput = el.find('.ui-select-search'); - clickItem(el, 'Wladimir'); + expect(isDropdownOpened(el)).toEqual(false); + triggerKeydown(searchInput, Key.Down); + expect(isDropdownOpened(el)).toEqual(true); - expect(isDropdownOpened(el)).toEqual(true); + clickItem(el, 'Wladimir'); - }); + expect(isDropdownOpened(el)).toEqual(true); - it('should closes dropdown when pressing ESC key from search input', function() { + }); - scope.selection.selectedMultiple = [scope.people[4], scope.people[5], scope.people[6]]; //Wladimir, Samantha & Nicole - var el = createUiSelectMultiple(); - var searchInput = el.find('.ui-select-search'); + it('should closes dropdown when pressing ESC key from search input', function () { - expect(isDropdownOpened(el)).toEqual(false); - triggerKeydown(searchInput, Key.Down); - expect(isDropdownOpened(el)).toEqual(true); - triggerKeydown(searchInput, Key.Escape); - expect(isDropdownOpened(el)).toEqual(false); + scope.selection.selectedMultiple = [scope.people[4], scope.people[5], scope.people[6]]; //Wladimir, Samantha & Nicole + var el = createUiSelectMultiple(); + var searchInput = el.find('.ui-select-search'); - }); + expect(isDropdownOpened(el)).toEqual(false); + triggerKeydown(searchInput, Key.Down); + expect(isDropdownOpened(el)).toEqual(true); + triggerKeydown(searchInput, Key.Escape); + expect(isDropdownOpened(el)).toEqual(false); - it('should select highlighted match when pressing ENTER key from dropdown', function() { + }); - scope.selection.selectedMultiple = [scope.people[5]]; //Samantha - var el = createUiSelectMultiple(); - var searchInput = el.find('.ui-select-search'); + it('should select highlighted match when pressing ENTER key from dropdown', function () { - triggerKeydown(searchInput, Key.Down); - triggerKeydown(searchInput, Key.Enter); - expect(scope.selection.selectedMultiple.length).toEqual(2); + scope.selection.selectedMultiple = [scope.people[5]]; //Samantha + var el = createUiSelectMultiple(); + var searchInput = el.find('.ui-select-search'); - }); + triggerKeydown(searchInput, Key.Down); + triggerKeydown(searchInput, Key.Enter); + expect(scope.selection.selectedMultiple.length).toEqual(2); - it('should stop the propagation when pressing ENTER key from dropdown', function() { + }); - var el = createUiSelectMultiple(); - var searchInput = el.find('.ui-select-search'); - spyOn(jQuery.Event.prototype, 'preventDefault'); - spyOn(jQuery.Event.prototype, 'stopPropagation'); + it('should stop the propagation when pressing ENTER key from dropdown', function () { - triggerKeydown(searchInput, Key.Down); - triggerKeydown(searchInput, Key.Enter); - expect(jQuery.Event.prototype.preventDefault).toHaveBeenCalled(); - expect(jQuery.Event.prototype.stopPropagation).toHaveBeenCalled(); + var el = createUiSelectMultiple(); + var searchInput = el.find('.ui-select-search'); + spyOn(jQuery.Event.prototype, 'preventDefault'); + spyOn(jQuery.Event.prototype, 'stopPropagation'); - }); + triggerKeydown(searchInput, Key.Down); + triggerKeydown(searchInput, Key.Enter); + expect(jQuery.Event.prototype.preventDefault).toHaveBeenCalled(); + expect(jQuery.Event.prototype.stopPropagation).toHaveBeenCalled(); - it('should stop the propagation when pressing ESC key from dropdown', function() { + }); - var el = createUiSelectMultiple(); - var searchInput = el.find('.ui-select-search'); - spyOn(jQuery.Event.prototype, 'preventDefault'); - spyOn(jQuery.Event.prototype, 'stopPropagation'); + it('should stop the propagation when pressing ESC key from dropdown', function () { - triggerKeydown(searchInput, Key.Down); - triggerKeydown(searchInput, Key.Escape); - expect(jQuery.Event.prototype.preventDefault).toHaveBeenCalled(); - expect(jQuery.Event.prototype.stopPropagation).toHaveBeenCalled(); + var el = createUiSelectMultiple(); + var searchInput = el.find('.ui-select-search'); + spyOn(jQuery.Event.prototype, 'preventDefault'); + spyOn(jQuery.Event.prototype, 'stopPropagation'); - }); + triggerKeydown(searchInput, Key.Down); + triggerKeydown(searchInput, Key.Escape); + expect(jQuery.Event.prototype.preventDefault).toHaveBeenCalled(); + expect(jQuery.Event.prototype.stopPropagation).toHaveBeenCalled(); - it('should increase $select.activeIndex when pressing DOWN key from dropdown', function() { + }); - var el = createUiSelectMultiple(); - var searchInput = el.find('.ui-select-search'); + it('should increase $select.activeIndex when pressing DOWN key from dropdown', function () { - triggerKeydown(searchInput, Key.Down); //Open dropdown + var el = createUiSelectMultiple(); + var searchInput = el.find('.ui-select-search'); - el.scope().$select.activeIndex = 0; - triggerKeydown(searchInput, Key.Down); - triggerKeydown(searchInput, Key.Down); - expect(el.scope().$select.activeIndex).toBe(2); + triggerKeydown(searchInput, Key.Down); //Open dropdown - }); + el.scope().$select.activeIndex = 0; + triggerKeydown(searchInput, Key.Down); + triggerKeydown(searchInput, Key.Down); + expect(el.scope().$select.activeIndex).toBe(2); - it('should decrease $select.activeIndex when pressing UP key from dropdown', function() { + }); - var el = createUiSelectMultiple(); - var searchInput = el.find('.ui-select-search'); + it('should decrease $select.activeIndex when pressing UP key from dropdown', function () { - triggerKeydown(searchInput, Key.Down); //Open dropdown + var el = createUiSelectMultiple(); + var searchInput = el.find('.ui-select-search'); - el.scope().$select.activeIndex = 5; - triggerKeydown(searchInput, Key.Up); - triggerKeydown(searchInput, Key.Up); - expect(el.scope().$select.activeIndex).toBe(3); + triggerKeydown(searchInput, Key.Down); //Open dropdown - }); + el.scope().$select.activeIndex = 5; + triggerKeydown(searchInput, Key.Up); + triggerKeydown(searchInput, Key.Up); + expect(el.scope().$select.activeIndex).toBe(3); - it('should render initial selected items', function() { - scope.selection.selectedMultiple = [scope.people[4], scope.people[5]]; //Wladimir & Samantha - var el = createUiSelectMultiple(); - expect(el.scope().$select.selected.length).toBe(2); - expect(el.find('.ui-select-match-item').length).toBe(2); - }); + }); - it('should parse the items correctly using single property binding', function() { + it('should render initial selected items', function () { + scope.selection.selectedMultiple = [scope.people[4], scope.people[5]]; //Wladimir & Samantha + var el = createUiSelectMultiple(); + expect(el.scope().$select.selected.length).toBe(2); + expect(el.find('.ui-select-match-item').length).toBe(2); + }); - scope.selection.selectedMultiple = ['wladimir@email.com', 'samantha@email.com']; + it('should parse the items correctly using single property binding', function () { - var el = compileTemplate( - ' \ - {{$item.name}} <{{$item.email}}> \ - \ -
\ -
\ -
\ -
' - ); + scope.selection.selectedMultiple = ['wladimir@email.com', 'samantha@email.com']; - expect(el.scope().$select.selected).toEqual([scope.people[4], scope.people[5]]); + var el = compileTemplate( + ' \ + {{$item.name}} <{{$item.email}}> \ + \ +
\ +
\ +
\ +
' + ); - }); + expect(el.scope().$select.selected).toEqual([scope.people[4], scope.people[5]]); - it('should add selected match to selection array using single property binding', function() { + }); - scope.selection.selectedMultiple = ['wladimir@email.com', 'samantha@email.com']; + it('should add selected match to selection array using single property binding', function () { - var el = compileTemplate( - ' \ - {{$item.name}} <{{$item.email}}> \ - \ -
\ -
\ -
\ -
' - ); + scope.selection.selectedMultiple = ['wladimir@email.com', 'samantha@email.com']; - var searchInput = el.find('.ui-select-search'); + var el = compileTemplate( + ' \ + {{$item.name}} <{{$item.email}}> \ + \ +
\ +
\ +
\ +
' + ); - clickItem(el, 'Natasha'); + var searchInput = el.find('.ui-select-search'); - expect(el.scope().$select.selected).toEqual([scope.people[4], scope.people[5], scope.people[7]]); - scope.selection.selectedMultiple = ['wladimir@email.com', 'samantha@email.com', 'natasha@email.com']; + clickItem(el, 'Natasha'); - }); + expect(el.scope().$select.selected).toEqual([scope.people[4], scope.people[5], scope.people[7]]); + scope.selection.selectedMultiple = ['wladimir@email.com', 'samantha@email.com', 'natasha@email.com']; - it('should format view value correctly when using single property binding and refresh function', function () { + }); - scope.selection.selectedMultiple = ['wladimir@email.com', 'samantha@email.com']; + it('should format view value correctly when using single property binding and refresh function', function () { - var el = compileTemplate( - ' \ - {{$item.name}} <{{$item.email}}> \ - \ -
\ -
\ -
\ -
' - ); + scope.selection.selectedMultiple = ['wladimir@email.com', 'samantha@email.com']; - var searchInput = el.find('.ui-select-search'); + var el = compileTemplate( + ' \ + {{$item.name}} <{{$item.email}}> \ + \ +
\ +
\ +
\ +
' + ); - scope.fetchFromServer = function(searching){ + var searchInput = el.find('.ui-select-search'); - if (searching == 'n') - return scope.people; + scope.fetchFromServer = function (searching) { - if (searching == 'o'){ - scope.people = []; //To simulate cases were previously selected item isnt in the list anymore - } + if (searching == 'n') + return scope.people; - }; + if (searching == 'o') { + scope.people = []; //To simulate cases were previously selected item isnt in the list anymore + } - setSearchText(el, 'n'); - clickItem(el, 'Nicole'); + }; - expect(el.find('.ui-select-match-item [uis-transclude-append]:not(.ng-hide)').text()) - .toBe("Wladimir Samantha Nicole "); + setSearchText(el, 'n'); + clickItem(el, 'Nicole'); - setSearchText(el, 'o'); + expect(el.find('.ui-select-match-item [uis-transclude-append]:not(.ng-hide)').text()) + .toBe("Wladimir Samantha Nicole "); - expect(el.find('.ui-select-match-item [uis-transclude-append]:not(.ng-hide)').text()) - .toBe("Wladimir Samantha Nicole "); + setSearchText(el, 'o'); - }); + expect(el.find('.ui-select-match-item [uis-transclude-append]:not(.ng-hide)').text()) + .toBe("Wladimir Samantha Nicole "); - it('should watch changes for $select.selected and update formatted value correctly', function () { + }); - scope.selection.selectedMultiple = ['wladimir@email.com', 'samantha@email.com']; + it('should watch changes for $select.selected and update formatted value correctly', function () { - var el = compileTemplate( - ' \ - {{$item.name}} <{{$item.email}}> \ - \ -
\ -
\ -
\ -
\ - ' - ); + scope.selection.selectedMultiple = ['wladimir@email.com', 'samantha@email.com']; - var el2 = compileTemplate(''); + var el = compileTemplate( + ' \ + {{$item.name}} <{{$item.email}}> \ + \ +
\ +
\ +
\ +
\ + ' + ); - expect(el.find('.ui-select-match-item [uis-transclude-append]:not(.ng-hide)').text()) - .toBe("Wladimir Samantha "); + var el2 = compileTemplate(''); - clickItem(el, 'Nicole'); + expect(el.find('.ui-select-match-item [uis-transclude-append]:not(.ng-hide)').text()) + .toBe("Wladimir Samantha "); - expect(el.find('.ui-select-match-item [uis-transclude-append]:not(.ng-hide)').text()) - .toBe("Wladimir Samantha Nicole "); + clickItem(el, 'Nicole'); - expect(scope.selection.selectedMultiple.length).toBe(3); + expect(el.find('.ui-select-match-item [uis-transclude-append]:not(.ng-hide)').text()) + .toBe("Wladimir Samantha Nicole "); - }); + expect(scope.selection.selectedMultiple.length).toBe(3); - it('should ensure the multiple selection limit is respected', function () { + }); - scope.selection.selectedMultiple = ['wladimir@email.com']; + it('should ensure the multiple selection limit is respected', function () { - var el = compileTemplate( - ' \ - {{$item.name}} <{{$item.email}}> \ - \ -
\ -
\ -
\ -
\ - ' - ); + scope.selection.selectedMultiple = ['wladimir@email.com']; - var el2 = compileTemplate(''); + var el = compileTemplate( + ' \ + {{$item.name}} <{{$item.email}}> \ + \ +
\ +
\ +
\ +
\ + ' + ); - expect(el.find('.ui-select-match-item [uis-transclude-append]:not(.ng-hide)').text()) - .toBe("Wladimir "); + var el2 = compileTemplate(''); - clickItem(el, 'Samantha'); - expect(el.find('.ui-select-match-item [uis-transclude-append]:not(.ng-hide)').text()) - .toBe("Wladimir Samantha "); + expect(el.find('.ui-select-match-item [uis-transclude-append]:not(.ng-hide)').text()) + .toBe("Wladimir "); - clickItem(el, 'Nicole'); + clickItem(el, 'Samantha'); + expect(el.find('.ui-select-match-item [uis-transclude-append]:not(.ng-hide)').text()) + .toBe("Wladimir Samantha "); - expect(el.find('.ui-select-match-item [uis-transclude-append]:not(.ng-hide)').text()) - .toBe("Wladimir Samantha "); + clickItem(el, 'Nicole'); - expect(scope.selection.selectedMultiple.length).toBe(2); + expect(el.find('.ui-select-match-item [uis-transclude-append]:not(.ng-hide)').text()) + .toBe("Wladimir Samantha "); - }); + expect(scope.selection.selectedMultiple.length).toBe(2); - it('should change viewvalue only once when updating modelvalue', function () { + }); - scope.selection.selectedMultiple = ['wladimir@email.com', 'samantha@email.com']; + it('should change viewvalue only once when updating modelvalue', function () { + scope.selection.selectedMultiple = ['wladimir@email.com', 'samantha@email.com']; - var el = compileTemplate( - ' \ - {{$item.name}} <{{$item.email}}> \ - \ -
\ -
\ -
\ -
\ - ' - ); + var el = compileTemplate( + ' \ + {{$item.name}} <{{$item.email}}> \ + \ +
\ +
\ +
\ +
\ + ' + ); - scope.counter = 0; - scope.onlyOnce = function(){ - scope.counter++; - }; + scope.counter = 0; + scope.onlyOnce = function () { + scope.counter++; + }; - clickItem(el, 'Nicole'); + clickItem(el, 'Nicole'); - expect(scope.counter).toBe(1); + expect(scope.counter).toBe(1); + }); - }); + it('should run $formatters when changing model directly', function () { + scope.selection.selectedMultiple = ['wladimir@email.com', 'samantha@email.com']; - it('should run $formatters when changing model directly', function () { + var el = compileTemplate( + ' \ + {{$item.name}} <{{$item.email}}> \ + \ +
\ +
\ +
\ +
\ + ' + ); - scope.selection.selectedMultiple = ['wladimir@email.com', 'samantha@email.com']; + // var el2 = compileTemplate(''); - var el = compileTemplate( - ' \ - {{$item.name}} <{{$item.email}}> \ - \ -
\ -
\ -
\ -
\ - ' - ); + scope.selection.selectedMultiple.push("nicole@email.com"); - // var el2 = compileTemplate(''); + scope.$digest(); + scope.$digest(); //2nd $digest needed when using angular 1.3.0-rc.1+, might be related with the fact that the value is an array - scope.selection.selectedMultiple.push("nicole@email.com"); + expect(el.find('.ui-select-match-item [uis-transclude-append]:not(.ng-hide)').text()) + .toBe("Wladimir Samantha Nicole "); - scope.$digest(); - scope.$digest(); //2nd $digest needed when using angular 1.3.0-rc.1+, might be related with the fact that the value is an array + }); - expect(el.find('.ui-select-match-item [uis-transclude-append]:not(.ng-hide)').text()) - .toBe("Wladimir Samantha Nicole "); + it('should support multiple="multiple" attribute', function () { + var el = compileTemplate( + ' \ + {{$item.name}} <{{$item.email}}> \ + \ +
\ +
\ +
\ +
\ + ' + ); + + expect(el.scope().$select.multiple).toBe(true); + }); - }); + it('should allow paste tag from clipboard', function () { + var el = createUiSelectMultiple({tagging: true, taggingTokens: ",|ENTER"}); - it('should support multiple="multiple" attribute', function() { + el.scope().$select.beforeTagging = function (item) { + return { + name: item, + email: item + '@email.com', + group: 'Foo', + age: 12 + }; + }; - var el = compileTemplate( - ' \ - {{$item.name}} <{{$item.email}}> \ - \ -
\ -
\ -
\ -
\ - ' - ); + clickMatch(el); + triggerPaste(el.find('input'), 'tag1'); - expect(el.scope().$select.multiple).toBe(true); - }); + expect($(el).scope().$select.selected.length).toBe(1); + }); - it('should allow paste tag from clipboard', function() { - scope.taggingFunc = function (name) { - return { - name: name, - email: name + '@email.com', - group: 'Foo', - age: 12 - }; - }; - - var el = createUiSelectMultiple({tagging: 'taggingFunc', taggingTokens: ",|ENTER"}); - clickMatch(el); - triggerPaste(el.find('input'), 'tag1'); - - expect($(el).scope().$select.selected.length).toBe(1); + it('should allow paste multiple tags', function () { + var el = createUiSelectMultiple({tagging: true, taggingTokens: ",|ENTER"}); + + el.scope().$select.beforeTagging = function (item) { + return { + name: item, + email: item + '@email.com', + group: 'Foo', + age: 12 + }; + }; + clickMatch(el); + triggerPaste(el.find('input'), ',tag1,tag2,tag3,,tag5,'); + + expect($(el).scope().$select.selected.length).toBe(4); + }); }); - it('should allow paste multiple tags', function() { - scope.taggingFunc = function (name) { - return { - name: name, - email: name + '@email.com', - group: 'Foo', - age: 12 - }; - }; - - var el = createUiSelectMultiple({tagging: 'taggingFunc', taggingTokens: ",|ENTER"}); - clickMatch(el); - triggerPaste(el.find('input'), ',tag1,tag2,tag3,,tag5,'); + describe('default configuration via uiSelectConfig', function () { - expect($(el).scope().$select.selected.length).toBe(5); - }); - }); - - describe('default configuration via uiSelectConfig', function() { + describe('searchEnabled option', function () { - describe('searchEnabled option', function() { + function setupWithoutAttr() { + return compileTemplate( + ' \ + {{$select.selected.name}} \ + \ +
\ +
\ +
\ +
' + ); + } - function setupWithoutAttr(){ - return compileTemplate( - ' \ + function setupWithAttr(searchEnabled) { + return compileTemplate( + ' \ {{$select.selected.name}} \ \
\
\
\
' - ); - } + ); + } - function setupWithAttr(searchEnabled){ - return compileTemplate( - ' \ - {{$select.selected.name}} \ - \ -
\ -
\ -
\ -
' - ); - } + it('should be true by default', function () { + var el = setupWithoutAttr(); + expect(el.scope().$select.searchEnabled).toBe(true); + }); - it('should be true by default', function(){ - var el = setupWithoutAttr(); - expect(el.scope().$select.searchEnabled).toBe(true); - }); + it('should disable search if default set to false', function () { + var uiSelectConfig = $injector.get('uiSelectConfig'); + uiSelectConfig.searchEnabled = false; - it('should disable search if default set to false', function(){ - var uiSelectConfig = $injector.get('uiSelectConfig'); - uiSelectConfig.searchEnabled = false; + var el = setupWithoutAttr(); + expect(el.scope().$select.searchEnabled).not.toBe(true); + }); - var el = setupWithoutAttr(); - expect(el.scope().$select.searchEnabled).not.toBe(true); - }); + it('should be overridden by inline option search-enabled=true', function () { + var uiSelectConfig = $injector.get('uiSelectConfig'); + uiSelectConfig.searchEnabled = false; - it('should be overridden by inline option search-enabled=true', function(){ - var uiSelectConfig = $injector.get('uiSelectConfig'); - uiSelectConfig.searchEnabled = false; + var el = setupWithAttr(true); + expect(el.scope().$select.searchEnabled).toBe(true); + }); - var el = setupWithAttr(true); - expect(el.scope().$select.searchEnabled).toBe(true); - }); + it('should be overridden by inline option search-enabled=false', function () { + var uiSelectConfig = $injector.get('uiSelectConfig'); + uiSelectConfig.searchEnabled = true; - it('should be overridden by inline option search-enabled=false', function(){ - var uiSelectConfig = $injector.get('uiSelectConfig'); - uiSelectConfig.searchEnabled = true; + var el = setupWithAttr(false); + expect(el.scope().$select.searchEnabled).not.toBe(true); + }); + }); - var el = setupWithAttr(false); - expect(el.scope().$select.searchEnabled).not.toBe(true); - }); }); - }); - - describe('accessibility', function() { - it('should have baseTitle in scope', function() { - expect(createUiSelect().scope().$select.baseTitle).toBe('Select box'); - expect(createUiSelect().scope().$select.focusserTitle).toBe('Select box focus'); - expect(createUiSelect({ title: 'Choose a person' }).scope().$select.baseTitle).toBe('Choose a person'); - expect(createUiSelect({ title: 'Choose a person' }).scope().$select.focusserTitle).toBe('Choose a person focus'); - }); + describe('accessibility', function () { + it('should have baseTitle in scope', function () { + expect(createUiSelect().scope().$select.baseTitle).toBe('Select box'); + expect(createUiSelect().scope().$select.focusserTitle).toBe('Select box focus'); + expect(createUiSelect({title: 'Choose a person'}).scope().$select.baseTitle).toBe('Choose a person'); + expect(createUiSelect({title: 'Choose a person'}).scope().$select.focusserTitle).toBe('Choose a person focus'); + }); - it('should have aria-label on all input and button elements', function() { - checkTheme(); - checkTheme('select2'); - checkTheme('selectize'); - checkTheme('bootstrap'); - - function checkTheme(theme) { - var el = createUiSelect({ theme: theme}); - checkElements(el.find('input')); - checkElements(el.find('button')); - - function checkElements(els) { - for (var i = 0; i < els.length; i++) { - expect(els[i].attributes['aria-label']).toBeTruthy(); - } - } - } + it('should have aria-label on all input and button elements', function () { + checkTheme(); + checkTheme('select2'); + checkTheme('selectize'); + checkTheme('bootstrap'); + + function checkTheme(theme) { + var el = createUiSelect({theme: theme}); + checkElements(el.find('input')); + checkElements(el.find('button')); + + function checkElements(els) { + for (var i = 0; i < els.length; i++) { + expect(els[i].attributes['aria-label']).toBeTruthy(); + } + } + } + }); }); - }); - - describe('select with the append to body option', function() { - var body; - beforeEach(inject(function($document) { - body = $document.find('body')[0]; - })); + describe('select with the append to body option', function () { + var body; - it('should only be moved to the body when the appendToBody option is true', function() { - var el = createUiSelect({appendToBody: false}); - openDropdown(el); - expect(el.parent()[0]).not.toBe(body); - }); + beforeEach(inject(function ($document) { + body = $document.find('body')[0]; + })); - it('should be moved to the body when the appendToBody is true in uiSelectConfig', inject(function(uiSelectConfig) { - uiSelectConfig.appendToBody = true; - var el = createUiSelect(); - openDropdown(el); - expect(el.parent()[0]).toBe(body); - })); + it('should only be moved to the body when the appendToBody option is true', function () { + var el = createUiSelect({appendToBody: false}); + openDropdown(el); + expect(el.parent()[0]).not.toBe(body); + }); - it('should be moved to the body when opened', function() { - var el = createUiSelect({appendToBody: true}); - openDropdown(el); - expect(el.parent()[0]).toBe(body); - closeDropdown(el); - expect(el.parent()[0]).not.toBe(body); - }); + it('should be moved to the body when the appendToBody is true in uiSelectConfig', + inject(function (uiSelectConfig) { + uiSelectConfig.appendToBody = true; + var el = createUiSelect(); + openDropdown(el); + expect(el.parent()[0]).toBe(body); + })); + + it('should be moved to the body when opened', function () { + var el = createUiSelect({appendToBody: true}); + openDropdown(el); + expect(el.parent()[0]).toBe(body); + closeDropdown(el); + expect(el.parent()[0]).not.toBe(body); + }); - it('should remove itself from the body when the scope is destroyed', function() { - var el = createUiSelect({appendToBody: true}); - openDropdown(el); - expect(el.parent()[0]).toBe(body); - el.scope().$destroy(); - expect(el.parent()[0]).not.toBe(body); - }); + it('should remove itself from the body when the scope is destroyed', function () { + var el = createUiSelect({appendToBody: true}); + openDropdown(el); + expect(el.parent()[0]).toBe(body); + el.scope().$destroy(); + expect(el.parent()[0]).not.toBe(body); + }); - it('should have specific position and dimensions', function() { - var el = createUiSelect({appendToBody: true}); - var originalPosition = el.css('position'); - var originalTop = el.css('top'); - var originalLeft = el.css('left'); - var originalWidth = el.css('width'); - openDropdown(el); - expect(el.css('position')).toBe('absolute'); - expect(el.css('top')).toBe('100px'); - expect(el.css('left')).toBe('200px'); - expect(el.css('width')).toBe('300px'); - closeDropdown(el); - expect(el.css('position')).toBe(originalPosition); - expect(el.css('top')).toBe(originalTop); - expect(el.css('left')).toBe(originalLeft); - expect(el.css('width')).toBe(originalWidth); + it('should have specific position and dimensions', function () { + var el = createUiSelect({appendToBody: true}); + var originalPosition = el.css('position'); + var originalTop = el.css('top'); + var originalLeft = el.css('left'); + var originalWidth = el.css('width'); + openDropdown(el); + expect(el.css('position')).toBe('absolute'); + expect(el.css('top')).toBe('100px'); + expect(el.css('left')).toBe('200px'); + expect(el.css('width')).toBe('300px'); + closeDropdown(el); + expect(el.css('position')).toBe(originalPosition); + expect(el.css('top')).toBe(originalTop); + expect(el.css('left')).toBe(originalLeft); + expect(el.css('width')).toBe(originalWidth); + }); }); - }); - });