如何在角度角度为ng模型动态赋值?
发布时间:2020-12-17 07:46:08 所属栏目:安全 来源:网络整理
导读:在这里,我使用ng-repeat动态生成一个html元素,例如 div ng-repeat="type in types" input type="checkbox" ng-model="{{type}}" /{{ type }}/div 我想为ng-model设置类型值.是否可能,或者我想要这样设置ng-true-value的类型值 div ng-repeat="type in types"
在这里,我使用ng-repeat动态生成一个html元素,例如
<div ng-repeat="type in types"> <input type="checkbox" ng-model="{{type}}" />{{ type }} </div> 我想为ng-model设置类型值.是否可能,或者我想要这样设置ng-true-value的类型值 <div ng-repeat="type in types"> <input type="checkbox" ng-model="{{type}}" ng-true-value="{{type}}" />{{ type }} </div>
由于ng-repeat为每个类型/项目/迭代创建子范围,因此我们需要将每个类型的ng模型与父范围相关联,而不是将子范围.一种方法是使用$parent:
<input type="checkbox" ng-model="$parent[type]">{{ type }} 如果$scope.types定义为@ Alex的答案,则如果单击相应的复选框,属性typeOne,typeTwo和typeThree将显示在父作用域上,并且该属性的值将为true.如果再次单击勾选复选框,该属性将保留,该值将切换为false.因此,您的代码将必须检查不存在的属性以及对值设置为true或false的属性.这有点凌乱 我更喜欢在父范围上预定义一组对象,其中每个对象的类型为(name),一个布尔值表示是否被选择: $scope.types = [ {name: 'typeOne',selected: false},{name: 'typeTwo',{name: 'typeThree',selected: false}]; 然后,$parent不是必需的(因为“type”的值将是对父对象的引用,而不是父属性(原语)值的副本): <input type="checkbox" ng-model="type.selected">{{ type.name }} 另请参阅What are the nuances of scope prototypal / prototypical inheritance in AngularJS?了解有关ng重复和子范围的更多信息. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |