Displaying json data in an input field using AngularJS

I would like to display JSON data in html input fields using AngularJS. Here is the code.

I have two HTML files. The first HTML file contains a table that displays json data. When you click on a line, it opens a modal window with a form (second HTML file).

Here's the code data: JSON

var examples = [
   { 'id': '1', 'fname': 'john' },
   { 'id': '2', 'fname': 'bonnie' },
   { 'id': '3', 'fname': 'joey' }
];

      

Here's the Code: (First HTML file)

...
<tr ng-repeat="item in examples" ng-click="open(this.item)">
   <td>{{ item.id }}</td>
   <td>{{ item.fname }}</td>
</tr>
...

      

Second HTML file:

...
    <input type="text" class="form-control" placeholder="ID" id="firstVal" value="">
...

      

My controller:

...
$scope.open = function (item) {
   console.log(item.id);
   $("#firstVal").val(item.id);
};
...

      

It does not insert the "id" value into the input field. How can I do this using AngularJS or jQuery? In the console, I get the id value.

+3


source to share


2 answers


<input type="text" class="form-control" placeholder="ID" ng-model="selectedId">

      

and



$scope.open = function (item) {
   console.log(item.id);
   $scope.selectedId = item.Id
};

      

+6


source


Also, make sure your second HTML is using the same controller (shared scope). In addition, it is always recommended to use dot notation when accessing object regions. In this case, you would suggest the same as entre, but with a minor modification:

$scope.open = function (item) {
   $scope.selectedObj.id = item.Id
};

      

And in the HTML form (once you have the same controller running there):



<input type="text" class="form-control" placeholder="ID" ng-model="selectedObj.id">

      

UPDATE Here's a working fiddle for you: https://jsfiddle.net/aqs9vLd8/1/ Please note that $ scope.selectedObj needs to be initialized as an object (empty) first.

Let me know if it works for you

+2


source







All Articles