0
我一直在網上搜索,但我找不到爲什麼我得到這個錯誤Angularjs從控制器調用服務功能
「checkDishService.checkDish是不是一個函數」
在從控制器調用服務功能時在控制檯中。
請幫忙!
這裏的服務:
(function() {
'use strict';
angular.module('public')
.service('checkDishService', checkDishService);
checkDishService.$inject = ['$http','$q', '$timeout']
function checkDishService($http,$q, $timeout) {
var service = this;
var items = [];
service.checkDish = function (shortName) {
var deferred = $q.defer();
$http.get('https://www.example.com/menu_items/'+shortName+'.json').success(function(data) {
service.items = data;
// Wait 2 seconds before returning
$timeout(function() {
deferred.resolve(data);
}, 400);
})
.error(function() {
deferred.reject("No such dish exists");
});
return deferred.promise;
};
}
})();
這裏的控制器:
(function() {
"use strict";
angular.module('restaurant', ['public'])
.controller('RegistrationController', RegistrationController);
RegistrationController.$inject = ['checkDishService','$scope','$stateParams'];
function RegistrationController($stateParams, checkDishService, $scope) {
var reg = this;
reg.checkDish = function(shortName){
if(shortName)
{
checkDishService.checkDish(shortName).then(function(res){
//the line before is the line throwing the error
});
}
}
}
})();
下面是從我所說的控制器形式:
<div ng-controller="RegistrationController as reg">
<form name='regForm' novalidate>
<input type="text" name="dish" placeholder="Favorite dish"
ng-model="reg.user.dish" ng-blur="reg.checkDish(reg.user.dish)"
required
minlength="1"
maxlength="4">
{{ reg.user.dish }}
<br>
<span ng-show="regForm.dish.$invalid.checkDish">No such dish exists.</span>
<button
ng-disabled="regForm.$invalid"
ng-click="reg.submit()">Submit</button>
</form>
</div>
的checkdish函數試圖在用戶點擊提交按鈕之前檢查菜是否存在。
非常感謝