AngularJS未在视图

时间:2015-06-19 11:57:17

标签: javascript json angularjs

根据要求更新了更多信息:

我有一个调用web方法的控制器,我希望将返回的JSON绑定到名为applications的控制器中的变量。警报正确显示JSON但我在视图中看不到任何内容。

注意我已经尝试使用手动数据在控制器中使用$ scope和'this',只有'this'工作,这就是为什么我使用它而不是下面的$ scope。

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

我的观点就像这样

<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喜欢

[
{
    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 个答案:

答案 0 :(得分:0)

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;
   })
}

有关Javascript中this的说明,请参阅How does the "this" keyword work?

答案 1 :(得分:0)

您正在使用controllerAs语法,这意味着您不会将变量放在控制器中的$scope上,而是放在控制器实例本身上。

将数据放在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;
   });
}
相关问题