cra*_*204 6 javascript angularjs angularjs-scope
嗨,我正在尝试使用import.io刮取一些足球比分.我设法让他们的JS使用API并提供数据.问题是它必须位于控制器内部的私有范围内,因为我无法对其进行重复操作.
任何人都可以告诉我为什么,并且如果有人对Scope有一个很好的指导可能会更有用.
latestScores.controller('ScoresController', function ($scope) {
$scope.pots = [];
var io2 = new importio("XXX", "XXXXXX[API KEY]XXXXXXXX", "import.io");
io2.connect(function (connected) {
if (!connected) {
console.error("Unable to connect");
return;
}
var data;
var callback = function (finished, message) {
if (message.type == "DISCONNECT") {
console.error("The query was cancelled as the client was disconnected");
}
if (message.type == "MESSAGE") {
if (message.data.hasOwnProperty("errorType")) {
console.error("Got an error!", message.data);
} else {
data = message.data.results;
}
}
if (finished) {
pots = data;
console.log(pots); /* This gives me an object */
}
}
io2.query({
"connectorGuids": [
"d5796d7e-186d-40a5-9603-95569ef6cbb9"],
}, callback);
});
console.log($scope.pots); /* This gives me nothing */
});
Run Code Online (Sandbox Code Playgroud)
angularjs 数据绑定无法知道您何时在第三方库的回调中更新范围。
在您的回调中,执行以下操作:
$scope.pots = dataReceived
$scope.$apply();
Run Code Online (Sandbox Code Playgroud)
如果你想跳过调用 $scope.apply(),你需要使用 Angular 自己的 Promise 模块(称为 $q)并将你的 api 调用包装到服务中。
另外,如果您的 API 是基于 websocket 的,您应该订阅 $scope.on('$destroy') 事件,以便在控制器消失时断开与您的 api 的连接。