我有一个适用于工厂和服务的代码:我很困惑在什么情况下我需要使用哪个代码。
此代码my value
在 console.log 中使用service
var mod = angular.module("MyModule", []);
mod.service("myService", function() {
console.log("this is service");
return {
getvalue : function() {
return "My value";
}
};
});
mod.controller("MyController", function(myService) {
console.log("MyController - myFactory: " + myService.getvalue());
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="MyModule">
<div ng-controller="MyController"></div>
</div>
我刚刚更改 mod.service()
的这段代码mod.factory()
,其余代码相同,它my value
在 console.log 中使用factory
var mod = angular.module("MyModule", []);
mod.service("myFactory", function() {
console.log("this is Factory");
return {
getvalue : function() {
return "My value";
}
};
});
mod.controller("MyController", function(myFactory) {
console.log("MyController - myFactory: " + myFactory.getvalue());
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="MyModule">
<div ng-controller="MyController"></div>
</div>