gpt4 book ai didi

javascript - 单独定义返回的“ Controller ”不是函数,未定义

转载 作者:行者123 更新时间:2023-11-30 11:44:49 28 4
gpt4 key购买 nike

不知道为什么这一次不起作用..以前它在每个地方都起作用 bt 这次它会产生这样的问题..

这里我喜欢app.js

var testApp= angular.module('test',[]);

testApp.controller('testCtrl',function($scope){
$scope.testValue='testttttttttt';
})

查看文件index.html

<div ng-app="test" ng-controller="testCtrl">
{{testValue}}
</div>

它工作很好..

但是当我单独制作 Controller 文件并在 View 中调用它时

<div ng-app="test" ng-controller="testCtrl">
{{testValue}}
</div>
<script src="testCtrl.js"></script>

它返回它的非函数,未定义...

但是如果在app.js我转换

var testApp= angular.module('test',[]);

var testApp= angular.module('test');

它再次工作..

这里,主要问题是什么??像这样我不能传递任何依赖关系..请提出任何建议..

最佳答案

您正在为您的模块声明和重新声明一个全局变量。这个全局变量可能会被提升或某种其他类型的 javascript 执行巫术,这将使您的代码以不可预测的方式运行。为了避免这种情况,只需使用 Angular 的内置模块 getter 调用,而不是在全局命名空间上声明它。

像这样:

App.js

angular.module('testApp', [
// dependencies here'
]);

TestCtrl.js

angular.module('testApp')
.controller(function($scope) {
$scope.testValue = "value";
});

同样,这里的重要区别是 angular.module('testApp', []) 和第二个参数(依赖列表)创建一个新模块,覆盖之前的 testApp 。另一方面,在没有第二个参数的情况下调用 angular.module('testApp') 只是检索模块,以便您可以添加更多指令/ Controller /配置/常量到

此外,您可能应该放弃独立 Controller ,因为它们不再被视为最佳实践。指令/组件路由现在流行

有关当前 Angular 最佳实践的简要概述,请查看 John Papa 的 https://github.com/johnpapa/angular-styleguide/blob/master/a1/README.md

关于javascript - 单独定义返回的“ Controller ”不是函数,未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41355720/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com