为什么 ng-show 不能正常工作?

Why ng-show does not work properly?

为什么 ng-show 不能正常工作? 我有代码:

<h3 class="alert alert-danger" ng-show="errorsFlag.flag">{{errorMessage}}</h3>

在我的控制器中:

$scope.errorsFlag = { flag:false };
//some code
SomeFunction.getSomething()
   .then(
        //success
        function(result){
            $scope.errorsFlag.flag = false;
        },
        //fail
        function(error){
            $scope.errorsFlag.flag = true;
        }
    ).finally(//some code);

当我的函数出现错误时,

$scope.errorsFlag.flag = true

,而页面上的元素'h3'一定是可见的,但是我刷新页面的时候,一次可见,一次不可见,什么问题? 当我检查代码时,我看到了这个:

<h3 class="alert alert-danger ng-binding ng-hide" ng-show="errorsFlag.flag"></h3>

,但在控制台中,$scope.errorsFlag.flag = true!; 在我的 fiddle 中它可以工作,但在我的项目中不起作用,我知道如果没有所有代码你就无法分辨出什么样的错误,但也许有人有同样的错误并记住如何修复它。

https://jsfiddle.net/gc3equ1f/1/

谢谢。

删除 ng-show 指令并使用 ng-bind="errorMessage"

您不需要 errorsFlag.flagerrorsFlag 对象。

如果你真的需要display:none这个h3

你可以只使用 ng-show="errorMessage"ng-bind="errorMessage"

   <h3 class="alert alert-danger ng-binding ng-hide" ng-show="errorMessage"  ng-bind="errorMessage"></h3>

事件 ng-show 我也遇到过这个问题。一旦尝试使用 $scope.$apply() 更新范围。 或者你也可以使用 ng-if 来达到同样的目的。

另一种方法是将控制器用作带有 this 关键字的语法。试试这个 fiddle:https://jsfiddle.net/hjamal/hu4t0zL8/2/

因此您的代码将如下所示:

var app = angular.module('myApp', []);

app.controller('TestC', function TestC ($scope, $q){
    var self = this;
  self.errFlag = {
        flag: true
    };
    
    var someFunc = function() {
       serviceFunc().then(
            function(){
              self.errFlag.flag = false;   
            },
            function(){
              self.errFlag.flag = true;   
            }
        );
    };
    
    var serviceFunc = function(){
            var def = $q.defer();
        
         def.reject("error 404");

            return def.promise;
        };    
    //someFunc();
});
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp">
    <div ng-controller='TestC as tc'>demo
        <!--  ng-show="errFlag.flag"  -->
        <h3 class="alert alert-danger" ng-show="tc.errFlag.flag">
                {{tc.errFlag.flag}}
        </h3>
    </div>
</div>