Parece que a me lo que eres realmente después es un Promise/Deferred: Editar
// for the purpose of this example let's assume that variables '$q' and 'scope' are
// available in the current lexical scope (they could have been injected or passed in).
function asyncGreet(name) {
var deferred = $q.defer();
setTimeout(function() {
// since this fn executes async in a future turn of the event loop, we need to wrap
// our code into an $apply call so that the model changes are properly observed.
scope.$apply(function() {
if (okToGreet(name)) {
deferred.resolve('Hello, ' + name + '!');
} else {
deferred.reject('Greeting ' + name + ' is not allowed.');
}
});
}, 1000);
return deferred.promise;
}
var promise = asyncGreet('Robin Hood');
promise.then(function(greeting) {
alert('Success: ' + greeting);
}, function(reason) {
alert('Failed: ' + reason);
);
: bien, esto es un examen sencillo plo de utilizar una promesa con un controlador y vinculante:
var app = angular.module('myApp', []);
app.controller('MyCtrl', function($scope, $q) {
var deferredGreeting = $q.defer();
$scope.greeting = deferredGreeting.promise;
/**
* immediately resolves the greeting promise
*/
$scope.greet = function() {
deferredGreeting.resolve('Hello, welcome to the future!');
};
/**
* resolves the greeting promise with a new promise that will be fulfilled in 1 second
*/
$scope.greetInTheFuture = function() {
var d = $q.defer();
deferredGreeting.resolve(d.promise);
setTimeout(function() {
$scope.$apply(function() {
d.resolve('Hi! (delayed)');
});
}, 1000);
};
});
jsFiddle de Trabajo: http://jsfiddle.net/dain/QjnML/4/
Básicamente la idea es que se puede obligar a la promesa y se cumplirá una vez que la respuesta asincrónico resuelve.
¿Puede proporcionar el ejemplo jsfiddle? –