aftab
aftab

Reputation: 693

How to bind json data to angularJS view using $scope?

I have a JSON response from the backend that i want to display to the front end so in below case i am not able to bind $scope value to view.If i change response into object instead of array its populating.How to populate array object to the view ?

main.html

<div class="row">
        <div class="form-group col-md-6">
            <div class="col-md-3">
                <label for="workerName">Full Name:</label>
            </div>
            <div class="col-md-9">
                <input type="text" class="form-control" name="workerName" ng-model="data.firstName">
            </div>
        </div>
        <div class="form-group col-md-6">
            <div class="col-md-3">
                <label for="workerName">Address:</label>
            </div>
            <div class="col-md-9">
                <input type="text" class="form-control" name="workerName" ng-model="data.lastName">
            </div>
        </div>
    </div>

app.js

var Obj = [{firstName: "Mike", lastName:"wegner"},{firstName:"John",lastName:"Ruch"}];

app.get('/test', function (req, res) {
  res.send(Obj);
});

workerFacotry.js

angular.module('myApp').factory('workerFactory', function ($http) {
    'use strict';
    return {
        getData: function(){
            return $http.get('/test');
        }
    }
});

workerController.js

angular.module('myApp').controller('WorkerController', function ($scope,workerFactory) {
    'use strict';
    $scope.test = function(){
        alert("first functiona is working");
    };
    $scope.data = [];
    $scope.getTestData = function(){
        workerFactory.getData().then(function(response){
            $scope.data = response.data;
            console.log("Data from server",$scope.data);
        })
    }
});

Json.js

[{
    "firstName": "Mike",
    "lastName": "wegner"
}, {
    "firstName": "John",
    "lastName": "Ruch"
}]

Upvotes: 0

Views: 3980

Answers (1)

mani
mani

Reputation: 3096

Loop through the data using ngRepeat directive as:

<div class="row" ng-repeat="d in data">
        <div class="form-group col-md-6">
            <div class="col-md-3">
                <label for="workerName">Full Name:</label>
            </div>
            <div class="col-md-9">
                <input type="text" class="form-control" name="workerName" ng-model="d.firstName">
            </div>
        </div>
        <div class="form-group col-md-6">
            <div class="col-md-3">
                <label for="workerName">Address:</label>
            </div>
            <div class="col-md-9">
                <input type="text" class="form-control" name="workerName" ng-model="d.lastName">
            </div>
        </div>
    </div>

Upvotes: 1

Related Questions