Home > Software design >  Both ng-model and ng-change on input alter the $scope state - which one takes priority
Both ng-model and ng-change on input alter the $scope state - which one takes priority

Time:03-29

I have the following array of objects

$scope.client.systemAssessments = [
    {
        id: 0,
        name: 'Name 1',
        paused: false
    },
    {
        id: 1,
        name: 'Name 2',
        paused: false
    },
]

I then render some HTML for each assessment:

<div ng-repeat="systemAssessment in client.systemAssessments">
    <span >
        <input ng-model="systemAssessment.paused" name="{{systemAssessment.name}}" ng-change="onPauseResumeAssessmentHandler(systemAssessment)" type="checkbox" toggle-btn on-type="success">
    </span>
</div>

And my ng-change function looks like this:

  $scope.onPauseResumeAssessmentHandler = function onPauseResumeAssessmentHandler(systemAssessment) {
    //const { id, paused } = systemAssessment;
    //const clientId = $scope.client.clientId;
    console.log(systemAssignedAssessment);

    try {
      throw new Error('ERROR');
      //AssessmentsService.pauseResumeAssessment(clientId ,id, !paused);
    } catch (error) {
      $scope.client.systemAssessments[0].paused = false;
      console.log($scope.client.systemAssessments);
    }
  };

Now since my input checkbox is binded to pausedAssessment.paused, if I check it, the paused property becomes true and the checkbox gets checked, however, I only want it to become checked if AssessmentsService.pauseResumeAssessment(clientId ,id, !paused); does not fail as it's a POST request.

For example, if the checkbox was unchecked and I clicked it, I'd want it to check only if the POST request goes through and for it to either stay unchecked, or to uncheck itself if the POST request fails.

As you can see in my code snippet, I tried using a try-catch block and then unchecking the first checkbox if the POST request throws an error, however, when I log the $scope.client.systemAssessments in the catch, it shows that the first assessment's paused property is still set to true, even though you can see that I set it to false.

I assume this happens because of a weird interaction between ng-model and ng-change ( maybe ng-model overwrites the changes I do in ng-change )

CodePudding user response:

Do things right. When unchecked checkbox is clicked, its gonna be checked -- do NOT fight against that. But after it is checked, u can uncheck it:

... ng-change:
if (smth.paused) {
    try {
      throw new Error('ERROR');
    } catch (error) {
      $timeout(() => { // Can not and should not be done immediately
          smth.paused = false;
      })
    }
}
  • Related