我是角色新手并试图设置登录系统。我有一些按钮'设置为在单击按钮时将用户重定向到用户facebook / google帐户的Oauth提示。我的问题是记录用户的功能是在页面日志上立即执行,而不是在单击按钮时执行。
我很确定根源在于JS对象的工作方式,但我仍在学习angularjs,这有点令人困惑。
我相信将函数放在$ scope上会立即执行它们,但我不知道如何将它们暴露给ng-click。
有人可以帮我解决如何让按钮按预期工作吗?
模板:
<ion-view title="Account">
<ion-nav-buttons side="right">
<button menu-toggle="right" class="button button-icon icon ion-navicon"></button>
</ion-nav-buttons>
<ion-content class="has-header padding">
<h1 ng-click="google_login()">Log in with Google</h1>
<h1 ng-click="fb_login()">Log in with Facebook</h1>
<h1 ng-click="dev_login()">Dev login</h1>
<div id="logs"></div>
<form class="list">
<label class="item item-input">
<input type="text" placeholder="Username" ng-model="user.username" required>
</label>
<label class="item item-input">
<input type="password" placeholder="Password" ng-model="user.password" required>
</label>
<div class="padding">
<button class="button button-block button-stable" ng-click="email_authenticate()">Login</button>
</div>
</form>
</ion-content>
</ion-view>
控制器:
.controller('AccountCtrl', function($scope, $state, Authentication) {
$scope.dev_login = Authentication.dev_authenticate(); //executes immediately
$scope.fb_login = Authentication.fb_authenticate(); //executes immediately
$scope.google_login = Authentication.google_authenticate(); //executes immediately
$scope.email_login = Authentication.email_authenticate(); //executes immediately
$scope.logout = Authentication.logout();
});
这些在services.js中定义:
.factory('Authentication', function ($http) {
return {
authenticate: function () {
return $http({
url: 'https://api.squawkfinace.com/authenticate',
method: 'post'//,
//data: {facebook_authtoken: key}
});
},
fb_authenticate: function () {
return $.oauth2({
//Oauth details
}, function (token, response) {
localStorage.setItem("LoggedInAccount", JSON.stringify({'platform': 'facebook', 'token': token}));
console.log(token);
$state.transitionTo("app.notifications");
}, function (error, response) {
// do something with error object
});
},
google_authenticate: function () {
return $.oauth2({
//oauth details
}, function (token, response) {
localStorage.setItem("Account", JSON.stringify({'platform': 'google', 'key': token}));
}, function (error, response) {
// do something with error object
$("#logs").append("<p class='error'><b>error: </b>" + JSON.stringify(error) + "</p>");
$("#logs").append("<p class='error'><b>response: </b>" + JSON.stringify(response) + "</p>");
});
},
dev_authenticate: function () {
return null;
},
email_authenticate: function () {
return null;
},
logout: function () {
localStorage.removeItem("Account");
return null;
}
}
});
答案 0 :(得分:2)
这是因为你实际上正在执行这些功能
$scope.dev_login = Authentication.dev_authenticate();
应该是
$scope.dev_login = Authentication.dev_authenticate;
第一个场景执行该函数并将结果分配给$ scope。您想要为该函数分配引用。