Skip to content

Commit

Permalink
Rename the directive
Browse files Browse the repository at this point in the history
  • Loading branch information
ghiden committed Mar 27, 2014
1 parent 9170705 commit 61bba59
Show file tree
Hide file tree
Showing 15 changed files with 326 additions and 330 deletions.
5 changes: 2 additions & 3 deletions Gruntfile.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@ module.exports = function (grunt) {
// Lint & run unit tests in Karma
// Just running `$ grunt watch` will only lint your code; to run tests
// on watch, use `$ grunt watch:karma` to start a Karma server first
files: ['src/select2.js', 'test/select2Spec.js'],
tasks: ['jshint', 'karma:unit:run']
}
},
Expand All @@ -37,8 +36,8 @@ module.exports = function (grunt) {
jshint: {
all:[
'gruntFile.js',
'angucomplete.js',
'test/**/*Spec.js'
'angucomplete-alt.js',
'test/**/*.spec.js'
],
options: {
jshintrc: '.jshintrc'
Expand Down
60 changes: 30 additions & 30 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
angucomplete-extra
angucomplete-alt
============

A simple but powerful AngularJS directive that allows you to quickly create autocomplete boxes that pull data either from a server or local variable.
This is a fork of Daryl Rowland's angucomplete (https://github.com/darylrowland/angucomplete) with a bit of tweaks here and there.

To see a demo go here: http://ghiden.github.io/angucomplete-extra
To see a demo go here: http://ghiden.github.io/angucomplete-alt

###Key Features
* Show just a title, a title and a description or a title, description and image in your autocomplete list
Expand All @@ -16,23 +16,23 @@ To see a demo go here: http://ghiden.github.io/angucomplete-extra
* Clear on selection: when you select an item, input field is cleared.

### Getting Started
Download the code, and include the angucomplete.js file in your page. Then add the angucomplete module to your Angular App file, e.g.
Download the code, and include the angucomplete-alt.js file in your page. Then add the angucomplete-alt module to your Angular App file, e.g.
```html
var app = angular.module('app', ["angucomplete"]);
var app = angular.module('app', ["angucomplete-alt"]);
```

### Local Usage

```html
<angucomplete id="ex1"
placeholder="Search countries"
<angucomplete-alt id="ex1"
place-holder="Search countries"
pause="100"
selectedobject="selectedCountry"
localdata="countries"
searchfields="name"
titlefield="name"
selected-object="selectedCountry"
local-data="countries"
search-fields="name"
title-field="name"
minlength="1"
inputclass="form-control form-control-small"/>
input-class="form-control form-control-small"/>
```

### Remote Usage
Expand All @@ -41,13 +41,13 @@ var app = angular.module('app', ["angucomplete"]);
<angucomplete id="members"
placeholder="Search members"
pause="400"
selectedobject="testObj"
url="http://myserver.com/api/user/find?s="
datafield="results"
titlefield="firstName,surname"
descriptionfield="email"
imagefield="profilePic"
inputclass="form-control form-control-small"/>
selected-object="testObj"
remote-url="http://myserver.com/api/user/find?s="
remote-url-data-field="results"
title-field="firstName,surname"
description-field="email"
image-field="profilePic"
input-class="form-control form-control-small"/>
```

### Description of attributes
Expand All @@ -56,16 +56,16 @@ var app = angular.module('app', ["angucomplete"]);
| id | A unique ID for the field | Yes | members |
| placeholder | Placeholder text for the search field | No | Search members |
| pause | The time to wait (in milliseconds) before searching when the user enters new characters | No | 400 |
| selectedObject | Where to store the selected object in your model/controller (like ng-model) | Yes | myObject |
| url | The remote URL to hit to query for results in JSON. angucomplete will automatically append the search string on the end of this, so it must be a GET request | No | http://myserver.com/api/users/find?searchstr= |
| datafield | The name of the field in the JSON object returned back that holds the Array of objects to be used for the autocomplete list. | No | results |
| titlefield | The name of the field in the JSON objects returned back that should be used for displaying the title in the autocomplete list. Note, if you want to combine fields together, you can comma separate them here (e.g. for a first and last name combined) | Yes | firstName,lastName |
| descriptionfield | The name of the field in the JSON objects returned back that should be used for displaying the description in the autocomplete list | No | twitterUsername |
| imagefield | The name of the field in the JSON objects returned back that should be used for displaying an image in the autocomplete list | No | pic |
| selected-object | Where to store the selected object in your model/controller (like ng-model) | Yes | myObject |
| remote-url | The remote URL to hit to query for results in JSON. angucomplete will automatically append the search string on the end of this, so it must be a GET request | No | http://myserver.com/api/users/find?searchstr= |
| remote-url-data-field | The name of the field in the JSON object returned back that holds the Array of objects to be used for the autocomplete list. | No | results |
| title-field | The name of the field in the JSON objects returned back that should be used for displaying the title in the autocomplete list. Note, if you want to combine fields together, you can comma separate them here (e.g. for a first and last name combined) | Yes | firstName,lastName |
| description-field | The name of the field in the JSON objects returned back that should be used for displaying the description in the autocomplete list | No | twitterUsername |
| image-field | The name of the field in the JSON objects returned back that should be used for displaying an image in the autocomplete list | No | pic |
| minlength | The minimum length of string required before searching | No | 3 |
| inputclass | The classes to use for styling the input box | No | form-control |
| localdata | The local data variable to use from your controller. Should be an array of objects | No | countriesList |
| searchfields | The fields from your local data to search on (comma separate them) | No | title,description |
| dataformatfn | A function that takes a query string and returns parameter(s) for GET. It should take the query string as argument and returns a key-value object.| No | Suppose if you need to send a query keyword and a timestamp to search API, you can write a function like this in the parent scope. $scope.dataFormatFn = function(str) { return {q: str, timestamp: +new Date()}; } |
| clearselected | To clear out input field upon selecting an item, set this attribute to true. | No | true |
| input-class | The classes to use for styling the input box | No | form-control |
| local-data | The local data variable to use from your controller. Should be an array of objects | No | countriesList |
| search-fields | The fields from your local data to search on (comma separate them) | No | title,description |
| remote-url-request-formatter | A function that takes a query string and returns parameter(s) for GET. It should take the query string as argument and returns a key-value object.| No | Suppose if you need to send a query keyword and a timestamp to search API, you can write a function like this in the parent scope. $scope.dataFormatFn = function(str) { return {q: str, timestamp: +new Date()}; } |
| clear-selected | To clear out input field upon selecting an item, set this attribute to true. | No | true |

File renamed without changes.
252 changes: 252 additions & 0 deletions angucomplete-alt.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,252 @@
/**
* angucomplete-extra
* Autocomplete directive for AngularJS
* This is a fork of Daryl Rowland's angucomplete with some extra features.
* By Hidenari Nozaki
*/
'use strict';

angular.module('angucomplete-alt', [] ).directive('angucompleteAlt', ['$parse', '$http', '$sce', '$timeout', function ($parse, $http, $sce, $timeout) {
var KEY_DW = 40,
KEY_UP = 38,
KEY_ES = 27,
KEY_EN = 13,
KEY_BS = 8,
MIN_LENGTH = 3,
PAUSE = 500;

return {
restrict: 'EA',
scope: {
selectedObject: '=',
localData: '=',
remoteUrlRequestFormatter: '=',
id: '@',
placeholder: '@',
remoteUrl: '@',
remoteUrlDataField: '@',
titleField: '@',
descriptionField: '@',
imageField: '@',
inputClass: '@',
pause: '@',
searchFields: '@',
minlength: '@',
matchClass: '@',
clearSelected: '@'
},
template: '<div class="angucomplete-holder"><input id="{{id}}_value" ng-model="searchStr" type="text" placeholder="{{placeholder}}" class="{{inputClass}}"/><div id="{{id}}_dropdown" class="angucomplete-dropdown" ng-if="showDropdown"><div class="angucomplete-searching" ng-show="searching">Searching...</div><div class="angucomplete-searching" ng-show="!searching && (!results || results.length == 0)">No results found</div><div class="angucomplete-row" ng-repeat="result in results" ng-click="selectResult(result)" ng-mouseover="hoverRow()" ng-class="{\'angucomplete-selected-row\': $index == currentIndex}"><div ng-if="imageField" class="angucomplete-image-holder"><img ng-if="result.image && result.image != \'\'" ng-src="{{result.image}}" class="angucomplete-image"/><div ng-if="!result.image && result.image != \'\'" class="angucomplete-image-default"></div></div><div class="angucomplete-title" ng-if="matchClass" ng-bind-html="result.title"></div><div class="angucomplete-title" ng-if="!matchClass">{{ result.title }}</div><div ng-if="result.description && result.description != \'\'" class="angucomplete-description">{{result.description}}</div></div></div></div>',
link: function(scope, elem, attrs) {
var isNewSearchNeeded, inputField, minlength = MIN_LENGTH, searchTimer = null, lastSearchTerm = null;

scope.currentIndex = null;
scope.searching = false;
scope.searchStr = null;

if (scope.minlength && scope.minlength !== '') {
minlength = scope.minlength;
}

if (!scope.pause) {
scope.pause = PAUSE;
}

if (!scope.clearSelected) {
scope.clearSelected = false;
}

isNewSearchNeeded = function(newTerm, oldTerm) {
return newTerm.length >= minlength && newTerm !== oldTerm;
};

scope.processResults = function(responseData, str) {
var titleFields, titleCode, i, t, description, image, text, re, strPart;

if (responseData && responseData.length > 0) {
scope.results = [];

titleFields = [];
if (scope.titleField && scope.titleField !== '') {
titleFields = scope.titleField.split(',');
}

for (i = 0; i < responseData.length; i++) {
// Get title variables
titleCode = [];

for (t = 0; t < titleFields.length; t++) {
titleCode.push(responseData[i][titleFields[t]]);
}

description = '';
if (scope.descriptionField) {
description = responseData[i][scope.descriptionField];
}

image = '';
if (scope.imageField) {
image = responseData[i][scope.imageField];
}

text = titleCode.join(' ');
if (scope.matchClass) {
re = new RegExp(str, 'i');
strPart = text.match(re)[0];
text = $sce.trustAsHtml(text.replace(re, '<span class="'+ scope.matchClass +'">'+ strPart +'</span>'));
}

scope.results[scope.results.length] = {
title: text,
description: description,
image: image,
originalObject: responseData[i]
};

}


} else {
scope.results = [];
}
};

scope.searchTimerComplete = function(str) {
// Begin the search
var searchFields, matches, i, match, s, params;

if (str.length >= minlength) {
if (scope.localData) {
searchFields = scope.searchFields.split(',');

matches = [];

for (i = 0; i < scope.localData.length; i++) {
match = false;

for (s = 0; s < searchFields.length; s++) {
match = match || (scope.localData[i][searchFields[s]].toLowerCase().indexOf(str.toLowerCase()) >= 0);
}

if (match) {
matches[matches.length] = scope.localData[i];
}
}

scope.searching = false;
scope.processResults(matches, str);

} else if (scope.remoteUrlRequestFormatter) {
params = scope.remoteUrlRequestFormatter(str);
$http.get(scope.remoteUrl, {params: params}).
success(function(responseData, status, headers, config) {
scope.searching = false;
scope.processResults(responseData[scope.remoteUrlDataField], str);
}).
error(function(data, status, headers, config) {
console.log('error');
});

} else {
$http.get(scope.remoteUrl + str, {}).
success(function(responseData, status, headers, config) {
scope.searching = false;
scope.processResults(responseData[scope.remoteUrlDataField], str);
}).
error(function(data, status, headers, config) {
console.log('error');
});
}
}

};

scope.hoverRow = function(index) {
scope.currentIndex = index;
};

scope.keyPressed = function(event) {
if (!(event.which === KEY_UP || event.which === KEY_DW || event.which === KEY_EN)) {
if (!scope.searchStr || scope.searchStr === '') {
scope.showDropdown = false;
lastSearchTerm = null;
} else if (isNewSearchNeeded(scope.searchStr, lastSearchTerm)) {
lastSearchTerm = scope.searchStr;
scope.showDropdown = true;
scope.currentIndex = -1;
scope.results = [];

if (searchTimer) {
$timeout.cancel(searchTimer);
}

scope.searching = true;

searchTimer = $timeout(function() {
scope.searchTimerComplete(scope.searchStr);
}, scope.pause);
}
} else {
event.preventDefault();
}
};

scope.selectResult = function(result) {
if (scope.matchClass) {
result.title = result.title.toString().replace(/(<([^>]+)>)/ig, '');
}

if (scope.clearSelected) {
scope.searchStr = null;
}
else {
scope.searchStr = lastSearchTerm = result.title;
}
scope.selectedObject = result;
scope.showDropdown = false;
scope.results = [];
};

inputField = elem.find('input');

inputField.on('keyup', scope.keyPressed);

elem.on('keyup', function (event) {
if(event.which === KEY_DW && scope.results) {
if ((scope.currentIndex + 1) < scope.results.length) {
scope.$apply(function() {
scope.currentIndex ++;
});
event.preventDefault();
}

} else if(event.which === KEY_UP) {
if (scope.currentIndex >= 1) {
scope.currentIndex --;
scope.$apply();
event.preventDefault();
}

} else if (event.which === KEY_EN && scope.results) {
if (scope.currentIndex >= 0 && scope.currentIndex < scope.results.length) {
scope.selectResult(scope.results[scope.currentIndex]);
scope.$apply();
event.preventDefault();
} else {
scope.results = [];
scope.$apply();
event.preventDefault();
}

} else if (event.which === KEY_ES) {
scope.results = [];
scope.showDropdown = false;
scope.$apply();
} else if (event.which === KEY_BS) {
scope.selectedObject = null;
scope.$apply();
}
});
}
};
}]);

Loading

0 comments on commit 61bba59

Please sign in to comment.