我在填充到我的视图中的服务中获取数据时遇到问题.我有一个如此定义的服务
app.factory('nukeService', function($rootScope, $http) {
var nukeService = {};
nukeService.nuke = {};
//Gets the list of nuclear weapons
nukeService.getNukes = function() {
$http.get('nukes/nukes.json')
.success(function(data) {
nukeService.nukes = data;
});
return nukeService.nukes;
};
return nukeService;
});
Run Code Online (Sandbox Code Playgroud)
和我的控制器
function NavigationCtrl($scope, $http, nukeService){
/*$http.get('nukes/nukes.json').success(function(data) {
$scope.nukes = data;
});*/
$scope.nukes = nukeService.getNukes();
}
Run Code Online (Sandbox Code Playgroud)
如果我使用来自控制器的$ http.get数据填充正常,但是,如果我尝试从服务中调用数据,我什么也得不到.我知道查询是异步的,但是我很难理解在返回数据后如何填充$ scope变量.我可以使用$ rootscope来广播一个事件并在控制器中监听它,但这似乎不是完成此任务的正确方法.我真的很感激有关如何以正确的方式做到这一点的任何建议.
AngularJS文档说:
$ q promises被临界引擎识别为angular,这意味着在模板中,您可以将附加到范围的promise视为结果值.
那么有人可以解释一下这个小提琴不起作用的原因吗?无法更改文本字段值.但是,分配$ http服务返回到范围字段的承诺就像魅力一样.
控制器:
function MyController($scope, $q, $timeout) {
this.getItem = function () {
var deferred = $q.defer();
deferred.resolve({
title: 'Some title'
});
return deferred.promise;
};
$scope.item = this.getItem();
}
Run Code Online (Sandbox Code Playgroud)
HTML:
<input type="text" ng-model="item.title">
Run Code Online (Sandbox Code Playgroud) 我在AngularJS服务中包装一个慢的WebSockets服务器,然后从我的控制器调用该服务.如果我将回调链接到回调到回调,一切正常,任何UI异步更新.
当我尝试用来$q.defer()清理那些混乱的回调时,似乎我的延迟永远不会被调用.我熟悉Python扭曲的延迟概念,所以我认为概念上一切都应该有效 - 但事实并非如此.
这是我能想到的最短的例子,使用setTimeout函数模拟慢速WebSockets服务器.
<!doctype html>
<html ng-app="beta">
<head>
<title>Beta</title>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.4/angular.min.js"></script>
<script>
var beta = angular.module('beta', []);
var BetaCtrl = function ($scope, betaServ) {
$scope.button = function () {
serv_result = betaServ.slow();
console.log(serv_result);
serv_result.then(function (result) {
console.log('callback finished');
});
}
}
beta.service('betaServ', function($q) {
this.slow = function () {
d = $q.defer()
setTimeout(function () {
console.log('before resolve');
d.resolve();
console.log('after resolve');
}, 2000);
return d.promise;
}
});
</script>
</head>
<body>
<div ng-controller="BetaCtrl">
<button …Run Code Online (Sandbox Code Playgroud)