1

I am trying for the past 5 hours without success... Here is the code..

In View:

<input type="text" ng-model="foo" auto-complete/>Foo = {{foo}}

In controller:

    myapp.directive('autoComplete', function(autoCompleteDataService) {
    return {
        restrict: 'A',
        link: function(scope, elem, attr, ctrl) {
            elem.autocomplete({
                source: autoCompleteDataService.getSource(), //from your service
                select: function( event, ui ) {
                    scope.foo= ui.item.label;
                    scope.$apply;
                },
                change:function (event, ui) {
                    if (ui.item === null) {
                        scope.foo = null;
                    }
                },
                minLength: 2
            });
        }
    };
});

    myapp.factory('autoCompleteDataService', [function() {
    return {
        getSource: function() {
            return ['apples', 'oranges', 'bananas'];
        }
    }
}]);

Here is the issue...

The selected item is getting into the input box, but foo variable next to input box is not updating.

Where is the mistake.

Please suggest...

6
  • 2
    Try changing scope.$apply; to scope.$apply(); Commented Sep 25, 2013 at 10:36
  • Wow.. It worked...I might have come to SOF earlier.. Thanks CodeHater.. Commented Sep 25, 2013 at 10:42
  • How to mark this comment as answer? Commented Sep 25, 2013 at 10:44
  • I have added my comment as answer below Commented Sep 25, 2013 at 10:45
  • 1
    And better if you change that two lines to: scope.$apply(function() { scope.foo = ui.item.label; }); so the scope.foo assign will be executed inside angular context. That way angular can manage any error. Commented Sep 25, 2013 at 10:45

1 Answer 1

2

Change

scope.$apply; 

to

scope.$apply(function(){
    scope.foo= ui.item.label;
});
Sign up to request clarification or add additional context in comments.

1 Comment

This is a similar approach calling a function defined on the controller scope. It also covers an approach to set the value and label (name,id pair). ozkary.com/2015/09/angularjs-autocomplete-directive-with.html

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.