-2

I am trying to use the jQuery auto-complete widget by using the class attribute of an element which is dynamically created using ng-repeat. So far it's not working for dynamically created elements.

What I have tried so far is:

When I apply it on static created input box, it works properly.

angularcontroller.js

$('.auto').autocomplete({       
      source: function(request, response) {
         $.ajax({
            url: "/auto",
            type: "GET",
            data: request,  // request is the value of search input
            success: function (data) {
              // console.log("data>>>"+JSON.stringify(data));
              // Map response values to fiedl label and value
               response($.map(data, function (el) {
                  return {
                     value: el.name,
                    label: el.name
                  };
                  }));
               }
            });
         }      
  })

html file

<tr ng-repeat="rowContent in dataRows" style="text-align:center">
   <td>
     <input type="text" width="80px">
   </td>
</tr>
Rohan Büchner
  • 5,333
  • 4
  • 62
  • 106

1 Answers1

1

As a general rule, all DOM manipulations should be part of directive. You should be accessing the element in the directive's link function and then set autocomplete on it

app.directive("myautocomplete", function(){
   return{
    restrict: 'A',
    scope: {
        suggestions: "="
    },
    link: function(scope, element, attrs){
        scope.$watch("suggestions", function(newV){
            if(newV && newV.length > 0)
            {
                $(element).autocomplete({
                    source: scope.suggestions
                });
            }
        });
    }
   };
});

"suggestions" is array of words that you want to pass for autocomplete to show.

html

<div>
   <input type="text" myautocomplete suggestions="suggestions" /></label>
</div>

Here "myautocomplete" is directive name and "suggestions" is passed in Scope with two-way binding.

Yashika Garg
  • 2,346
  • 2
  • 15
  • 17