javascript 如何使用 ng-checked 在 angularJs 中预选复选框

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14225855/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 21:03:48  来源:igfitidea点击:

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

javascriptrubysinatraangularjshaml

提问by toy

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

这是#{preferred_genres}来自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-checkedto be something like this it works.

所以这意味着每个复选框都应该被选中。但是当我加载页面时没有选中复选框。但是,如果我硬编码ng-checked成为这样的东西,它就可以工作。


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

This is really strange. Please help.

这真的很奇怪。请帮忙。

回答by dnc253

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

的值ng-checked需要是一个表达式。摆脱 {{}}。所以,像这样:

 %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-checkeddirective. If the value of your model is true, then it will be checked for you.

此外,您甚至不需要拥有ng-checked指令。如果您的模型的值是真的,那么它将为您检查。