Sam
Sam

Reputation: 14586

angularjs - need help for delayed search directive

fiddle here: http://jsfiddle.net/graphicsxp/QA4Fa/2/

I'm triying to create a directive for searching. Basically it's just a textbox that detects user input and after a 1 second delay, a search method is called.

It's not working yet and I'm having two issues.

First, why is the filterCriteria not updated in the span when user inputs text ?

Second, the watch on filterCriteria is triggered at page loading but not when text is entered in the textbox.

<div ng-app="myApp" ng-controller="myController">   
  <delayed-search ng-model="filterCriteria"></delayed-search>
   <span>filter criteria is : {{filterCriteria}}</span>
</div>

angular.module('myApp', []).directive("delayedSearch", ['$timeout', function($timeout) {
return {
    restrict: "E",
    template: '<input type="text"  />',
    scope: {
        filterCriteria : '='
    },
    link: function (scope, element, attrs) {

    },
    controller: function ($scope) {
        var timer = false;
        $scope.$watch('filterCriteria', function () {
            if (timer) {
                $timeout.cancel(timer);
            }
            timer = $timeout(function () {
                alert('timeout expired');
            }, 1000)
        });
    }
}
}]).controller('myController', function($scope){  });

Upvotes: 1

Views: 2639

Answers (2)

Ganaraj
Ganaraj

Reputation: 26841

You should NOT use a controller with a directive ( until you understand it ! ) .

A controller in a directive is meant for directive to directive communication (I wish they had named it something else!).

@Langdon got it right.. But here is another implementation of the same. Note that in both the answer's the controller is missing.

http://jsfiddle.net/QA4Fa/4/

Upvotes: 3

Langdon
Langdon

Reputation: 20073

First, why is the filterCriteria not updated in the span when user inputs text ?

Your scope is wrong, it should be scope: { ngModel : '=' },, and your template should be template: '<input type="text" ng-model="ngModel" />.

Second, the watch on filterCriteria is triggered at page loading but not when text is entered in the textbox.

Same as the first problem, you should be watching ngModel.

Also, you don't need the overhead of a controller for this, you can get away with just using the link function. Here's an updated fiddle: http://jsfiddle.net/QA4Fa/3/

Upvotes: 2

Related Questions