0

I have 3 components, the web api, the controller, and the html. I can hit the web api just fine and i get back the results in JSON format, but when it then tries to render the JSON into the html, it looks like this.

{
    "Projects": [{
        "ProjectId": 1,
        "Name": "Project1",
        "Key": "Software",
        "ProjectTypeKey": "1"
    }, {
        "ProjectId": 2,
        "Name": "Project2",
        "Key": "Hardware",
        "ProjectTypeKey": "2"
    }, {
        "ProjectId": 3,
        "Name": "Project3",
        "Key": "Hardware",
        "ProjectTypeKey": "3"
    }]
}

WebApi

    public IHttpActionResult Get()
    {
        listProjects.Add(new Project { ProjectId = 1, Name = "Project1", Key = "Software", ProjectTypeKey = "1" });
        listProjects.Add(new Project { ProjectId = 2, Name = "Project2", Key = "Hardware", ProjectTypeKey = "2" });

        listEmployeeProject.Add(new EmployeeProject {Projects = listProjects });

        return Json(listEmployeeProject);
    }

Controller

var myApp = angular.module('myApp', []);

myApp.service('dataService', function ($http) {

this.getData = function () {
    // $http() returns a $promise that we can add handlers with .then()
    return $http({
        method: 'GET',
        url: '/api/employee'           
    });
}
});

myApp.controller('ProjectController', function ($scope, dataService) {
$scope.Projects = [];
dataService.getData().then(function (result) {
    $scope.Projects = result.data;
});
});

HTML

<div ng-app="myApp" ng-controller="ProjectController">
{{1 + 1}}

<div ng-repeat="project in Projects">
    {{project}}
</div>

Even when i switch {{project}} to {{project.Name}}, nothing renders on the page.

console.log(results.data) looks like below

enter image description here

15
  • {{1 + 1}} is rendered? Commented Aug 11, 2016 at 23:43
  • yes this renders as 2 Commented Aug 11, 2016 at 23:44
  • Have to checked what you're getting in result.data? Commented Aug 11, 2016 at 23:44
  • Any errors on console? Put a console.log(result.data) in your then function. Commented Aug 11, 2016 at 23:45
  • results.data is an array of 3 objects Commented Aug 11, 2016 at 23:45

1 Answer 1

1

Its very clear from your console that you are returning an array of length 1 which has another array of length 3 in it

This is because of this line in your code

listEmployeeProject.Add(new EmployeeProject {Projects = listProjects });

Here you are retuning a EmployeeProject array and each element of that array has multiple projects. So do either of these things

a. Return listProjects like return Json(listProjects) (You should be returning Ok(model) ideally)

b. Or in angular promise do,

$scope.Projects = result.data[0].Projects;
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.