资料来源: http: //plnkr.co/edit/NpyTspWsY3rh0bzl9JUq
该代码示例适用于 plnkr。当我将代码复制到使用 yeoman 创建的新应用程序中时,出现以下错误:
ReferenceError: $hello is not defined
at $get (http://localhost:9000/scripts/app.js:21:16)
at Object.invoke (http://localhost:9000/components/angular/angular.js:2864:28)
at http://localhost:9000/components/angular/angular.js:2702:37
at getService (http://localhost:9000/components/angular/angular.js:2824:39)
at Object.invoke (http://localhost:9000/components/angular/angular.js:2842:13)
at http://localhost:9000/components/angular/angular.js:2702:37
at Object.getService [as get] (http://localhost:9000/components/angular/angular.js:2824:39)
at http://localhost:9000/components/angular/angular.js:9545:24
at filter (http://localhost:9000/components/angular/angular.js:6107:14)
at _filterChain (http://localhost:9000/components/angular/angular.js:6098:41)
我不知道为什么它适用于 plnkr 但不适用于新创建的 Angular 应用程序。
yeoman 应用程序如下所示:
'use strict';
angular.module('asdfApp', ['myHello'])
.config(function ($routeProvider) {
$routeProvider
.when('/', {
templateUrl: 'views/main.html',
controller: 'MainCtrl'
})
.otherwise({
redirectTo: '/'
});
});
var myModule = angular.module('myHello', []);
myModule.provider('$hello', function () {
this.$get = function () {
$hello = function (key) {
return 'hello ' + key;
};
return $hello;
}
});
myModule.filter('hello',function ($parse, $hello) {
return function (key) {
return $hello(key);
};
});
当我将代码更改为此(在对象中返回 say 函数)时,它可以在 yeoman 脚手架应用程序中工作:
var myModule = angular.module('myHello', []);
myModule.provider('$hello', function () {
this.$get = function () {
var say = function (key) {
return 'hello ' + key;
};
return { say : say};
}
});
myModule.filter('hello',function ($parse, $hello) {
return function (key) {
return $hello.say(key);
};
});