0

UPDATED as requested with more info:

I have a controller that calls a web method and I want the returned JSON to be binded to a variable in the controller called applications. The alert displays the JSON correctly but I see nothing in my View.

Note I have tried $scope and 'this' in the controller with manual data and only 'this' worked which is why I have use it instead of $scope below.

app.controller('AppsController', function ($http, $scope) {
$http.post('/WebMethod/DoStuff', {}).
 success(function (data, status, headers, config) {
     alert(data);
     this.applications = data;
 })
}

My View is like this

<div class="container" ng-controller="AppsController as appCtrl">
<div class="row" ng-repeat="application in appCtrl.applications">

<div class="col-xs-6 applicationName" ng-click="appCtrl.expand($index)">{{application.name}}</div>
</div></div>

JSON like

[
{
    name: "Application 1",
    alerts: "2",
    status: "Red",
    notifications:  [
        {
            header: "Notification Header 1",
            updateType: "New",
            message: "hello world",
            startTime: "11:00",
            endTime: "12:00"
        }              
    ],
    expanded: false
}]

2 Answers2

0

this is not what you expect it to be. Try this:

app.controller('AppsController', function ($http, $scope) {
  var self = this;
  $http.post('/WebMethod/DoStuff', {}).
   success(function (data, status, headers, config) {
       alert(data);
       //or you can use $scope.applications = data; instead 
       self.applications = data;
   })
}

See How does the "this" keyword work? for explanation of this in Javascript.

Community
  • 1
  • 1
daerin
  • 1,309
  • 1
  • 11
  • 17
  • This worked, I also had to wrap my data in JSON.parse() for some reason. Thanks for the response, very helpful insight into 'this' via your link also which is why I chose this answer. – Myles B. Currie Jun 19 '15 at 12:17
0

You're using controllerAs syntax, which means you don't place variables on the $scope in the controller, but rather on the controller instance itself.

Placing the data on this is correct, but you have to keep reference to the instance itself, so you need to do this:

app.controller('AppsController', function ($http, $scope) { // you probably don't need to inject the $scope
   var ctrl = this;
   $http.post('/WebMethod/DoStuff', {}).
    success(function (data, status, headers, config) {
        alert(data);
        ctrl.applications = data;
   });
}
Omri Aharon
  • 16,299
  • 3
  • 36
  • 54