AngularJs doesn't bind ng-checked with ng-model [duplicate]
Asked Answered
O

1

2

I have googled this and found out that people had this issue, but I haven't found any solution.

So this is my code


%section(ng-controller="UserCtrl" ng-init="user_genres=#{preferred_genres}")
    %ul
         %li(ng:repeat="genre in preferred_genres")
            %input(type = "checkbox" ng:model="preferred_genres[genre]" id="genre-{{$index + 1}}" ng-checked="user_genres['{{genre}}']")
            %label{:for => "genre-{{$index + 1}}"} {{genre}}

For example if some of the checkboxes are checked due to ng-checked expression is true and on page render. And I didn't actually click the checkbox it again. When it comes to the controller, the scope seems to ignore the one that has been checked because of ng-checked. How do I make them sync nicely?

Ourself answered 9/1, 2013 at 0:27 Comment(1)
Weird I asked this question before the duplicated one. hmmOurself
F
3

I'm not certain I understand what the real problem is, but see if this fiddle is what you want. (I obtained a list of preferred_genres from your other post.)

The controller scope property preferred_genres is being updated based on the checkbox state:

<li ng-repeat="(genre, checked) in preferred_genres">
  <input type="checkbox" ng-model="preferred_genres[genre]"
   id="genre-{{$index + 1}}">

As @dnc253 mentioned in your other post, you probably don't need ng-checked since each item has its own ng-model.

Fordo answered 9/1, 2013 at 4:25 Comment(1)
Also if @Ourself whants to save original list of 'user_genres' got from server (e.g. reset to original checked), he can add to controller: $scope.preferred_genres = angular.copy($scope.user_genres);Aphasic

© 2022 - 2024 — McMap. All rights reserved.