17

在这里,我正在使用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>
4

2 回答 2

12

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

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

如果 $scope.types 的定义与@Alex的答案一样,则如果单击相应的复选框,则 properties typeOne, typeTwo, andtypeThree将出现在父范围上,并且该属性的值将为true。如果再次单击选中的复选框,则该属性保持不变,并且值将切换为false。因此,您的代码必须检查不存在的属性以及值设置为 true 或 false 的存在的属性。这有点乱。

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

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

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

<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.

于 2012-12-22T02:31:54.890 回答
8

您可以将动态值存储到 $scope 的属性之一中,如下所示:

function DynamicController($scope) {
    $scope.types = [
        "typeOne",
        "typeTwo",
        "typeThree"        
    ];
    $scope.typeValues = {};
};

<div ng-app ng-controller="DynamicController">
    <div ng-repeat="type in types">
        <input  type="checkbox" ng-model="typeValues[type]" ng-click="show()" /> {{ type }}
    </div>

    <h3>Values</h3>
    <div ng-repeat="type in types">
        {{ type }} : {{ typeValues[type] }}
    </div>
</div>

然后,您可以通过范围的 typeValues 属性检查您的值。

var i,
    length = $scope.types.length;

for (i = 0; i < length; i++) {
    console.log($scope.types[i] + " : " + $scope.typeValues[$scope.types[i]]);
}            
于 2012-12-21T13:10:29.303 回答