0

My

homeController.js

var app = angular.module('myApp');
app.controller('HomeController', 
function($scope, $http, $rootScope, $stateParams, $state, LoginService) {
$scope.user = $rootScope.userName;
console.log("Starting http request");
$http.get("http://127.0.0.1:5000/trying").success(function (response) {
      $scope.myData = response.users;
      console.log(response);
  });
console.log("ending http request");
});
<div class="col-md-12" style="width:500px;">
    <div align="right"><a ui-sref="login">Logout</a></div>
        <h4>Welcome {{user}}! </h4>
        <p><strong>This is Home Page</strong></p>
        <ul>
        <li ng-repeat="x in myData">
            Data are : {{ x.fname + ', ' + x.coordinates }}
        </li>
        </ul>
    </div>

Console

Response object

The home.html is getting rendered from index.html. It is doing it fine as can be the user with which am logging in is displaying. However the ng-repeat is not working fine. When inspecting its showing that its getting commented out. What am i doing wrong?

Community
  • 1
  • 1

1 Answers1

0
  1. I would make sure that $scope.myData exists outsideof the http.get function. Define it as an array or dictionary/obj right above the http.get function, and under $scope.user... that way the view knows what to expect.
  2. Is myData an array or a dictionary? make sure you are using the correct looping syntax (x in myData vs x of myData). Can also do (dataKey, dataValue) in myData
  3. I usu sally add an ng-if="!isLoading" to the ng-repeat if the contents are dependent on an http call. Initially I set in the this.$onInit function (which gets called automatically once the page is ready to be initialized) then in the response set it to isLoading = false.

`

this.$onInit = function(){
  $scope.isLoading = true;
  // rest of the stuff like http.get...
  $http.get("http://127.0.0.1:5000/trying").success(function (response) 
    $scope.myData = response.users;
    $scope.isLoading = false;
    console.log(response);
  });
};

`

Let me know if that helps the behavior. of your view, it could also be that the view isn't updating for some other reason.

PRO TIP: When you define your $scope.myData initially, IT MUST be the same type of variable that you are returning if you want ng-repeat to behave correctly. None of this, "declared as [] but then fills in as a {} later on with an api call".

This is one of those things that can ghost you hard since vanilla javascript is pretty hands off with variable type swapping. The view will just ignore the code smell and not do anything... which can be pretty darn frustrating if you don't know what to look for. This is why some developers have gone off to typescript and other flavors of javascript that are a bit more cemented in what they allow you to do with variable... but that is another post completely.

isaacdre
  • 842
  • 7
  • 10