0

I am trying to pre select checkboxes in angular 1.4 by comparing values in two arrays but for some reason my logic keeps omitting the first item in the array. My model that binds to checkboxlist is like below:

 $scope.weekDays = [{
    name: "Monday",
    value: false,
}, {
    name: "Tuesday",
    value: false,
}, {
    name: "Wednesday",
    value: false,
}, {
    name: "Thursday",
    value: false,
}, {
    name: "Friday",
    value: false,
}, ];

The value I receive from my db is

'Monday,Tuesday,Thurdsay'

I then split the value that I receive from my db into array and if the days name match in both the arrays I set the value as true which checks the checkbox.

 var PrefDays = 'Monday,Tuesday,Thursday';
 var selected_pref_days = new Array();

 selected_pref_days = PrefDays.split(',');

 for(var i = 0; i < selected_pref_days.length; i++) {
    console.log(selected_pref_days[i]);
     angular.forEach($scope.weekDays, function (day) {
       if (selected_pref_days[i] == day.name) {
           day.value = true;
        }
      })
  }

I expect to get $scope.weekDays to be like below:

$scope.weekDays = [{
name: "Monday",
value: true,
}, {
name: "Tuesday",
value: true,
}, {
name: "Wednesday",
value: false,
}, {
name: "Thursday",
value: true,
}, {
name: "Friday",
value: false,
}, ];

Instead I always get the first value as "false". Could someone please assist me ? Thank you

3
  • Have you tried putting a debugger statement or breakpoint in the code to step through it? Commented Feb 7, 2018 at 14:11
  • I think the value you receive from db is different than what you have provided here as I tested your code with the values that you have provided above and result is same as expected result. plnkr.co/edit/FznHH9V6FeTFdfjw1BMZ?p=preview Commented Feb 7, 2018 at 14:23
  • Maybe somewhere else in the code you alter the first value? Commented Feb 7, 2018 at 14:36

1 Answer 1

1

I can't find the issue but here is a simplest solution (and also easy to test and debug) that works for me. Sorry that I can not clarify your situation but at least you can keep coding on your final logic

$scope.weekDays = $scope.weekDays.map(d => {
    d.value = selected_pref_days.indexOf(d.name) != -1; 
    return d;
})
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.