仅仅是为了注意,我对angularJS一无所知,我之前和之后使用过knockoutJS我只是做出假设。
我有这样的代码:
angular.module("umbraco").controller("recallCtrl",
function ($scope, $routeParams) {
$scope.dcList = {
key: "value",
abc: "aaaa",
prop: "tadaa!"
}
});
和标记如下:
<div ng-controller="recallCtrl">
<table class="table table-sm">
<thead>
<tr>
<td></td>
<th>Key</th>
<th>Value</th>
</tr>
</thead>
<tr ng-repeat="(key, value) in dcList">
<td>
</td>
<td>
<input ng-model="key" />
</td>
<td>
<input ng-model="value"/>
</td>
</tr>
</table>
<pre>{{dcList | json}}</pre>
</div>
因此,当我编辑相应的输入时,不应该在html的末尾输出dcList
,而我会假设这些输入被绑定到对象?
如果我做错了,请告知。我想创建对象并能够更改其键和值。
答案 0 :(得分:3)
您当前代码无法正常工作的原因是&#34;键&#34;和&#34;价值&#34;变量在ng-repeat
范围内,不再直接引用原始对象。
保持&#34;值&#34;附加很简单,只需使用dcList[key]
而不是value
。添加新密钥需要更多工作;在这里,我已将ng-blur
附加到每个&#34;键&#34;当字段模糊时将初始化新键的字段。 (ng-change
会在每次击键时创建一个新字段,这不是你想要的。)请注意,当你开始输入一个新密钥时,它的值似乎消失了 - 这是因为{{1直接引用新的密钥名称。当然,这在实际UI中会有些混乱;您可能希望将不同的行为编码到dcList[key]
函数中(例如将旧值复制到新密钥中,或删除原始密钥)。
createNewKey
&#13;
function recallCtrl($scope) {
$scope.dcList = {
key: "value",
abc: "aaaa",
prop: "tadaa!"
}
$scope.createNewKey = function(k) {
$scope.dcList[k]="";
}
}
&#13;
答案 1 :(得分:2)
请测试此代码,更改与键对应的值,
angular.module('app', [])
.controller('Controller', function($scope) {
$scope.dcList = {
key: "value",
abc: "aaaa",
prop: "tadaa!"
}
})
<!DOCTYPE html>
<html>
<head>
<script src="//cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.0/angular.min.js"></script>
</head>
<body ng-app="app">
<div ng-controller="Controller">
<table class="table table-sm">
<thead>
<tr>
<td></td>
<th>Key</th>
<th>Value</th>
</tr>
</thead>
<tr ng-repeat="(key, value) in dcList">
<td>
</td>
<td>
<input ng-model="key" disabled/>
</td>
<td>
<input ng-model="dcList[key]" />
</td>
</tr>
</table>
<pre>{{dcList | json}}</pre>
</div>
</body>
</html>