0

Inspired from this codepen I used a JSON file to load some basic input fields and toggles. 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.

My code looks the this

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

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

1 Answer 1

1

You need to use ng-model on your form elements to bind their input to the scope.

<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

Sign up to request clarification or add additional context in comments.

5 Comments

It really all depends on your json input. stackoverflow.com/a/13715352/580487
it's not an array of objects that my ng-repeat loops through, it's just all the property names in the object and their values.
i've updated my example to show binding to one object with arbitrary keys
The (key, value in template seems to work... but have a strange behavior of making the placeholder the actual input value
Thank you very much for the swift answer

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.