1

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){  });
Sam
  • 13,934
  • 26
  • 108
  • 194
  • As an alternate approach, take a look at this answer, which provides a directive that allows you to put a delay on ngChange: http://stackoverflow.com/questions/21121460/angular-directive-encapsulating-a-delay-for-ng-change/21420441#21420441. Use ngChange to call the search method with an ngDelay of 1s. – Doug Jan 29 '14 at 03:46

2 Answers2

3
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/

ganaraj
  • 26,841
  • 6
  • 63
  • 59
  • nice one ! and thanks for the advice, it's very useful (i'm still learning angular). I'll mark Langdon's reply as answer though as he was first to reply. Thanks for helping. – Sam Apr 23 '13 at 15:06
2

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/

Langdon
  • 19,875
  • 18
  • 88
  • 107