【问题标题】:$scope not working inside a function$scope 在函数中不起作用
【发布时间】:2015-10-01 18:50:52
【问题描述】:

我有以下代码。我在 html 上使用 ng-show 并尝试在 angular 函数上对其进行操作,但它不起作用。我不确定在函数内更改 $scope 值的正确方法。

在 Angular 上,

app.controller("ControlController", function($scope, $http, $location) {

    $scope.badRequest = false;

    $scope.login = function() {

        $http.post('/login', { 

            email: $scope.email,

            password: $scope.password

            }).then function(res) {

                $location.path('/');

            },function(err) {

                 $scope.badRequest = true;

                 console.log($scope.badRequest); // this will print true.

                 //But this  does not change the $scope.badRequest on DOM. 

            });

      };

});

在翡翠上,我有

.incorrect-container(ng-show='badRequest')

有什么帮助吗?

【问题讨论】:

  • 您确定正在设置该变量吗?如果你在它前面放一个日志语句,它会被命中吗?
  • @CharlieS -- 这应该没什么区别-$http 是一个角度模块,会触发一个摘要循环。 (并且您不希望 $apply() 在随机位置浮动) - 它仅在提供的问题中列为答案,因为 $.getJSON 不会触发摘要循环......即使那样,仍然不推荐。
  • 以上ngShow是否在你的控制器范围内?
  • 您的 Jade 生成的 HTML 看起来如何?你确定 html 在你的控制器的定义中吗?
  • 我们可以得到你的 html 输出吗?也许 ng-show 不在控制器的范围内

标签: javascript angularjs pug ng-show


【解决方案1】:

不确定是不是你复制错了,但是“.then”是一个函数调用。应该是

$scope.login = function() {
    $http.post('/login', { 
        email: $scope.email,
        password: $scope.password
    })
    .then(function(data) {
        // do stuff in here with successfully returned data
    })
    .catch(function(err) {
        $scope.badRequest = true;
    });
};

按照你的方式,.then 甚至没有被调用。此外,当我按原样运行它时,我遇到了语法错误。你没收到吗?

【讨论】:

    猜你喜欢
    • 2014-05-14
    • 1970-01-01
    • 2017-07-27
    • 2016-02-26
    • 2014-12-14
    • 1970-01-01
    • 2016-04-11
    • 1970-01-01
    • 2012-09-10
    相关资源
    最近更新 更多