0

I have an array of items like this

[{
  name: "name213",
  value: "value1"
}, {
  name: "name122",
  value: "value2"
}]

I want to ng-model my input on one object of this array but I don't know this position. I just know his name.

What is the best way to do this? During the initialisation of the array, save the object in var? Bind the input on another object and when I want to save it, merge it with the array?

3
  • Your input switch the value field of your object? Commented Mar 1, 2018 at 13:52
  • do you have one input field or several of them inside ng-repeat? Commented Mar 1, 2018 at 13:53
  • yes my input switch the value of the object. And I have 1. In fact i have 2 Inputs (for 2 objects) and potentially a lot of object in my Array. I believe because is it 2 special object, it's not totally dumb to put them into new variables in my scope. Commented Mar 1, 2018 at 13:54

1 Answer 1

1

(In my comment I though about it backwards, so I decided to fix it and post it as an answer instead)

You can use ng-change on input field to change the value of an object. To find it simply use ES6 method .find() that can be applied on array. Long story short, here is a demo where everything is dynamic:

var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
    $scope.array = [
    { name : "a", value: "1"}, {name: "b", value: "2"},
    { name : "c", value: "3"}, {name: "d", value: "4"},
    { name : "e", value: "5"}, {name: "f", value: "6"},
    { name : "g", value: "7"}, {name: "h", value: "8"}
    ]; // your array 
    $scope.selected = 'a'; // default value for a `name`
    
    $scope.find = function(name){
        /* can be replaced with a for loop if ES6 is not supported */
    	$scope.array.find((e)=>{return e.name == name}).value = $scope.model;
    }
    
    $scope.change = function(e){
    	$scope.selected = e;
        $scope.model = ""; // clear the model 
    }
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>

<div ng-app="myApp" ng-controller="myCtrl">
Names: <button ng-repeat="x in ['a','b','c','d','e','f','g','h']" ng-click="change(x)">{{x}}</button>
<br>
Selected: "{{selected}}" 
<br>
New Value for that name: <input ng-model="model" ng-change="find(selected)" type="text"/>
<br>
{{array}}

</div>

I'm not sure what were you planning to do with the second input field, so I leave it for you to adjust it with my code.

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

Comments

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.