Question

I am having a form page which is used for both add and edit form . So at the time of adding data into form , i need to check input data is duplicated or not, so i created a directive which will check with the data base weather data is existed or not.

<input name="divId" type="text" class="form-control fL w250"   ng-model="divisionData.DivisionID"  ng-disabled="Disabled()" unique-divid required /></div>

at the time of adding new data its works fine . but at the time of edit also using the same form so the unique-divid directive is running. I don't want this to happen in edit page

.directive('uniqueDivid', function($http) {
  var toId;
  return {
    restrict: 'A',
    require: 'ngModel',
    link: function(scope, elem, attr, ctrl) { 
     scope.$watch(attr.ngModel, function(value) {
        if(toId) clearTimeout(toId);
        toId = setTimeout(function(){
          console.log(value);
            $http({
            method  : 'POST',
            url     : 'http://testurl',
            data    : $.param({'DivisionID' : value}), 
            headers : { 'Content-Type': 'application/x-www-form-urlencoded' }  
        })
            .success(function(data) {
                console.log(data);
                if(data.status == 'success'){
                    ctrl.$setValidity('uniqueDivid', true);
                }else if(data.status == 'fail'){
                    ctrl.$setValidity('uniqueDivid', false);
                }
                if (!data.success) {
                } else {
                }
            });


        }, 200);
      })
    }
  }
});

Please suggest a solution either disable the directive or stop the scope.$watch function at the time of edit .

Was it helpful?

Solution

Can you add additional attribute to the input field indicating type of form action (create/edit) it is serving?

For example:

<input name="divId" type="text" class="form-control fL w250" ng-model="divisionData.DivisionID" ng-disabled="Disabled()" unique-divid form-action="edit" required />

If action type matches the one you want to ignore, just return from linking function.

link: function(scope, elem, attr, ctrl) { 
  if (attr.formAction === "edit") return;
  ..
}

In case you do not want to modify template, what is the indication in controller or scope that could be used to distinguish between new and existing divisionData? You could use that property as a flag to return from the unique-divid directive:

link: function(scope, elem, attr, ctrl) { 
  if (!scope.divisionData.isNew) return;
  ..
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top