Javascript AngularJS控制器中回调函数的作用域问题
我有下面的angular应用程序(): HTMLJavascript AngularJS控制器中回调函数的作用域问题,javascript,angularjs,angularjs-scope,ng-controller,Javascript,Angularjs,Angularjs Scope,Ng Controller,我有下面的angular应用程序(): 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
<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>
在服务连接中
,我使用了设置超时
(注意:setTimeout
被用作异步调用的占位符。我的原始代码没有setTimeout
。它调用了第三方库中的异步函数。我无法使用代码中包含的调用创建JSFIDLE。因此,我将对该库的调用替换为对d的setTimeout
)演示代码的异步性质)
当我尝试从回调函数中访问$scope
到连接时出现问题。会话初始化
。调试后,我发现以下行不起作用:
/***************************
* THIS LINE IS THE CULPRIT
***************************/
$scope.authStatus = status;
这似乎是一个范围问题,但此行前面的一个简单的console.log($scope)
语句表明$scope
具有正确的值。但是,文本框#authstatus
的值
属性绑定到$scope.authstatus
不会更改
我做错了什么?多亏了@RahilWazir,我想出了一个解决方案:
/***************************
* THIS LINE IS THE CULPRIT
***************************/
$scope.$apply(function () {
$scope.authStatus = status;
});
setTimeout
是罪魁祸首,因为它运行回调,更新作用域,但不运行摘要循环,从而使双向数据绑定工作。请改用$timeout
服务:
$timeout(function () {
callback(null, 'authenticated');
}, 1000);
您需要在
$scope.$apply(函数(){…})中设置$scope
属性
,因为您在angularThank之外设置了authStatus
属性,所以请阅读。谢谢@RahilWazir:但您能再解释一下吗?我不确定如何在这个例子中使用$scope.$apply
。如果您使用而不是setTimeout,那么您就不需要调用$apply。@GruffBunny:setTimeout的使用只是为了演示pupo这实际上是一个web请求。但是感谢$timeout
@RahilWazir上的提示(至少对我来说不是)。因为setTimeout
被用作异步调用的占位符。它只是用来显示代码的异步性质。所以(至少对我来说),它不起作用。Define不起作用?你注入了$timeout
服务吗?它与setTimeout
@RahilWazir具有相同的用途:我的原始代码没有setTimeout
。它调用了第三方库中的异步函数。我无法使用代码中包含的调用创建JSFIDLE。因此我将对该库的调用替换为setTimeout
,以演示代码的异步性质。因此在本例中,$timeout
对我来说是无用的,因为我想要的不是超时。我希望这个解释很清楚?谢谢您的回答,但是setTimeout
被用作异步调用的占位符调用。我的原始代码没有setTimeout
。它调用了第三方库中的异步函数。我无法使用代码中包含的调用创建JSFIDLE。因此,我用setTimeout
替换了对该库的调用,以演示代码的异步性质。因此在本例中,$timeout
对我来说不是一个解决方案。很抱歉造成混淆。不用担心。它不是我的-1:)顺便说一句-移动$apply以在服务中包装回调,然后使用$rootScope。$apply。这样,您就不必在使用此服务的每个控制器中使用$scope.$apply。
$timeout(function () {
callback(null, 'authenticated');
}, 1000);