Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pre-select checkbox in angularJs with ng-checked

I seem to cannot get this to work. So I have a bunch of genres of movies which I want them to be checked if those are the genres in user database. 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}}

And this is #{preferred_genres} from haml


{"Action & Adventure":true,"Animation":true,"Art House & International":true,"Classics":true,"Comedy":true,"Documentary":true,"Drama":true,"Horror":true,"Kids & Family":true,"Musical & Performing Arts":true,"Mystery & Suspense":true,"Romance":true,"Science Fiction & Fantasy":true,"Special Interest":true,"Sports & Fitness":true,"Television":true,"Western":true}

So that means every checkbox should be checked. But no checkbox is checked when I load the page. However if I hardcode ng-checked to be something like this it works.


ng-checked="user_genres['Western']"

This is really strange. Please help.

like image 652
toy Avatar asked Jan 08 '13 23:01

toy


People also ask

How do I check if a checkbox is checked in AngularJS?

The ng-checked Directive in AngularJS is used to read the checked or unchecked state of the checkbox or radio button to true or false. If the expression inside the ng-checked attribute returns true then the checkbox/radio button will be checked otherwise it will be unchecked.

How do I make a checkbox readonly in AngularJS?

If checkbox will be checked then ng-readonly will get TRUE value and TextBox will be converted into Read-Only TextBox. If checkbox will be unchecked then ng-readonly will get FALSE value and Read-Only TextBox will be converted into again Read-Write textbox.

What is the use of NG-checked?

Definition and Usage The ng-checked directive sets the checked attribute of a checkbox or a radiobutton. The checkbox, or radiobutton, will be checked if the expression inside the ng-checked attribute returns true. The ng-checked directive is necessary to be able to shift the value between true and false .


1 Answers

The value of ng-checked needs to be an expression. Get rid of the {{}}. So, something like this:

 %input(type = "checkbox" ng-model="preferred_genres[genre]" id="genre-{{$index + 1}}" ng-checked="user_genres[genre]")

Also, you don't need to necessarily even have the ng-checked directive. If the value of your model is true, then it will be checked for you.

like image 96
dnc253 Avatar answered Oct 16 '22 02:10

dnc253