[英]AngularJS creating json from ng-repeat
Inspired from this codepen I used a JSON file
to load some basic input fields and toggles. 从此代码笔中得到启发,我使用了一个
JSON file
来加载一些基本的输入字段和切换。 When the user change something and press save, I would like to save these new property values
in a new JSON object
with same property names
. 当用户更改某些内容并按Save时,我想将这些新
property values
保存在具有相同property names
的新JSON object
。
My code looks the this 我的代码看起来像这样
JS JS
.controller('page', function($scope, templateSettingsFactory, savedSettingsFactory) {
$scope.template = templateSettingsFactory;
$scope.saved = savedSettingsFactory;
$scope.saveSettings = function(){
var temp = $scope.template;
var jsonObj = {};
for(var key in temp){
jsonObj[key]=temp[key];
}
$scope.saved.$add(jsonObj);
};
});
HTML 的HTML
<label ng-repeat="item in template">
<input type="text" placeholder="{{item}}">
</label>
<button class="button" ng-click="saveSettings()">Save</button>
The problem is that calling the saveSettings()
don't get the updated property values
of $scope.template
- perhaps it's not doing two-way binding? 问题在于,调用
saveSettings()
不会获得$scope.template
的更新property values
-也许不是在进行双向绑定?
You need to use ng-model
on your form elements to bind their input to the scope. 您需要在表单元素上使用
ng-model
将其输入绑定到范围。
<input type="text" ng-model="item.property">
Here is an example of binding to a single object with arbitrary keys: 这是使用任意键绑定到单个对象的示例:
<div ng-repeat="(key,value) in template">
<div>{{key}}</div>
<input type="text" ng-model="template[key]"/>
</div>
https://docs.angularjs.org/api/ng/directive/ngModel https://docs.angularjs.org/api/ng/directive/ngModel
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.