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

Why ng-show does not work properly?

本文关键字:工作 常工作 ng-show 不能 为什么      更新时间:2023-09-26

为什么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!;在我的小提琴是工作,但在我的项目不是工作,我明白,没有所有的代码你不能告诉什么样的bug,但也许有人是相同的bug,并记得如何修复它。

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

谢谢。

事件我也面对这个问题的ng-show。尝试使用$scope.$apply()更新作用域。或者您也可以使用ng-if来达到相同的目的。

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

不需要errorsFlag。国旗 errorsFlag 对象。

如果你真的需要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>

另一种方法是使用this关键字代替controller as语法。试试这个: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>