2016-04-14 29 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>