Angular $scope和ng-if/ng-show问题.视图中的状态没有改变

Angular $scope and ng-if/ng-show issue. Status not changing in the view

本文关键字:状态 改变 视图 问题 scope ng-if ng-show Angular      更新时间:2023-09-26

我正在使用Firebase对我的web应用程序进行身份验证。我在不同的页面上有按钮,我只想在管理员登录时出现。我一直试图在按钮上使用ng-if来显示loggedin = true。我已经控制台记录了'loggedin'的状态,它似乎正在正确地改变,但按钮根本不显示。

我怎么也弄不明白这里到底发生了什么事。我已经查看了angular文档中关于$scope、ngIf和ngShow指令的内容,但是什么都没找到。我还回顾了这个StackOverflow的帖子,它显示了这个过程的起源。它似乎对那些在帖子里的人有用,但对我来说没有乐趣。

这是我的控制器中的代码:

app.controller('welcomeCtrl', function ($scope, welcomeData, $routeParams, $location) {
var ref = new Firebase('https://mywebapp.firebaseio.com/');
  //authentication check
  var auth = new FirebaseSimpleLogin(ref, function (error, user) {
    if (error) {
      // an error occurred while attempting login
      console.log(error);
    }
    // no user logged in
     else if (user === null) {
      console.log("Not logged in");
    }
    // normal user logged in
    else if (user.id !== "47f0b82c-59d2-4bcd-8arc-ecb438eb0163") {
      console.log("You are logged in as normal user");
    }
    // admin logged in
    else {
      console.log("Logged in as admin");
      $scope.loggedin = true;
      console.log("logging the scope.loggedin as admin " + $scope.loggedin);
    }
  });
  $scope.loggedin = false;
  console.log("logging scope.loggedin " + $scope.loggedin);
  var authCheck = function () {
    console.log("logging the scope in authCheck " + $scope.loggedin);
    return auth.user !== null;
  };
  authCheck();

这是一个似乎没有适当改变的HTML元素:

<div ng-show="loggedin">
  <a class="btn waves-effect waves-red" ng-href="/#/editWelcome/{{welcome._id}}">Update
  </a>
</div>

你知道我做错了什么吗?谢谢你的帮助。

首先,FirebaseSimpleLogin已弃用。验证方法现在是核心Firebase库的一部分。您可以使用onAuth回调来实现。

你没有看到$scope.loggedin值变化的原因是因为Firebase的回调发生在Angular的摘要作用域之外。你需要使用$scope.$evalAsync()或Firebase自己的AngularFire库来告诉Angular这个变化。

要使用$evalAsync,在你的最后一个else块中把$scope的变化包装成这样的函数:

    // admin logged in
    else {
      console.log("Logged in as admin");
      $scope.$evalAsync(function() {
         $scope.loggedin = true;
      });
    }

感谢Sherali Turdiyev对这个问题的回答。

 //authentication check
 var auth = new FirebaseSimpleLogin(ref, function (error, user) {
if (error) {
  // an error occurred while attempting login
  console.log(error);
}
// no user logged in
 else if (user === null) {
  console.log("Not logged in");
}
// normal user logged in
else if (user.id !== "47f0b82c-59d2-4bcd-8arc-ecb438eb0163") {
  console.log("You are logged in as normal user");
}
// admin logged in
else {
  console.log("Logged in as admin");
  $scope.loggedin = true;
  console.log("logging the scope.loggedin as admin " + $scope.loggedin);
}
// this resolved the issue
$scope.$apply();
 });

在阅读了$scope.$apply()的文档后,我发现这是摘要周期的一个问题。$scope.$apply()强制使用更新范围的摘要。此外,我发现我不应该在控制器中这样做。是时候把这个变成指令了。再次感谢他的帮助!