我的 Controller 和服务上有这样的(都在单独的文件中):
.controller('authCtrl',['$scope','MyConnect',function($scope,MyConnect){
/***************Testing Area******************/
console.log("connecting");
MyConnect.initialize();
$scope.myID = ??? //I want this to be updated
}
.factory('MyConnect', ['$q', function($q) {
var miconnect = {
initialize: function() {
this.bindEvents();
},
bindEvents: function() {
document.addEventListener('deviceready', this.onDeviceReady, false);
},
onDeviceReady: function() {
thirdPartyLib.initialize();
miconnect.applyConfig();
},
applyConfig: function() {
if (thirdPartyLib.isReady()) {
//I want in here to update $scope.myID in controller and reflect the changes in UI textbox
//$scope.myID = thirdPartyLib.id(); //something like this will be good
}
else {
}
}
}
return miconnect;
}])
所以,我不确定如何更新 $scope.myID (这是一个文本框)。我不知道如何在事件监听器之后进行回调。通常如果 ajax 我可以使用 .then 来等待数据到达。
主要的是,我需要使用第三方库(专有),并且根据指南,在设备准备好后调用thirdPartyLib.initialize(),然后在实际调用该函数之前检查是否该thirdPartyLib.isReady()检索 id。
最佳答案
在服务准备就绪之前,您无法直接分配给 $scope.myID
。您需要以某种方式提供回调,将正确的值分配给您的 $scope
模型。您可以通过让服务在准备就绪时返回某个 Promise 来实现此目的,或者通过从服务发出事件来实现此目的。我将给出最后一个选项的示例。根据此 thirdPartyLib
与 Angular
的集成程度,您可能需要启动 Angular
才能正确应用范围。这里我使用$scope.$evalAsync
。您还可以返回一个将使用 id
解析的 Promise,而不是像使用 ajax 库那样直接传递回调以便 .then
。
此外,如果 thirdPartyLib
特别糟糕,并且它的初始化是异步的,并且它没有为您提供任何回调/ promise /事件驱动的指示符,表明它已准备好,您可能需要
.controller('authCtrl', ['$scope', 'MyConnect',
function($scope, MyConnect) {
console.log("connecting");
// my connect should probably just `initialize()` on it's own when it's created rather than relying on the controller to kick it.
MyConnect.initialize();
MyConnect.whenID(function(id) {
// $evalAsync will apply later in the current $digest cycle, or make a new one if necessary
$scope.$evalAsync(function(){
$scope.myID = id;
});
})
}
])
.factory('MyConnect', ['$q', '$rootScope'
function($q, $rootScope) {
var miconnect = {
...,
onDeviceReady: function() {
thirdPartyLib.initialize();
miconnect.applyConfig();
/* Also, if the `thirdPartyLib` is particularly sucky, AND if it's initialize is asynchronous,
* AND it doesn't provide any callback/promise/event driven indicator that it's ready,
* you may need to hack some kind of `setTimeout` to check for when it is actually `isReady`. */
// ok, listeners can do stuff with our data
$rootScope.$emit('MyConnect.ready');
},
whenID: function(callback) {
if (thirdPartyLib.isReady()) {
callback(thirdPartyLib.id);
} else {
var unregister = $rootScope.$on('MyConnect.ready', function() {
// unregister the event listener so it doesn't keep triggering the callback
unregister();
callback(thirdPartyLib.id);
});
}
}
}
return miconnect;
}
])
关于javascript - AngularJS 如何在事件监听器后更新 View /范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30472292/