我创建了一个具有简单计算方法的服务。它需要一个值并将其平方。但是,我收到一个错误,说广场未定义,所以我猜测我传递的值不正确。
jsfid:http://jsfiddle.net/ADukg/19107/
var myApp = angular.module('myApp',[]);
//myApp.directive('myDirective', function() {});
//myApp.factory('myService', function() {});
/* function MyCtrl($scope) {
$scope.name = 'Superhero';
} */
myApp.controller('MyCtrl', ['$scope', function($scope, CalcService) {
var cheese = CalcService.square(2);
$scope.value = cheese;
}]);
myApp.service('CalcService', function(x){
this.square = function(x) {
var y = x*x;
return y;
}
});

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-controller="MyCtrl">
Hello, {{value}}!
</div>
&#13;
答案 0 :(得分:1)
我认为您错过了以适当的方式向控制器注入服务检查代码段
ON CREATE
答案 1 :(得分:1)
在这里看到你错过了CalcService
注入控制器初始化:
myApp.controller('MyCtrl', ['$scope', 'CalcService', function($scope, CalcService) {
var cheese = CalcService.square(2);
$scope.value = cheese;
}]);
答案 2 :(得分:1)
您错过了注入&#39; CalcService &#39;。
myApp.controller(&#39; MyCtrl&#39;,[&#39; $ scope&#39;,&#39; CalcService &#39;,功能($ scope,< strong> CalcService ){ }]);
答案 3 :(得分:0)
您的服务应该是:
myApp.service('CalcService', function(){
return {
square: function (x) {
var y = x*x;
return y;
}
}});
你应该在控制器中注入服务。