0

Here are my checkboxes :

<input type="checkbox" ng-model="data.lang[0]" id="FR" ng-true-value="'FR'" ng-false-value="''"  checked/>FR
<input type="checkbox" ng-model="data.lang[1]" id="NL" ng-true-value="'NL'" ng-false-value="''" />NL
<input type="checkbox" ng-model="data.lang[2]" id="EN" ng-true-value="'EN'" ng-false-value="''" />EN

I'd like to check a language and update my model 'data.lang'

But i have a problem :

If second checkbox is checked i have :
   [null,"NL"]
If the third is checked i have :
   [null,null,'EN']

What i need to have :

If second checkbox is checked :
    ['NL']
If second and third are checked :
    ['NL','EN']
If all are checked :
    ['FR','NL','EN']

I don't know how to update my model like i want could you help me? Thanks

4
  • Invoke a function everytime theres a change in these checkbox. Clue : Use push and splice on the Array Commented Mar 10, 2017 at 16:25
  • I tried with a function in ng-change but because i use data.lang[n] as model it bind on the nth position in the array Commented Mar 10, 2017 at 16:28
  • Make data.lang an array of objects with { val: 'en', checked: boolean } and change your inputs to one with an ng-repeat... Commented Mar 10, 2017 at 16:29
  • Please create a fiddle. Commented Mar 10, 2017 at 16:34

2 Answers 2

2

Change your data structure and ng-repeat your input similar to the below.

$scope.langs = [
  {
    val: 'en',
    checked: false
  }
]

<input type="checkbox" ng-repeat="lang in langs" ng-model="lang.checked">{{lang.val}}</input>

Then do something like:

$scope.sendMyData() {
  $scope.langs.forEach(function(item) {
    if (item.checked) $scope.myData.push(item.value);
  });
}
Sign up to request clarification or add additional context in comments.

3 Comments

i need $scope.langs is equal to ['FR','NL','EN'] if all checbkoxes are checked, not [{val:'FR', checked: 'true'},{val:'NL', checked: 'true'},{val:'EN', checked: 'true'}]''
Before you ship that data off to wherever it is going to go, make an array from the checked fields of each object. Your current data model is going to cause you more harm than good.
See my edit for the function to handle conversion to your data structure.
0

This is because your data.lang[] has length 3. i.e. if one value will there then other will be null.

Try this with ng-repeat so it will work.

1 Comment

That's what I said in my answer above.

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.