如何为angularjs中的ng-model动态赋值?

JSA*_*ict 17 angularjs

在这里,我使用ng-repeateg 动态生成一个html元素

<div ng-repeat="type in types">
    <input  type="checkbox" ng-model="{{type}}" />{{ type }}
</div>
Run Code Online (Sandbox Code Playgroud)

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

<div ng-repeat="type in types">
    <input  type="checkbox" ng-model="{{type}}" ng-true-value="{{type}}" />{{ type }}
</div>
Run Code Online (Sandbox Code Playgroud)

Mar*_*cok 12

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

<input type="checkbox" ng-model="$parent[type]">{{ type }}
Run Code Online (Sandbox Code Playgroud)

如果$ scope.types就像@亚历克斯的答案定义,那么性能typeOne,typeTwo以及typeThree会出现在父范围如果点击相应的复选框,以及财产的价值将是true.如果再次单击选中的复选框,则属性仍然存在,并且值将切换为false.因此,您的代码必须检查不存在的属性以及存在且值设置为true或false的属性.那有点乱.

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

$scope.types = [ 
  {name: 'typeOne', selected: false},
  {name: 'typeTwo', selected: false},
  {name: 'typeThree', selected: false}];
Run Code Online (Sandbox Code Playgroud)

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

<input type="checkbox" ng-model="type.selected">{{ type.name }}
Run Code Online (Sandbox Code Playgroud)

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


Ale*_*ock 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>
Run Code Online (Sandbox Code Playgroud)

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

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

for (i = 0; i < length; i++) {
    console.log($scope.types[i] + " : " + $scope.typeValues[$scope.types[i]]);
}            
Run Code Online (Sandbox Code Playgroud)