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

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

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

我一辈子都弄不明白这里发生了什么。我已经查看了 angular 文档,阅读了有关 $scope、ngIf 和 ngShow 指令的信息,但没有任何内容适合我。我还查看了 this Whosebug post,它首先显示了此过程的来源。它似乎对那个线程中的人有用,但对我来说并不快乐。

这是我控制器中的代码:

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();
 });

reading the documentation for $scope.$apply() 之后我发现这是摘要循环的问题。 $scope.$apply() 强制更新范围的摘要。此外,我发现我不应该在控制器中这样做。是时候把它变成指令了。再次感谢他的帮助!