2016-04-14 69 views
0

我使用整數來表示我的應用程序中的一個狀態,其中有幾個(3)容器使用<div ng-if="state == value">來顯示該頁面的正確信息。問題是,當state更改時,屏幕變成白色。沒有錯誤,沒有任何東西。這只是空白。Angular在更新ng-if變量後顯示空屏幕

angular.module('CharCount') 
 

 
    .controller('MainCtrl', function($scope, $timeout) { 
 

 
    $scope.state = 0; 
 
    
 
    $scope.stateText = "waiting"; 
 
    
 
    $scope.clicked = function() { 
 
     $timeout(function() { 
 
     $scope.state = 1; 
 
     $scope.state = "loading"; 
 
     $scope.test(null, function() { 
 
      $scope.state = 2; 
 
      $scope.state = "finished, should show State C"; 
 
     }); 
 
     }); 
 
    }; 
 
    
 
    $scope.test = function(a, callback) { 
 
     $timeout(callback); 
 
    }; 
 
    
 

 
    });
<html> 
 

 
    <head> 
 
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.3/angular.min.js"></script> 
 
    </head> 
 

 
    <body ng-app="CharCount"> 
 
    <div ng-controller="MainCtrl"> 
 
     <div ng-if="state == 0"> 
 
     State A<br> 
 
     {{stateText}}<br> 
 
     <button ng-click="clicked()">click me</button> 
 
     </div> 
 
     
 
     <div ng-if="state == 1"> 
 
     State B<br> 
 
     {{stateText}} 
 
     </div> 
 
     
 
     <div ng-if="state == 2"> 
 
     State C<br> 
 
     {{stateText}} 
 
     </div> 
 
    </div> 
 
    <script src="angular-character-count.js"></script> 
 
    <script src="app.js"></script> 
 
    </body> 
 

 
</html>

如果任何人都可以解釋爲什麼出現這種情況,這將會有很大的幫助。

回答

1

有在代碼中的許多問題:

  1. 爲了獲取應用程序實例中使用的吸氣劑,第二個參數傳遞給module()爲空數組。 ==>angular.module('CharCount', [])
  2. 裏面的$timeout回調,變量state被分配一個字符串。

    $scope.state = 1; 
    $scope.state = "loading"; // This is incorrect 
    

    由於在視圖中沒有條件且所有其他條件評估爲false,所以不會顯示任何元素。

  3. 邏輯錯誤:在調用$timeout之前應設置值。

    $scope.state = 1; 
    $scope.stateText = "loading"; 
    

    將這些語句移到$timeout以上。

演示:

angular.module('CharCount', [])      // <--- #1 
 

 
.controller('MainCtrl', function($scope, $timeout) { 
 

 
    $scope.state = 0; 
 
    $scope.stateText = "waiting"; 
 

 
    $scope.clicked = function() { 
 
    $scope.state = 1;        // <--- #3 
 
    $scope.stateText = "loading";     // <--- #2 
 

 
    $timeout(function() { 
 
     $scope.test(null, function() { 
 
     $scope.state = 2; 
 
     $scope.stateText = "finished, should show State C"; // <--- #2 
 
     }); 
 
    }, 1000); 
 
    }; 
 

 
    $scope.test = function(a, callback) { 
 
    $timeout(callback); 
 
    }; 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.3/angular.min.js"></script> 
 

 
<body ng-app="CharCount"> 
 
    <div ng-controller="MainCtrl"> 
 
    <div ng-if="state == 0"> 
 
     State A 
 
     <br>{{stateText}} 
 
     <br> 
 
     <button ng-click="clicked()">click me</button> 
 
    </div> 
 

 
    <div ng-if="state == 1"> 
 
     State B 
 
     <br>{{stateText}} 
 
    </div> 
 

 
    <div ng-if="state == 2"> 
 
     State C 
 
     <br>{{stateText}} 
 
    </div> 
 
    </div> 
 

 
</body>