问题描述:

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

}]

网友答案:

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.

网友答案:

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;
   });
}
相关阅读:
Top