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 ArrayCommentedMar 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 arrayCommentedMar 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...
    – Brant
    CommentedMar 10, 2017 at 16:29
  • Please create a fiddle.CommentedMar 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); }); } 
3
  • 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'}]''CommentedMar 10, 2017 at 16:38
  • 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.
    – Brant
    CommentedMar 10, 2017 at 18:03
  • See my edit for the function to handle conversion to your data structure.
    – Brant
    CommentedMar 10, 2017 at 18:06
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
  • That's what I said in my answer above.
    – Brant
    CommentedMar 10, 2017 at 18:06

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.