Checkbox list breaks, why? And optimal Angularjs way? -


i don't understand this, suspect i'm doing wrong, or non-angularjs way.

i have checkbox list inside ng-repeat. controller loads list json. pretty straightforward really. i'm using directive (car-select) on each of resulting checkboxes. directive calls function inside main $scope (selectbrand()). cycles through selected checkboxes, , if checked==true, add $scope.brand. i've added textbox $scope.brand fills it, , i've set required fires built in validation e.g:

html:

<div ng-repeat="v in viewmodel">   <label class="checkbox">     <input type="checkbox" ng-model="v.c" ng-checked="v.c" />{{v.n}}   </label> </div> <input type="text" name="brands" ng-model="brands" car-select required/> <br> 

js:

  $scope.selectbrand = function() {     var selectedbrands = [];     angular.foreach($scope.viewmodel, function(v){        if (v.c)         selectedbrands.push(v.v);     })     if (selectedbrands.length > 0)       $scope.brands = selectedbrands;     else       $scope.brands = null;   } 

directive:

app.directive('carselect', function() {   return function(scope, element) {     element.bind('change', function() {       scope.selectbrand();     })   } }); 

here's weird part don't understand. took while figure out particular line making whole thing work. if add following in page, works great. if remove it, whole thing breaks. why?!

<div>{{selectbrand()}}</div> 

it's whole thing doesn't bind unless above called in html. it's called in directive, , i've tried putting call inside clickbutton() function, breaks. either way, live update of textbox seems fail if above removed. i'd love explanation of how i'm doing wrong , how fix :)

plunker: http://plnkr.co/edit/4qiskcq7yyh678ylsttf?p=preview

ok, create fork ;-)

update variable data checked

your model :

{"cars":   [     {"v":"m","n":"mini","c":false},     {"v":"c","n":"corvette","c":true},     {"v":"b","n":"bmw","c":true},     {"v":"l","n":"lamborghini","c":true},     {"v":"f","n":"ferrari","c":false}   ] } 

you want checked :

$scope.brands = $filter('filter')($scope.viewmodel, {c: true}); 

when model change want update variable use watch in controller

$scope.$watch('viewmodel', function(newval, oldval){                         if (oldval != newval)                         {                          $scope.brands = $filter('filter')($scope.viewmodel, {c: true});                             }                             },true                         );   }); 

see http://plnkr.co/edit/pnabre?p=preview


Comments