简体   繁体   English

如何将angularjs对象绑定到它们的键和值

[英]how to bind angularjs objects to their keys and values

I read through some articles on angular model binding, and just out of curiousity, I was wondering if its possible to bind keys to input too, 我阅读了一些关于角度模型绑定的文章,只是出于好奇,我想知道它是否可以将键绑定到输入,

http://jsfiddle.net/x3azn/jM28y/4/ http://jsfiddle.net/x3azn/jM28y/4/

so I am hoping ot update the main arr through the input boxes and achieve 2 way key-binding. 所以我希望通过输入框更新主arr并实现双向键绑定。

Is this possible? 这可能吗?

as explained here Binding inputs to an array of primitives using ngRepeat => uneditable inputs , yes you can, but not that way 如此解释使用ngRepeat =>不可编辑的输入将输入绑定到基元数组 ,是的,你可以,但不是这样

try this 试试这个

function ctrl($scope) {
$scope.arr = [{name:'1', lastname: '2'},
              {name:'3', lastname: '4'},
              {name:'5', lastname: '6'}]
}

<div ng-repeat="person in arr">
    <input type="text" ng-model="person.name" />
    <input type="text" ng-model="person.lastname" />
</div>

http://jsfiddle.net/jM28y/5/ http://jsfiddle.net/jM28y/5/

No, it is not possible to bind a key to an input. 不,不可能将键绑定到输入。

The closest thing that I found you can do is abuse ngRepeat's $index property and bind it to the input. 我发现你能做的最接近的事情是滥用ngRepeat的$index属性并将其绑定到输入。 You can't change keys for existing values but you can change what value is shown as well as create new key-value pairs. 您无法更改现有值的键,但可以更改显示的值以及创建新的键值对。 By no means am I recommending this as a solution, I just wanted to share the hackery that ensued when I was investigating this question. 我决不建议将其作为一种解决方案,我只想分享在调查这个问题时所产生的hackery。

JSFiddle: http://jsfiddle.net/DanielBank/v6tFG/ JSFiddle: http//jsfiddle.net/DanielBank/v6tFG/

JavaScript: JavaScript的:

function ctrl($scope){
    $scope.obj = {
        '0': 'a',
        '1': 'b',
        '2': 'c',
        'George': 'Clooney',
    };
}

HTML: HTML:

<div ng-app>
<div ng-controller="ctrl">
    <div ng-repeat="value in obj">
        <input type="text" ng-model="$index"/>
        <input type="text" ng-model="obj[$index]"/>
        <input type="text" ng-model="value"/>
    </div>    
    {{obj}}
</div>
</div>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM