在我的 Angular 应用程序中,我有一个消息服务来显示我的应用程序的信息、加载和错误消息。它看起来像这样:
module.factory('msgSvc', function(){
var current_message = '';
return {
message: function(){
return current_message;
},
setMessage: function(msg){
console.log('setting message: '+ msg);
current_message = msg;
},
clear: function(){ current_message = null; current_style = null}
}
});
在我看来我有
<span class="pull-left label label-warning" >{{ msg.message() }}</span>
我有一个登录控制器,当用户提交表单时,我想在发送 ajax 登录时显示“正在登录...”消息。如果出现错误,则显示错误消息。这是我的代码:
function LoginCtrl($scope, $http, msgSvc) {
[...]
$scope.login = function(creds) {
console.log(creds);
msgSvc.setMessage('Logging in...');
$http.post('http://...',creds)
.success(function(data){
console.log(data);
[...]
msgSvc.clear();
$location.path('/');
})
.error(function(data, status){
console.log(status);
msgSvc.setMessage('Wrong username or password.');
});
};
}
login()
由提交表单调用,Logging in...
即使调用了函数也不会显示(它出现在控制台中)。但出现错误消息。
难道我做错了什么?
编辑:登录表单
<form class="form">
<input type="text" placeholder="Username" ng-model="loginCreds.username" required />
<input type="password" placeholder="Password" ng-model="loginCreds.password" required />
<button ng-click="login(loginCreds)">Login</button>
</form>
编辑2
如果它改变任何东西,在服务和实际代码中有许多控制器设置消息,显示消息的控制器($scope.msg
设置变量的位置)与设置消息的控制器不同。
function BodyCtrl($scope, msgSvc) {
$scope.msg = msgSvc;
}