यह करने के लिए की तरह लग रहा
// 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);
);
संपादित करें:: मुझे क्या तुम सच में करने के बाद कर रहे हैं एक Promise/Deferred है ठीक है, यहाँ एक सरल परीक्षा है एक नियंत्रक के साथ एक वादा का उपयोग कर और बाध्यकारी की मिसाल:
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: http://jsfiddle.net/dain/QjnML/4/
मूल रूप से विचार है कि आप वादा बाध्य कर सकते हैं और एक बार async प्रतिक्रिया यह निराकरण यह पूरा किया जाएगा है।
क्या आप jsfiddle उदाहरण प्रदान कर सकते हैं? –