jrDeveloper jrDeveloper - 26 days ago 11
AngularJS Question

Updating the view of a screen in AngularJS

Hey—I’m working on an angular 1.6 app, and I’ve come across an issue I’m not quite sure how to resolve. Here’s a brief discussion of the set up. The page is a form with thirty questions. There is a lot of conditional logic from the client that goes as follows: if user selects “Yes” on Q1 then show them Q2-4, if “No” on Q1, then skip to Q5. This repeats itself in the thirty question form.

I’ve come across the following scenario—what if the user selects “Yes” on Q1, answers Q2-4 and then realizes Q1 should really be “No”.

So my question is: 1) how do I clear the models? and 2) how do I update the view? So that if they decide, third time around, that Q1 should in fact be yes, Q2-Q4 are unchecked/clear/blank.

For 1) I just wrote a simple “clearAll method as follows:

function clearAll(arr){
arr.forEach(function(element){
if(element!==undefined){
element = null;
}
});
}


This clears the models but doesn’t update the view. How do I update the view so that Q2-4 are clear/empty/blank?

The idea I had is to update the view, so

$scope.$watch( myModel, function(val){
//set to null or delete?
}


But I cannot generalize this so it is flexible enough to accept an array. Any advice would be appreciated. Thanks.

Answer Source

For your particular problem I would use ui-router and resolve different states based on a question, i.e. state.questions and take different parameters like if you have url /questions as your base intro page (maybe weclome to questions or something), you would have /questions/1 and it would be 1st question /questions/2 would be second etc... Then keep one list of objects on some simple service i.e.:

let questions = [];

which will persist throughout the app, later to be filled with some objects like:

{ 
q1: {
  answers: [1,2,3]
},
{
q2: {
  answers: [1,3]
}

You can always clear it after you are done with it or push new answer. Also you can check for particular answer before even loading the state, and this will give you great flexibility what you actually want.

well for ugly solution your watch maybe could work if you add watch group and timeout:

$scope.$watchGroup(arrayOfModels, (newVal, oldVal)=>{
  if(newVal) {
   // now do something you want with that models
   // if they don't apply, try $timeout(()=> $scope.$apply());
  }
})