Angular: Empty Fiddle
http://angularjs.org/
HTML
<script src="http://code.angularjs.org/angular-1.0.1.js"></script>
<div ng-controller="MyCtrl">
<input type="text" ng-model="obj.value"/><br/>
resolve deferred <input type="radio" ng-model="result" value="1"/><br/>
reject deferred <input type="radio" ng-model="result" value="0"/><br/>
<ul>
<li ng-repeat="r in results">{{r}}</li>
</ul>
</div>
JavaScript
var myApp = angular.module('myApp',[])
.factory('MyService', ['$q' ,'$timeout',function($q, $timeout) {
return new function() {
this.update = function(obj, resolve) {
var req = $q.defer();
$timeout(function(){
if (resolve === "1") {
console.log('successing', resolve == 'false');
req.resolve('success');
}
else {
req.reject('error');
}
}, 500);
return req.promise;
}
}
}]);
function MyCtrl($scope, MyService) {
$scope.obj = {value: "foo"};
$scope.results = [];
$scope.result = "1";
$scope.$watch('obj.value',function(val, oldVal) {
if (val === oldVal) return;
MyService.update($scope.obj, $scope.result).then(function(response){
$scope.results.push(response);
}, function(response) {
$scope.obj.value = oldVal;
$scope.results.push(response);
});
});
}