Coder Social home page Coder Social logo

ui-autocomplete's Introduction

ui-autocomplete directive v0.6.1

Intend to replace Select2!

AngularJS Autocomplete Wrapper for the jQuery UI Autocomplete Widget - v1.11.2

Requirements

Testing

Installation options

bower install ui-autocomplete --save

Usage

Load the script files in your application like this:

<script type="text/javascript" src="javascript/jquery/jquery.js"></script>
<script type="text/javascript" src="javascript/jquery-ui/jquery-ui.js"></script>
<script type="text/javascript" src="javascript/angular/angular.js"></script>
<script type="text/javascript" src="javascript/angular-ui/autocomplete.js"></script>

Add the autocomplete module as a dependency to your application module:

var myAppModule = angular.module('MyApp', ['ui.autocomplete'])

Apply the directive to your input elements:

<input type="text" ng-model="modelObj" ui-autocomplete="myOption">

ui-autocomplete option

Options

All the options must be passed through the directive. There have added 5 options besides official options:

  • html If true, you can use html string or DOM object in sourceData.label
  • focusOpen If true, the suggestion menu auto open with all source data when element focus
  • onlySelectValid If true, element value must be selected from suggestion menu, otherwise set validity of 'onlyselect' to false
  • groupLabel html string or DOM object, it is used to group suggestion result, it can't be seleted
  • outHeight number, it is used to adjust suggestion menu' css style "max-height", and you would set css "overflow-y", see demo.

You can config options like this:

myAppModule.controller('MyController', function ($scope, $compile) {
    /* config object */
    $scope.myOption = {
        options: {
            html: true,
            focusOpen: true,
            onlySelectValid: true,
            source: function (request, response) {
                var data = [
                        "Asp",
                        "BASIC",
                        "C",
                        "C++",
                        "Clojure",
                        "COBOL",
                        "ColdFusion",
                        "Erlang",
                        "Fortran",
                        "Groovy",
                        "Haskell",
                        "Java",
                        "JavaScript",
                        "Lisp",
                        "Perl",
                        "PHP",
                        "Python",
                        "Ruby",
                        "Scala",
                        "Scheme"
                ];
                data = $scope.myOption.methods.filter(data, request.term);

                if (!data.length) {
                    data.push({
                        label: 'not found',
                        value: ''
                    });
                }
                // add "Add Language" button to autocomplete menu bottom
                data.push({
                    label: $compile('<a class="btn btn-link ui-menu-add" ng-click="addLanguage()">Add Language</a>')($scope),
                    value: ''
                });
                response(data);
            }
        },
        methods: {}
    };
});

// in html template
<input type="text" ng-model="modelObj" ui-autocomplete="myOption">

All official options Here.

Methods

Autocomplete methods will be added to $scope.myOption.methods after Autocomplete initialized. There also have added 2 methods:

  • filter filter html labels besides official methods
  • clean use to empty ngModal object

You can invoke methods like this:

$scope.myOption.methods.search('term');

data = $scope.myOption.methods.filter(data, request.term);

$scope.myOption.methods.clean();

All official methods Here.

Events

Autocomplete events will be emitted just like official events triggered.

You can bind events to initialize the autocomplete like this:

$scope.myOption.events = {
    change: function( event, ui ) {
        // do something
    },
    close: function( event, ui ) {
        // do something
    },
    //...other event handlers
};

All official events Here.

Working with ng-model

The ui-autocomplete directive plays nicely with ng-model.

Not only primitive type ngModel, you can also use object type ngModel! There must have a property 'value' in object type ngModel.

A object type ngModel like this:

modelObj = {
    id: 'ae15581f-d8e1-48e8-9d6d-b5989ae77ce5',
    name: 'JavaScript',
    value: 'JavaScript',
    // some other property
};

Documentation for the autocomplete

The autocomplete works alongside of all the documentation represented here

ui-autocomplete's People

Contributors

fabiowitt avatar felipenbrito avatar gsto avatar mark0978 avatar zensh avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar

ui-autocomplete's Issues

Filter not working when data pulled from ajax request

