我有以下角度应用(JSFiddle):
HTML
<form data-ng-app="jsApDemo" data-ng-controller="loginCtrl">
<label for="username">Username:</label>
<input type="text" id="username" data-ng-model="username" />
<br />
<label for="password">Password:</label>
<input type="password" id="password" data-ng-model="password" />
<br />
<button type="submit" data-ng-click="executeLogIn()">Log in</button>
<br />
<label for="authstatus">Authentication status:</label>
<input type="text" id="authstatus" readonly value="{{ authStatus }}" />
</form>
这是一个简单的登录表单,当用户单击提交时,我想在控制器loginCtrl
中执行一个函数。 loginCtrl
调用实现身份验证过程的服务。
的JavaScript
// the controller and its module
angular.module('jsApDemo', ['Core'])
.controller('loginCtrl', ['$scope', 'Connection', function ($scope, Connection) {
$scope.authStatus = 'unauthenticated';
$scope.executeLogIn = function () {
$scope.authStatus = 'authenticating';
Connection.sessionInitialize({
username: $scope.username,
password: $scope.password
}, function (error, status) {
if (!error) {
/***************************
* THIS LINE IS THE CULPRIT
***************************/
$scope.authStatus = status;
}
});
};
}]);
// the service and its module
angular.module('Core', []).service('Connection', function () {
this.sessionInitialize = function (options, callback) {
if (!options || !options.username || !options.password) {
callback('Username, and password are mandatory', null);
return;
}
setTimeout(function () {
callback(null, 'authenticated');
}, 1000);
};
});
在服务Connection
中,我使用了setTimeout
(注意:setTimeout
被用作异步调用的占位符。我的原始代码没有setTimeout
它调用了第三方库中的异步函数。我无法在代码中包含该调用的JSFiddle。所以我用setTimeout
替换了对该库的调用,以演示异步性质代码)。
当我尝试从回调函数中访问$scope
到Connection.sessionInitialize
时出现问题。调试后我发现以下行不起作用:
/***************************
* THIS LINE IS THE CULPRIT
***************************/
$scope.authStatus = status;
这似乎是一个范围问题,但此行之前的简单console.log($scope)
语句显示$scope
具有正确的值。但是,其#authstatus
属性绑定到value
的文本框$scope.authStatus
不会更改。
我做错了什么?
答案 0 :(得分:0)
setTimeout
是罪魁祸首,因为它运行回调,更新范围,但不会运行摘要周期,这使得双向数据绑定工作。请改用$timeout
服务:
$timeout(function () {
callback(null, 'authenticated');
}, 1000);
答案 1 :(得分:-1)
感谢@RahilWazir,我想出了一个解决方案:
/***************************
* THIS LINE IS THE CULPRIT
***************************/
$scope.$apply(function () {
$scope.authStatus = status;
});