【问题标题】:Function in angular keeps getting executed角度函数不断执行
【发布时间】:2015-10-28 00:22:21
【问题描述】:

我的项目中有这个模板:

<script type="text/ng-template" id="/challenges.html" ng-controller="ChallengeCtrl">

    <main>
    <h3 class="headingregister">Start challenge reeks</h3>

    {{getUser()}}

        <form name="startChallengesForm" ng-submit="getChallenges()">
            <button type="submit" class="btn btn-primary">Doe de challenges!</button>
        </form>
    </main>

</script>

getUser() 函数应该显示当前登录的用户信息。

这是 ChallengeCtrl:

app.controller('ChallengeCtrl', ['$scope', 'auth',
    function($scope, auth) {
        $scope.isLoggedIn = auth.isLoggedIn;
        $scope.currentUser = auth.currentUser;
        $scope.logOut = auth.logOut;

        $scope.getUser = function(){
            auth.getUser(auth.currentUser()).getValue(function(value){
                return value;
            });
        };

    }]);

这是 auth.getUser:

auth.getUser = function(usr){
            return{
                getValue: function(callback){
                    $http({
                        method: 'POST',
                        url:'http://groep6api.herokuapp.com/user',
                        headers: {'Content-Type': 'application/x-www-form-urlencoded'},
                        transformRequest: function(obj) {
                            var str = [];
                            for(var p in obj)
                                str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
                            return str.join("&");
                        },
                        data : {username: usr}
                    }).then(function (result) {
                        //return result.data;
                        callback(result.data);

                    });
                }
            }
        }

问题是当我运行页面时,我在开发人员工具中看到该函数被一遍又一遍地调用,它应该只显示用户信息。

我怎样才能做到这一点?

【问题讨论】:

    标签: angularjs


    【解决方案1】:

    模板中的函数调用在每个摘要循环中执行。只需在控制器中获取用户一次并将值分配给范围

    auth.getUser(auth.currentUser()).getValue(function(value){
        $scope.user = value;
    });
    

    在您的模板中,而不是 {{getUser()}}

    {{user}}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-02-09
      • 2022-06-12
      • 2020-11-13
      • 1970-01-01
      • 2020-05-09
      • 2021-05-02
      • 2020-06-20
      • 1970-01-01
      相关资源
      最近更新 更多