2017-05-05 56 views
0

我有一個select在指令中調用控制器,當用戶在下拉列表中選擇一個值時,該指令又調用服務中的函數。出於某種原因,我得到這個錯誤:Angularjs TypeError:不是功能問題

TypeError: myService.getMessage is not a function

所以我創建了一個plunker拉出的基本功能,我能夠用一個控制器來調用一個基本服務複製的錯誤,但我仍然還沒有解決它。

下面是代碼:

HTML代碼:

<!DOCTYPE html> 
    <html ng-app="app"> 

     <head> 
     <meta charset="utf-8" /> 
     <title>AngularJS Plunker</title> 
     <script>document.write('<base href="' + document.location + '" />');</script> 
     <link rel="stylesheet" href="style.css" /> 
     <script data-require="[email protected]" src="https://code.angularjs.org/1.2.22/angular.js" data-semver="1.2.22"></script> 
     <script src="script.js"></script> 
     </head> 

     <body ng-controller="MainCtrl"> 
     <select ng-options="option for option in listOfOptions" 
       ng-model="selectedItem" 
       ng-change="selectedItemChanged()"> 
     </select> 

     <p>This is the selected Item from the model: <b>{{selectedItem}}</b></p> 
     <p>This is the result of the ng-change function: <b>{{calculatedValue}}</b></p> 

    </body> 

腳本代碼:

var app = angular.module('app', []); 

app.controller('MainCtrl', function($scope, myService) { 
    $scope.listOfOptions = ['One', 'Two', 'Three']; 

    $scope.selectedItemChanged = function(){ 
    $scope.calculatedValue = 'You selected number ' + $scope.selectedItem; 
    //Call the service. 
    myService.getMessage(); 
    } 
}); 

app.service('myService', function(){ 
    function getMessage(){ 
    alert("You are in myService!"); 
    } 
}); 

我見過很多的不同,多少更多比較這種類型的錯誤的授權代碼,但我不明白是什麼造成這種情況?任何想法,以正確的方式來做到這一點?

我想要做的是從控制器或指令使用像myService.mySearch(param1)這樣的函數。

回答

1

​​是一個函數,它接受一個namefunction定義service.It充當構造function.We可以注入,並使用該特定的服務在其它組分:controllersdirectivesfilters

正確的語法:

app.service('myService', function(){ 
    this.getMessage = function(){ 
    alert("You are in myService!"); 
    } 
}); 

主要的是service是一個構造函數。因此,我們可以使用this關鍵字。在後臺,此代碼在實例化時調用Object.create()與服務constructor function

+0

謝謝!所以如果我在服務中調用一個函數,就像函數mySearch(param1){this.mySearch = function(param1){// do something}}爲什麼這不起作用? –

+0

它應該工作'app.service('myService',function(){this.mySearch = function(param1){// do something}});' –

+0

不,我沒有正確解釋它。這確實有用,但是當我在我的商業代碼中從控制器中調用我的服務時,我仍然得到原始錯誤。 –

3

錯誤的服務代碼,應該是:

app.service('myService', function() { 
    this.getMessage = function() { 
    alert("You are in myService!"); 
    } 
}); 
0

除了Fetra R「的回答,

廠是在所有情況下大多較好。當你有需要在不同控制器中實例化的構造函數時,可以使用它。服務是一種Singleton對象。對於所有控制器,來自服務的對象返回將相同。

因此,它就像一個單身物體,你必須聲明它爲胎兒R的答案,或者你可以寫一個工廠。

app.factory('myService', function() { 
    return { 
    getMessage: function() { 
     alert("You are in myService!"); 
    } 
    } 
}); 

並以相同的方式使用它。