我的项目中有这个模板:
<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);
});
}
}
}
问题是当我运行页面时,我在开发人员工具中看到该函数被反复调用,它应该只显示用户信息。
我该如何做到这一点?
答案 0 :(得分:3)
每个摘要周期都会执行模板中的函数调用。只需在控制器中获取一次用户并将值分配给范围
auth.getUser(auth.currentUser()).getValue(function(value){
$scope.user = value;
});
并在您的模板中,而不是{{getUser()}}
{{user}}