Angular中的变量作用域

4
我正在使用Angular构建一个简单的网页注册表格,将数据存储在Parse中。
controller('AppCtrl', ['$scope', '$rootScope', function($scope, $rootScope) {

    $rootScope.groupCreated = false;

    $scope.signUp = function(form) {

        var Group = Parse.Object.extend("AdminOrg");
        var group = new Group();
        group.set("groupName", form.name);
        group.set("groupPassword", form.password);

            group.save(null, {
                  success: function(data) {
                      $rootScope.groupCreated = true;

                  },
                  error: function(data, error) {
                    alert(error.message);
                  }
                });
      };
}]);

我正在使用$rootScope.groupCreated在我的HTML中,一旦成功函数被调用,隐藏注册表格并显示“小组创建成功”的消息。该值已经成功地更改为true,但是它没有改变HTML视图。我正在使用以下代码来隐藏和显示两个div:

ng-hide="$rootScope.groupCreated"
ng-show="$rootScope.groupCreated"

我在HTML中是否不正确地访问了$rootScope?


1
只需使用 ng-hide="groupCreated" - vp_arth
@vp_arth 很好的发现。 - dfsq
太棒了,谢谢你。 - Andrew
1个回答

5

Angular并不知道您已经在作用域上做出了更改,因为解析函数不是Angular生态系统的一部分,所以它们不包含在摘要检查循环中。只需使用$apply方法手动通知Angular即可:

group.save(null, {
    success: function (data) {
        $rootScope.groupCreated = true;
        $rootScope.$apply();
    },
    error: function (data, error) {
        alert(error.message);
    }
});

还有一个问题,感谢vp_arth在评论中指出:您不应该在Agnular表达式中使用$rootScope前缀:

ng-show="groupCreated"

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接