options: {
html: true,
focusOpen: false,
onlySelectValid: true,
minLength: 1,

        source: function(request, response) {
            
        $.ajax({
        url: "some url",
        dataType: "json",
        data: request,
        success: function(data) {
            
            response(data);   

        

        
      }

this is how i had used this widget but unable to filter options in response data

No instance method ?

Autocomplete widget has an instance method but it is missing from this implementation.

I wanted to raise select event of autocomplete directive from my controller. What I was thinking is to get an instance then call instance.select().
Thanks

Can't set "appendTo" property to null

From the documentation for appendTo:

When the value is null, the parents of the input field will be checked for a class of ui-front. If an element with the ui-front class is found, the menu will be appended to that element. Regardless of the value, if no element is found, the menu will be appended to the body.

It looks like this line of code is making this impossible:

options.appendTo = options.appendTo || element.parents('.ng-view')[0] || element.parents('[ng-view]')[0] || null;

Testing?

Would be great if you could give an example of how to test this. Currently using Jasmine and have this, but the sleeps slow down our tests.

it('should update the thing on select', function () {
var newText = 'Option Text';
input('authorInput').enter('option text');
sleep(1);
element('ul.ui-autocomplete li:nth-child(1) a').click();
sleep(1);
expect(element('#thing .value').text()).toBe(newText);
});

Can't use ng-model with empty object since 1.3.x update

Since 1.3.x update, ui-autocomplete component can't use empty ng-model object.

This can be seen here : http://jsfiddle.net/ar1bqtat/3/

Error is :
TypeError: Cannot read property 'value' of undefined at Object.fn (autocomplete-0.5.7.js:137:44) at Scope.$digest (https://code.angularjs.org/1.3.4/angular.js:14129:29) at Scope.$apply (https://code.angularjs.org/1.3.4/angular.js:14391:24) at bootstrapApply (https://code.angularjs.org/1.3.4/angular.js:1437:15) at Object.invoke (https://code.angularjs.org/1.3.4/angular.js:4138:17) at doBootstrap (https://code.angularjs.org/1.3.4/angular.js:1435:14) at bootstrap (https://code.angularjs.org/1.3.4/angular.js:1455:12) at angularInit (https://code.angularjs.org/1.3.4/angular.js:1349:5) at HTMLDocument.<anonymous> (https://code.angularjs.org/1.3.4/angular.js:25910:5) at j (http://code.jquery.com/jquery-1.11.1.min.js:2:27244)

Notes to merge into angular-ui

I've also briefly looked at your ui-autocomplete. I would have to create a new repo for the project and give you ownership of it, which I'm not entirely against. However, it again runs into certain design concerns that I stated regarding the ui-sortable module.

The extremely large size of the code is a concern because it means a tremendous amount of hand-holding is being done simply to port existing behavior over in a new, custom way. Instead, it would be better to leave certain aspects up to the developer (such as my comments on ui-event) to reduce the amount of code in the module and thereby reduce the amount of code that will need maintenance and upkeep.

If the original plugin has bugs, patch the original plugin, not this implementation. If the original plugin requires a specific data format, let the user do the work of standardizing their data. Do NOT spend time trying to hand-hold users for n-variations when simply giving them a few simple and powerful variations is enough to allow them to do everything.

If you think you'd be willing to simplify this module down so that it has all the necessary functionality with only patches that are required to make it behave at 100% status-quo for non-angular then we can look into merging it in.

P.S.

None of this is intended to dissuade you or a personal attack. I personally have become burned out from trying to maintain too many plugins and have grown accustomed to projects that try to satisfy every stupid request and only end up holding the hands for people who are too lazy to do a basic amount of expected work and in the end create massive amount of maintance, expectations for new features and scope creep, and MASSIVE unnecessary file-sizes.

Stick to simple and powerful and give people the tools to do almost everything. If they want complex edge cases, create demos that show them how to do this instead of adding new options, methods, features, etc.

It is also not our responsibility to add new features to an existing project / plugin via the wrapper. If people want new features, patch the original project so that everyone can benefit, or if it's too impractacle, the user should probably look for a new alternative project.

ui-autocomplete change pristine state on form load

Hi,

I'm using $pristine and $dirty form indicators to determine if there's some changes in the form and let the user know that he is about to leave the page with unsaved values.

When i apply ui-autocomplete on some input, it appears that the form pristine state is automatically changed to false (dirty = true) even if there is no changes in the form : after loading the form, state i already diry but user hasn't interact yet. Then if the user want to leave the page, a confirm message appears because my app has detected that the form state is dirty...

I made some research and i figure out that in ui-automplete, there is a call to angular method setViewValue ("ctrl.$setViewValue(ngModel.value);"). This method change the form pristine state.

Would you have any hack / fix for this problem ?

Local variable 'selectItem' interferes with typing in new values

Note: this occurs with the following options: focusOpen=false, minLength > 0, onlySelect=false

Steps to reproduce:

  1. bind an autocomplete to a string value in your model, provide 'source'
  2. focus the autocomplete, type enough letters to provide a drop-down from source
  3. choose one of the items in the drop-down
  4. focus the autocomplete again. Highlight the whole text.
  5. Type in a new value that does cause any suggestion (does not appear in source)
    (it's important that what you type does NOT cause the source to return any values,
    hence the drop-down never opens)
  6. Press TAB to blur the control
  7. the control re-renders with the last selected source item instead of what you typed

Cause:
The local variable 'selectItem' only gets set to null in the "open" event, so if that event never happens, it stays at its last-selected value.
When the "change" event fires after the user types a new value, the code looks at the 'selectItem' variable instead of the "ui" argument passed to the change handler.

Solution:
I added a line to the "change" handler "selectItem = ui" which solved the problem for me. I wonder though, since that information is passed in as an argument, whether the "selectItem" local variable is really needed at all. I don't see any other references in the code that make use of it outside the "change" handler.

Hope this helps!
Rob

Implementation error

Hi,
Thank you for this library. I am willing to use this library for one of my projects. But during its implementation I am getting numerous console error:
TypeError: element.parents is not a function
TypeError: element.autocomplete is not a function

I use gulp, and have downloaded the autocomplete.js, and used it to bundle autocomplete.js.
I am only using <script> tag to include my gulp generated js files.

my html file :

<textarea class="form-control " ng-model="companyChat.new_comment" marked id="comment"
name="comment" placeholder="Type a message" rows="2" ui-autocomplete="mentionUser">
</textarea>

my controller :

myApp.controller('myController', ['$scope', '$stateParams', '$state', '$timeout', 'authService', '_', 'localStorageService',
    function ($scope, $stateParams, $state, $timeout, authService, _, localStorageService) {
    $scope.mentionUser = {
    options: {
      html: true,
      focusOpen: true,
      onlySelectValid: true,
      source: function (request, response) {
        var data = [
                "Asp",
                "BASIC",
                "C",
                "C++"
        ];
        data = $scope.mentionUser.methods.filter(data, request.term);

        if (!data.length) {
          data.push({
            label: 'not found',
            value: ''
          });
        }
        data.push({
          label: $compile('<a class="btn btn-link ui-menu-add" ng-click="addLanguage()">Add Language</a>')($scope),
          value: ''
        });
        response(data);
      }
    },
    methods: {}
  };
  return $scope;
}]);

any insights will really be of great help @zensh .
Thanks

template for items ?

Any example of using an html template for the items ?

edit: nevermind, I found it.

[enhancement] Add missing bower.json.

Hey, maintainer(s) of zensh/ui-autocomplete!

We at VersionEye are working hard to keep up the quality of the bower's registry.

We just finished our initial analysis of the quality of the Bower.io registry:

7530 - registered packages, 224 of them doesnt exists anymore;

We analysed 7306 existing packages and 1070 of them don't have bower.json on the master branch ( that's where a Bower client pulls a data ).

Sadly, your library zensh/ui-autocomplete is one of them.

Can you spare 15 minutes to help us to make Bower better?

Just add a new file bower.json and change attributes.

{
  "name": "zensh/ui-autocomplete",
  "version": "1.0.0",
  "main": "path/to/main.css",
  "description": "please add it",
  "license": "Eclipse",
  "ignore": [
    ".jshintrc",
    "**/*.txt"
  ],
  "dependencies": {
    "<dependency_name>": "<semantic_version>",
    "<dependency_name>": "<Local_folder>",
    "<dependency_name>": "<package>"
  },
  "devDependencies": {
    "<test-framework-name>": "<version>"
  }
}

Read more about bower.json on the official spefication and nodejs semver library has great examples of proper versioning.

NB! Please validate your bower.json with jsonlint before commiting your updates.

Thank you!

Timo,
twitter: @versioneye
email: [email protected]
VersionEye - no more legacy software!

IE8 compatibility

Hi.
First - great job, nice plugin.

I think, It would be nice to add IE8 compatibility. I made a small investigation and found the only problem is with this line of code

valueMethod = element.val.bind(element)
is there any chance to add this feature?

Thanks
Bart

Severe bug in IE

Hi,

This directive has a sever bug with IE. Like, it does not work in mouse click. When I use normal keyboard for selection, it works, but when I click on a menu item, it does not work. Instead of assigning the whole value to the textbox, it is again triggering the selection.

Video.zip

Please check and let us know. Thanks.

Example for use of "groupLabel"

Hi Yan,

thanks for your plugin. :)

Could you provide an example how to use the option groupLabel please.
How must the data be defined? How can I style the groups?

Thanks in advance. Greetings,
Stefan

Returning false in event handlers does not work

$scope.autocompleteConfig = {
        options: {
            minLength: 1,
            source: [{'label': 'French', 'value':'fr', alternateValueForDisplay: 'FR'}]
        }, 
       events: {
           select: function(event, ui) {
             angular.element(event.target).val(ui.item.alternateValueForDisplay);
             return false;
           }
     }
    };

Returning false is necessary to override the default behavior of "select" event handler of jQuery autocomplete plugin. But, this false return value cannot be read by jQuery due to the way events are bound by this directive (since these events are intercepted by the directive)

$digest already in progress

Hi,

There is a little issue with $digest and $apply management. When I write in the field, the console point out an error "$digest already in progress" referenced to the line 179.

This issue can be solved by setting the line under a timeout
$timeout(function() {
scope.$apply(function (){changeNgModel();});
})

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.