如何在angularjs中为ng-model动态赋值? [英] How to give value dynamically for ng-model in angularjs?

查看:100
本文介绍了如何在angularjs中为ng-model动态赋值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这里我使用 ng-repeat 动态生成一个 html 元素,例如

<input type="checkbox" ng-model="{{type}}"/>{{ type }}

我想设置 ng-model 的类型值.是否有可能,否则我想像这样为 ng-true-value 设置该类型值

<input type="checkbox" ng-model="{{type}}" ng-true-value="{{type}}"/>{{ type }}

解决方案

由于 ng-repeat 为每个类型/项目/迭代创建了一个子作用域,我们需要将每个类型的 ng-model 与父作用域相关联,而不是比子作用域.一种方法是使用 $parent:

{{ type }}

如果 $scope.types 的定义类似于@Alex 的回答,则属性 typeOnetypeTwotypeThree 将出现在父级上如果点击相应的复选框,则该属性的值为true.如果再次单击选中的复选框,则该属性保持不变,值将切换为 false.因此,您的代码必须检查不存在的属性以及存在值设置为 true 或 false 的属性.有点乱.

我更喜欢在父作用域上预定义一个对象数组,其中每个对象都有类型(名称)和一个布尔值来指示它是否被选中:

$scope.types = [{名称:'typeOne',选择:false},{名称:'typeTwo',选择:false},{名称:'typeThree',选择:false}];

那么,$parent 不是必需的(因为type"的值将是对父对象的引用,而不是父属性(原始)值的副本):

{{ type.name }}

另见 什么AngularJS 中范围原型/原型继承的细微差别是什么? 以了解有关 ng-repeat 和子范围的更多信息.

Here I am generating an html element dynamically using ng-repeat eg

<div ng-repeat="type in types">
    <input  type="checkbox" ng-model="{{type}}" />{{ type }}
</div>

I want to set the type value for ng-model. Is it possible or else I want to set that type value for ng-true-value like this

<div ng-repeat="type in types">
    <input  type="checkbox" ng-model="{{type}}" ng-true-value="{{type}}" />{{ type }}
</div>

解决方案

Since ng-repeat creates a child scope for each type/item/iteration, we need to associate the ng-model for each type with the parent scope, rather than the child scope. One way to do that is to use $parent:

<input type="checkbox" ng-model="$parent[type]">{{ type }}

If $scope.types is defined like in @Alex's answer, then properties typeOne, typeTwo, and typeThree will appear on the parent scope if the corresponding checkbox is clicked, and the value of the property will be true. If a checked checkbox is clicked again, the property remains, and the value will switch to false. Your code would therefore have to check for non-existent properties and for properties that exist with the value set to true or false. That's a little messy.

I would prefer to predefine an array of objects on the parent scope, where each object has the type (name), and a boolean to indicate if it is selected or not:

$scope.types = [ 
  {name: 'typeOne', selected: false},
  {name: 'typeTwo', selected: false},
  {name: 'typeThree', selected: false}];

Then, $parent is not required (because the value of "type" will be a reference to the parent object, rather than a copy of the parent property's (primitive) value):

<input type="checkbox" ng-model="type.selected">{{ type.name }}

See also What are the nuances of scope prototypal / prototypical inheritance in AngularJS? to learn more about ng-repeat and child scopes.

这篇关于如何在angularjs中为ng-model动态赋值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