为什么以下代码不起作用:
<!DOCTYPE html>
<html ng-app="demo">
<head>
<meta charset="utf-8" />
<title>Demo</title>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.6/angular.js"></script>
<script>
angular.module('demo',[])
.factory('myFactory', function(){
return {foo: function(){return 'bar';}};
})
.run(['myFactory', testFn(myFactory)]);
function testFn(myFactory){alert(myFactory.foo());}
</script>
</head>
<body ng-app="demo">
</body>
</html>
但是轰鸣声代码有效:
<!DOCTYPE html>
<html ng-app="demo">
<head>
<meta charset="utf-8" />
<title>Demo</title>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.6/angular.js"></script>
<script>
angular.module('demo',[])
.factory('myFactory', function(){
return {foo: function(){return 'bar';}};
})
.run(['myFactory', function(myFactory){
alert(myFactory.foo());
}]);
</script>
</head>
<body ng-app="demo">
</body>
</html>
在我的应用程序中,运行的函数很长,所以我不想把它内联到app.run,因为它看起来很乱。怎么做?
答案 0 :(得分:1)
Angular的run
块需要一个指向函数的指针,因此无需创建其他函数,您可以将其重写为:
angular.module('app',[])
.run(['myFactory', testFn]) // testFn is a pointer to the function.
答案 1 :(得分:0)
对不起,我是个白痴。由此修复:
<!DOCTYPE html>
<html ng-app="demo">
<head>
<meta charset="utf-8" />
<title>Demo</title>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.6/angular.js"></script>
<script>
angular.module('demo',[])
.factory('myFactory', function(){
return {foo: function(){return 'bar';}};
})
.run(['myFactory', function(myFactory){
testFn(myFactory);
}]);
function testFn(myFactory) {alert(myFactory.foo());}
</script>
</head>
<body ng-app="demo">
</body>
</html>