how to bind angularjs objects to their keys and values

北城余情 提交于 2019-12-07 07:07:02

问题


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/

so I am hoping ot update the main arr through the input boxes and achieve 2 way key-binding.

Is this possible?


回答1:


as explained here Binding inputs to an array of primitives using ngRepeat => uneditable inputs, yes you can, but not that way

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/




回答2:


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

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

JavaScript:

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

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>


来源:https://stackoverflow.com/questions/23643592/how-to-bind-angularjs-objects-to-their-keys-and-values

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!