Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Here's a quick little reusable directive that seems to do what you're looking to do. I've simply called it <code>checkList</code>. It updates the array when the checkboxes change, and updates the checkboxes when the array changes.</p> <pre class="lang-javascript prettyprint-override"><code>app.directive('checkList', function() { return { scope: { list: '=checkList', value: '@' }, link: function(scope, elem, attrs) { var handler = function(setup) { var checked = elem.prop('checked'); var index = scope.list.indexOf(scope.value); if (checked &amp;&amp; index == -1) { if (setup) elem.prop('checked', false); else scope.list.push(scope.value); } else if (!checked &amp;&amp; index != -1) { if (setup) elem.prop('checked', true); else scope.list.splice(index, 1); } }; var setupHandler = handler.bind(null, true); var changeHandler = handler.bind(null, false); elem.bind('change', function() { scope.$apply(changeHandler); }); scope.$watch('list', setupHandler, true); } }; }); </code></pre> <p>Here's a controller and a view that shows how you might go about using it.</p> <pre class="lang-html prettyprint-override"><code>&lt;div ng-app="myApp" ng-controller='MainController'&gt; &lt;span ng-repeat="fruit in fruits"&gt; &lt;input type='checkbox' value="{{fruit}}" check-list='checked_fruits'&gt; {{fruit}}&lt;br /&gt; &lt;/span&gt; &lt;div&gt;The following fruits are checked: {{checked_fruits | json}}&lt;/div&gt; &lt;div&gt;Add fruit to the array manually: &lt;button ng-repeat="fruit in fruits" ng-click='addFruit(fruit)'&gt;{{fruit}}&lt;/button&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <pre class="lang-javascript prettyprint-override"><code>app.controller('MainController', function($scope) { $scope.fruits = ['apple', 'orange', 'pear', 'naartjie']; $scope.checked_fruits = ['apple', 'pear']; $scope.addFruit = function(fruit) { if ($scope.checked_fruits.indexOf(fruit) != -1) return; $scope.checked_fruits.push(fruit); }; }); </code></pre> <p>(The buttons demonstrate that changing the array will also update the checkboxes.)</p> <p>Finally, here is an example of the directive in action on Plunker: <a href="http://plnkr.co/edit/3YNLsyoG4PIBW6Kj7dRK?p=preview">http://plnkr.co/edit/3YNLsyoG4PIBW6Kj7dRK?p=preview</a></p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload