Search code examples
angularjsangularjs-directiveisolated-scope

why $scope.info binding late on ng-change in custom directive


tag:

<grid-filter varible="info.M_id" on-change="searchMember()">
</grid-filter>

directive

app.directive("gridFilter", function () {
return {      
scope: {
varible: "=",
onChange: "&"
},
template: [
'<div class="input-append input-group">',
'<input class="form-control border-right-0" ng-change="onChange();"   no-special-char  class="form-control" ng-model="varible"    />',
'<div class="input-group-append">',
' <span class="input-group-text"><i class="fa-filter fa" aria-hidden="true"></i></span>',
' </div>',
' </div>'].join("")
};
})

Controller

$scope.searchMember = function () {      
    var data = $scope.info;
    Request.GetTabledata("SearchMemberData", data, null, $scope, true);
}

When typing on textbox for example hello. The controller doesn't bind $scope.info.M_id first time on change. Suppose that I input h , e then $scope.info.M_id binds only h


Solution

  • One approach is to use one-way ("<") binding for the input, and use the on-change event for output:

    app.directive("gridFilter", function () {
        return {      
                scope: {
                varible: "<",
                onChange: "&"
            },
            template: `
              <div class="input-append input-group">
                <input class="form-control border-right-0"
                       ng-change="onChange({$event: varible})"
                       no-special-char  class="form-control" ng-model="varible"  />
                <div class="input-group-append">
                  <span class="input-group-text">
                    <i class="fa-filter fa" aria-hidden="true"></i>
                  </span>
                </div>
              </div>
            `
        };
    })
    

    Usage:

    <grid-filter  varible="info.M_id"
                  on-change="info.M_id=$event; searchMember($event)">
    </grid-filter>
    
    $scope.searchMember = function (data) {      
        console.log(data);
    }
    

    This will avoid the digest cycle delay inherent to two-way ("=") binding.

    It has the added benefit of making future migration to Angular 2+ easier as Angular 2+ does not have two-way ("=") binding.