0

I have a loop on twig, on which I'm trying to listen for changes on a checkbox, by appending an object to the index of the loop every time I check the check box.

{% for key, item in items %}
<input type="checkbox" ng-true-value="{{ item.id }}" ng-false-value="'NO'" ng-model="myCheckBox.{{ key }}">

And this is my angular controller:

$scope.myCheckBox = {}

$scope.$watchCollection('myCheckBox', function(){
    console.log($scope.myCheckBox);
})

when I dump myCheckBox, every time i check the the check box, it's appending normally to my object and looks like this {"0":"1","1":"20"} (first item being the index, and second time being my item id). But, using the $watch or $watchCollection is not working, when i listen on these changes. I have already tried ($watch, true) and it isn't working, also isn't $watchCollection supposed to be the fix for that!

brokleyscoding
  • 187
  • 3
  • 12
  • Use the [`ng-change`](https://docs.angularjs.org/api/ng/directive/ngChange) directive on the input element. It is more efficient than using a watcher. – georgeawg Dec 18 '18 at 15:25
  • yeah, I have already tried ng-change before i considered a watcher, but still not working... – brokleyscoding Dec 18 '18 at 16:41
  • is `ng-model="myCheckBox.{{ key }}"` even a valid syntax? Shouldn't it be `ng-model="myCheckBox[key]"`? – Alon Eitan Dec 18 '18 at 16:44
  • yes, it's a valid syntax in twig! I already stated that I dump it and it gets me right results. – brokleyscoding Dec 18 '18 at 17:44
  • I'm surprised that the `ng-model` didn't generate a parse error. It usually does when mixing interpolation into `ng-model` expressions. In any case, it is bad practice. – georgeawg Dec 18 '18 at 17:46
  • This is not a duplicate for the question stated. I already use ($watch, true) but it's not working... Also, $watchCollection, should be the fix ($watch, true). – brokleyscoding Dec 18 '18 at 17:48
  • I deleted my answer, my last suggestion is to inspect the DOM after it was rendered (Using the developer tools: Inspect Element), also go to the `console` tab and check for js errors. Good luck! – Alon Eitan Dec 18 '18 at 18:19
  • Unfortunately no, there are no errors. Thank you for the suggestion though. – brokleyscoding Dec 18 '18 at 18:24

0 Answers0