2017-05-31 59 views
1

我有$ scope.parents变量位于控制器“userCrtl”。问题是在AJAX调用后它的值没有被更新。我试图使用$ q在承诺结束后应用更改;但是,我没有成功。我试图使用$ scope.watch来检测更改,但这种方法从未开始。因此,我的html页面从不更新。当我使用console.log($ scope.parents)时,$ scope.parents的值正常显示,但是html视图没有更新。如果使用默认值($ scope.parents =“test”)初始化$ scope.parents,则会显示此值,但不会再进行更改。 最令人沮丧的是,我在其他应用程序控制器中做了同样的事情,一切正常。某些内容只会导致$ scope变量的先前定义的值在html中显示。 以下是控制器代码:

app.controller("userCtrl", function($scope, userService, $http) { 
    $scope.panels = userService.get(); 
    $scope.parents = null; 
    $scope.start = function(panel) { 
     // Get parents blocks 
     $http.get(path + "getpaneluser /" + panel.painelUsername).then (function (response) { 
      $scope.parents = response.data; 
     // Here the value of parents is normally displayed 
        console.log($scope.parents); 
     }, function(error) { 
     }); 
    }; 
// Displays only null, even if $scope.parents has a value after the AJAX call 
    $scope.$Watch('parents', function() { 
     console.log($scope.parents); 
    }); 
}); 

HTML代码:

<div class="col-lg-12" style="padding-right: 0%;"> 
{{parents}} <!-- value never displayed --> 
    <div ng-repeat="item in parents" class="declareContainer"> 
     {{item}} 
    </div> 
</div> 

谢谢大家的帮助

+2

您的代码中有一个错字:$ scope。$ watch应该是$ scope。$ watch,但这不是y的原因我们的问题 –

+0

只是为了涵盖所有的基础,你能确认你提供的html模板是否在userCtrl中,而不是在不同控制器的权限之下?这将解释为什么UI继续显示旧值,而不是由userCtrl加载的新值,因为由userCtrl设置的$ scope.parents将在其自己的子范围内并且不可用于您的html模板。 – CodeWarrior

+0

所以朋友,在路由里面app.js定义如下: templateUrl:“意见/ panelUser.html”, 控制器:“userCtrl” 我相信这是正确的 –

回答

2

你的Ajax调用范围后$的范围内应用数据

$http.get(path + "getpaneluser /" + panel.painelUsername).then (function (response) { 
      $scope.parents = response.data; 
     // Here the value of parents is normally displayed 
        console.log($scope.parents); 
    $scope.$apply() 
     }, function(error) { 
     }); 
+2

实际上,则()调用应用在摘要循环中,所以你必须使用$ scope。$ apply()在$ scope.parents上应用你的更改 –

+0

我的朋友,问题在继续......我不知道该怎么尝试。我是否可以通过console.log($ scope.parents)在后台获取$ scope.parents的值。在我的路由中,我为每个路由设置了html模板和控制器。 事实是,如果$ scope.parents用某个值初始化,我可以在html页面上显示该值。如果变量的值发生变化,则html保持静态。 –

+0

我认为最好制作一段视频来展示正在发生的事情,以便更容易理解我的问题。 –