我想从https://docs.angularjs.org/api/ng/service/$q运行promises示例,这是我的代码:
angular.module('testControllers').controller('testCtrl', ['$scope', '$q', function($scope, $q) {
function asyncGreet(name) {
// perform some asynchronous operation, resolve or reject the promise when appropriate.
return $q(function(resolve, reject) {
setTimeout(function() {
if (true) {
resolve('Hello, ' + name + '!');
} else {
reject('Greeting ' + name + ' is not allowed.');
}
}, 1000);
});
}
var promise = asyncGreet('Robin Hood');
promise.then(function(greeting) {
console.log('Success: ' + greeting);
}, function(reason) {
console.log('Failed: ' + reason);
});
}
Chrome一直告诉我: TypeError:object不是函数
我对样本做了什么错误?
答案 0 :(得分:2)
请确保您至少在版本1.3中使用angularjs,请参阅下面的演示
var app = angular.module('app', [])
.controller('firstCtrl', function($scope, $q) {
$scope.ver = angular.version.full;
$scope.message = ""
$scope.asyncGreet = function (name) {
// perform some asynchronous operation, resolve or reject the promise when appropriate.
return $q(function(resolve, reject) {
setTimeout(function() {
if (true) {
resolve('Hello, ' + name + '!');
} else {
reject('Greeting ' + name + ' is not allowed.');
}
}, 1500);
});
}
promise = $scope.asyncGreet('Robin Hood');
promise.then(function(greeting) {
alert('Success: ' + greeting);
}, function(reason) {
alert('Failed: ' + reason);
});
});

<script src="http://cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.0/angular.js"></script>
<div ng-app="app">
<div ng-controller="firstCtrl">
Angular ver: {{ver}}
</div>
</div>
&#13;
答案 1 :(得分:-2)
请参阅下面的示例
var app = angular.module('app', []);
app.controller('fCtrl', function($scope, $q) {
$scope.test = true;
function asyncGreet(name, test) {
// perform some asynchronous operation, resolve or reject the promise when appropriate.
var deffered = $q.defer();
setTimeout(function() {
if (test) {
deffered.resolve('Hello, ' + name + '!');
} else {
deffered.reject('Greeting ' + name + ' is not allowed.');
}
}, 1000);
return deffered.promise;
}
$scope.action = function() {
var promise = asyncGreet('Robin Hood', $scope.test);
promise.then(function(greeting) {
alert('Success: ' + greeting);
}, function(reason) {
alert('Failed: ' + reason);
});
};
$scope.action();
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app">
<div ng-controller="fCtrl">
<input type="radio" ng-model="test" ng-value="true" ng-change="action()" />TRUE
<input type="radio" ng-model="test" ng-value="false" ng-change="action()" />FALSE
</div>
</div>