我有一個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)這樣的函數。
謝謝!所以如果我在服務中調用一個函數,就像函數mySearch(param1){this.mySearch = function(param1){// do something}}爲什麼這不起作用? –
它應該工作'app.service('myService',function(){this.mySearch = function(param1){// do something}});' –
不,我沒有正確解釋它。這確實有用,但是當我在我的商業代碼中從控制器中調用我的服務時,我仍然得到原始錯誤。 –