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函數試圖在用戶點擊提交按鈕之前檢查菜是否存在。

非常感謝

回答

0

您必須按正確的注射順序傳遞參數。改變這樣的

RegistrationController.$inject = ['checkDishService','$scope','$stateParams']; 

function RegistrationController(checkDishService, $scope, $stateParams) { 
0

參數順序應該總是同樣喜歡注射的訂單的訂單。

RegistrationController.$inject = ['checkDishService','$scope','$stateParams']; 

function RegistrationController(checkDishService, $scope, $stateParams) 

無論如何,我希望你有你的答案。

相關問題