许多角度示例使用简单的全局函数。角度种子和角度使用更复杂的编码风格。以下是stackoverflow / jsbin:http://jsbin.com/lucit/8/edit
中一个简单样式示例的示例var app = angular.module( 'app', [] );
var MyFunc = function() {
this.name = "default name";
this.$get = function() {
this.name = "new name"
return "Hello from MyFunc.$get(). this.name = " + this.name;
};
return "Hello from MyFunc(). this.name = " + this.name;
};
// returns the actual function
app.service( 'myService', MyFunc );
// returns the function's return value
app.factory( 'myFactory', MyFunc );
// returns the output of the function's $get function
app.provider( 'myProv', MyFunc );
function MainCtrl( $scope, myService, myFactory, myProv ) {
$scope.serviceOutput = "service = "+ JSON.stringify(myService);
$scope.factoryOutput = "factory = " + myFactory;
$scope.providerOutput = "provider = " + myProv;
}
以下是尝试以角度种子模块样式重写一个简单示例:http://jsbin.com/hitun/4/edit
var MyFunc = function() {
this.name = "default name";
this.$get = function() {
this.name = "new name"
return "Hello from MyFunc.$get(). this.name = " + this.name;
};
return "Hello from MyFunc(). this.name = " + this.name;
};
angular.module('app', [
'app.controllers',
'app.services'
]);
angular.module('app.services',[])
.factory('MainData', MyFunc)
.service('MainData', MyFunc)
.provider('MainData', MyFunc));
angular.module('app.controllers',[])
.controller('MainCtrl', [function($scope, myService, myFactory, myProv){
$scope.serviceOutput = "service = "+ JSON.stringify(myService);
$scope.factoryOutput = "factory = " + myFactory;
$scope.providerOutput = "provider = " + myProv;
}]);
无论我如何尝试调整语法,我都会遇到错误。
答案 0 :(得分:2)
以下行的括号太多:
.provider('MainData', MyFunc));
将其更改为:
.provider('myProv', MyFunc);
工厂,服务和提供商均名为MainData
,但在MainCtrl
您尝试注入myService
,myFactory
,myProv
。< / p>
重命名:
angular.module('app.services', [])
.factory('myFactory', MyFunc)
.service('myService', MyFunc)
.provider('myProv', MyFunc);
您的控制器定义使用内联数组表示法。注意功能前面的括号:
.controller('MainCtrl', [function(
将其更改为:
.controller('MainCtrl', ['$scope', 'myService', 'myFactory', 'myProv',
function($scope, myService, myFactory, myProv) {
或删除两个括号:
.controller('MainCtrl', function($scope, myService, myFactory, myProv) {
$scope.serviceOutput = "service = " + JSON.stringify(myService);
$scope.factoryOutput = "factory = " + myFactory;
$scope.providerOutput = "provider = " + myProv;
});
中详细了解相关信息