[英]Angular doesn't work when defining a service and factory separately
我正在尝试编写一个简单的角度服务和如下所示的工厂:
的HTML:
<div ng-controller="mycontroller">
{{saycheese}}
</div>
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()
];
}]);
但是JSFiddle
仍然只显示{{saycheese}}
而不是对该函数进行角度映射。
链接到我的小提琴: http : //jsfiddle.net/PxdSP/3047/
您能指出我在这种情况下哪里出问题了吗? 谢谢。
您的代码中有几个语法错误,检查控制台将毫无疑问地对SO有所帮助。 这是编写控制器( demo )的一种可能方法:
myApp.controller("mycontroller", ["$scope", "myfactory", "myservice",
function($scope, myfactory, myservice) {
$scope.saycheese = [
myfactory.sayHello(),
myservice.sayHello()
];
}]);
除了明显的修复myapp => myApp
(变量名称在JavaScript中区分大小写)之外,还应将$scope
作为参数传递给控制器(并像使用控制器那样使用数组化-正确的-形式作为其依赖关系提及)您才能访问它。 否则,您将得到ReferenceError: $scope is not defined
调用控制器代码时, ReferenceError: $scope is not defined
异常。
几件事情:
myapp.controller(...)
应该是myApp.controller(...)
$scope
。 固定控制器:
myApp.controller("mycontroller", ["myfactory", "myservice", "$scope", function(myfactory, myservice, $scope) {
$scope.saycheese = [
myfactory.sayHello(),
myservice.sayHello()
];
}]);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.