2017-05-31 58 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

我認爲最好製作一段視頻來展示正在發生的事情,以便更容易理解我的問題。 –