我有一个选择,它在指令中调用一个控制器,当用户在下拉列表中选择一个值时,该控制器又从服务中调用一个函数。由于某种原因,我收到此错误:
类型错误:myService.getMessage 不是函数
因此,我创建了一个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) 这样的函数。
.service()
是一个接受 aname
和 a的函数function
来定义服务。它充当构造函数。我们可以在其他组件中注入和使用该特定服务:controllers
、directives
和filters
。
正确的语法:
app.service('myService', function(){
this.getMessage = function(){
alert("You are in myService!");
}
});
主要是它service
是一个构造函数。因此,我们可以使用this
关键字。在后台,此代码在实例化时调用Object.create()
service constructor function
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句