【问题标题】:Binding issue in AngularJSAngularJS 中的绑定问题
【发布时间】:2015-09-05 20:19:57
【问题描述】:

我正在尝试从 http 获取请求进行绑定。 http get 返回真或假。我已经测试了 get 并且它正在正确返回。当我运行下面的代码时,它也会正确显示警报(1111)。但是,当我尝试更改按钮文本时,什么也没有出现!我已经尝试了我所知道的一切。任何建议都会有所帮助。

Post.js

myApp.controller('FollowController', ['$scope', '$http', function($scope, $http) {

    var status = "";

        $http.get('/Home/CheckFollower?idToFollow=' + profileId + '&followerId=' + currentUserId).
            success(function(data) {
                //check if it is a follower

                if (data) {
                    // Not following - Show unfollow
                    alert("1111");
                    $scope.statusMessage = data;


                } else {
                    //Following - show Follow

                    $scope.statusMessage = data;
                }

            })
            .error(function(data, status) {
                console.log(data);
            });

}]);

HTML

   <span style="float: right" ng-controller="FollowController as follow">
                        <button type=" button" class="btn btn-success" onclick="location.href='@Url.Action("Follow", "Home", new { idToFollow = ViewBag.ProfileId, followerId = User.Identity.GetUserId() })'">
                            {{ follow.statusMessage }}</button>

                        </span>

【问题讨论】:

    标签: javascript angularjs angularjs-scope angularjs-controller angularjs-controlleras


    【解决方案1】:

    您应该将变量绑定到this 而不是$scope,因为您正在使用controllerAs approach

    控制器

    myApp.controller('FollowController', ['$scope', '$http',
        function($scope, $http) {
            var status = "";
            var follow = this;
            $http.get('/Home/CheckFollower?idToFollow=' + profileId + '&followerId=' + currentUserId).
            success(function(data) {
              //check if it is a follower
              if (data) {
                // Not following - Show unfollow
                alert("1111");
                follow.statusMessage = data;
              } else {
                //Following - show Follow
                follow.statusMessage = data;
              }
            })
            .error(function(data, status) {
              console.log(data);
            });
        }
    ]);
    

    【讨论】:

    • 啊!谢谢!成功了!
    • @JeremyLewallen 很高兴帮助你..谢谢 :)
    • 只是好奇,在这个解决方案之前,我尝试创建一个函数并使用返回。但是,它一遍又一遍地运行该功能。你知道它为什么会这样做吗?
    • @JeremyLewallen 我没有让你明白这一点......关于你在说什么功能?
    • 我创建了一个名为 checkFollower() 的函数。它与上面的逻辑相同,只是它使用了 return。当我使用角度绑定 {{ checkFollower() }} 调用该函数时,它停留在无限循环中。只是好奇你是否知道为什么会发生这种情况
    猜你喜欢
    • 2019-01-26
    • 1970-01-01
    • 2018-03-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-08
    相关资源
    最近更新 更多