Frostbch Frostbch - 10 months ago 51
AngularJS Question

Cant display $scope array of objects in AngularJs

I have this weird problem that i cant display my scope variable values. I am new with angular but i have done this many times before. So here is main parts of index.html. div-ui is inside of body but it doesn't see here:

<input type="text" class="form-control" ng-model="searchUsers" placeholder="Search users"/>
<a ng-click="search()" ui-sref="search">Search</a>

<div ui-view>


Here is search.html:

<p>Hello world</p> // Shows normally
<p>{{test1}}</p> // Shows normally
<p>{{test2}}</p> // Nothing
<p ng-repeat="x in searchResult">{{x.username}}</p> // Nothing
<p ng-repeat="(key,value) in searchResult">{{value}}</p> // Nothing
<p ng-repeat="(key,value) in searchResult">{{value.username}}</p> // Nothing

Here is the controller:

.controller('NavigationCtrl', ["$scope", "$http", "$state",

$scope.searchResult = [];
// Tried with and without this

$scope.loggedIn = true;
$scope.loggedIn = false;

$scope.logUserIn = function(){
$'api/user/login', $scope.login)
localStorage.setItem('User-Data', JSON.stringify(response));
$scope.loggedIn = true;

$scope.logOut = function (){
$scope.loggedIn = false;

$scope.test1 = "hi";

$ = function (){

$scope.test2 = "hi again";

$"api/user/search", {username: $scope.searchUsers})

$scope.searchResult = response;
// returns array of objects. There is all information that i want.


Everything looks just normal. Inside of search function it's working and console.log returns just what i except. I have also tried repeat divs and tables but i am pretty sure that it's not the problem here.

Here is also my app.js if the problem is there:

angular.module('TimeWaste', ['ui.router', 'ngFileUpload'])
.config(function ($stateProvider, $urlRouterProvider){


.state("main", {
url: "/",
templateUrl: "app/main/main.html",
controller: "MainCtrl"
.state("search", {
url: "/search",
templateUrl: "app/main/search.html",
controller: "NavigationCtrl"

There is couple more states and they all works just fine. I made it little bit shorter so this post won't be so long.

Answer Source

The reason you're able to see {{test1}} and not other values is because you have 2 different controllers called 'MainCtrl' and 'NavigationCtrl'. You are using ui-sref to switch states. So, this is what happening.

  1. When you click your href link, it looks for search() method inside your MainCtrl and then change the state to "search".

  2. It then loads the variables and methods from NavigationCtrl into scope and that's why you're able to see {{test1}} which is loaded into the scope. But you haven't called search() method and hence you're not able to see the other values.

To check my answer, call your method explicitly inside your controller after your function definition $;

If you're seeing the result then that is your problem.