[英]Angular doesn't work when defining a service and factory separately
I'm trying to write a simple angular service and a factory like below: 我正在尝试编写一个简单的角度服务和如下所示的工厂:
html: 的HTML:
<div ng-controller="mycontroller">
{{saycheese}}
</div>
Javascript Java脚本
var myApp = angular.module('myApp', []);
myApp.service('myservice', function() {
this.sayHello = function() {
return "from service";
};
});
myApp.factory('myfactory', function() {
return {
sayHello: function() {
return "from factory!"
}
};
});
//defining a controller over here
myapp.controller("mycontroller", ["myfactory", "myservice", function(myfactory, myservice) {
$scope.saycheese = [
myfactory.sayHello(),
myservice.sayHello()
];
}]);
But the JSFiddle
still just displays {{saycheese}}
instead of angular mapping the function. 但是
JSFiddle
仍然只显示{{saycheese}}
而不是对该函数进行角度映射。
Link to my fiddle: http://jsfiddle.net/PxdSP/3047/ 链接到我的小提琴: http : //jsfiddle.net/PxdSP/3047/
Can you point me where am I going wrong in this case ? 您能指出我在这种情况下哪里出问题了吗? Thanks.
谢谢。
You have several syntax errors in your code, and checking the console would have helped without questioning the SO. 您的代码中有几个语法错误,检查控制台将毫无疑问地对SO有所帮助。 Here's one possible way to write the controller ( demo ):
这是编写控制器( demo )的一种可能方法:
myApp.controller("mycontroller", ["$scope", "myfactory", "myservice",
function($scope, myfactory, myservice) {
$scope.saycheese = [
myfactory.sayHello(),
myservice.sayHello()
];
}]);
Apart from obvious fix myapp => myApp
(variable names are case-sensitive in JavaScript), $scope
should be passed into controller as an argument (and mentioned as its dependency if using arrayed - proper - form of controller definition, as you did) before you can access it. 除了明显的修复
myapp => myApp
(变量名称在JavaScript中区分大小写)之外,还应将$scope
作为参数传递给控制器(并像使用控制器那样使用数组化-正确的-形式作为其依赖关系提及)您才能访问它。 Otherwise you just get ReferenceError: $scope is not defined
exception when controller code is invoked. 否则,您将得到
ReferenceError: $scope is not defined
调用控制器代码时, ReferenceError: $scope is not defined
异常。
Couple things: 几件事情:
myapp.controller(...)
should be myApp.controller(...)
myapp.controller(...)
应该是myApp.controller(...)
$scope
in your controller. $scope
。 Fixed controller: 固定控制器:
myApp.controller("mycontroller", ["myfactory", "myservice", "$scope", function(myfactory, myservice, $scope) {
$scope.saycheese = [
myfactory.sayHello(),
myservice.sayHello()
];
}]);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.