I'm trying to implement functionality for checking multiple items in a list of checkboxes. I am using a Map to store the data and its selected/unselected state.
List<String> fruits = [
{'fruit': 'apple', 'selected': true},
{'fruit': 'banana', 'selected': true},
{'fruit': 'kiwi', 'selected': false}
];
The checkboxes display initially with the checked/unchecked status correctly rendered, but when I toggle a checkbox's checked status, the fruits map does not update. How can I correctly create a two-way binding here?
Here is my .dart file:
import 'package:angular/angular.dart';
@NgDirective(
selector: '[my-controller]',
publishAs: 'ctrl'
)
class MyController {
List<String> fruits = [
{'fruit': 'apple', 'selected': true},
{'fruit': 'banana', 'selected': true},
{'fruit': 'kiwi', 'selected': false}
];
}
main() {
ngBootstrap(module: new Module()..type(MyController));
}
And here is the view markup:
<!DOCTYPE html>
<html ng-app>
<body>
<div my-controller>
<ul>
<li ng-repeat="item in ctrl.fruits">
{{item['fruit']}}
<input type="checkbox" ng-model="item['selected']" />
</li>
</ul>
</div>
<!-- THIS DOES NOT UPDATE WHEN THE CHECKBOXES ARE TOGGLED -->
{{ctrl.fruits}}
<script type="application/dart" src="main.dart"></script>
<script type="text/javascript" src="packages/browser/dart.js"></script>
</body>
</html>
The reason why it does not update is because ctrl.fruits is being watch on reference. Since the fruits list reference never changes the binding never changes either.
Here is a simple fix:
{{ctrl.fruits | json}}
By running it through a filter it forces the object to be JSONified in each digest.
Unfortunately there is no easy way to deep watch an object, since the computational complexity would be potentially unbounded.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With