2016-12-28 68 views
1

不知道为什么这不工作这time..Previously每一个地方及其工作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> 

它的工作罚款 ..

当我使控制器文件seprately并调用它的视图

<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'); 

再次工程..

这里,什么主要问题?像这样我不能通过任何依赖..任何建议请..

+0

你可以分享你在单独的文件控制器的代码? – superUser

+0

此外,需要注意的是'var testApp = angular.module('test')'与_ var testApp = angular.module('test',[])''是相同的__not__。一个是宣布一个新的模块,另一个是检索一个已有的模块。如果你在这两个文件中使用第二种格式,那么你只需重新创建你的模块。清除以前添加的任何内容。 –

+0

@suzo我一直在测试就像现在一样的测试控制器..它不工作太.. –

回答

0

加载app.js文件后放置控制器文件。

所以app.js的内容将是,

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

Controller.js会,

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

index.html中,订货会,

<script src="app.js"></script> 
<script src="testCtrl.js"></script> 

DEMO

+0

为什么downvote球员? – Sajeetharan

+0

可能是因为'testApp'是一个全局变量,通常被认为是不好的形式。最好使用angular的预期getter方法'angular.module('testApp')'来检索要添加的模块。 –

+0

如果我没有在app.js之后放置testctrl.js,那么它在两种情况下都不应该工作.. @sajee –

3

您正在为模块声明和重新声明一个全局变量。这个全局变量可能会被挂起或者其他类型的javascript执行voodoo,这会让你的代码以不可预知的方式运行。为了防止这种情况发生,只需使用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')仅仅调用第二个参数检索模块,以便您可以添加更多指令/控制器/配置/常量。另外,你也许应该沟通独立的控制器,因为它们不再被认为是最佳实践。指令/组件路线更多现在流行

对于当前角的最佳实践的简要概述,请约翰爸爸的https://github.com/johnpapa/angular-styleguide/blob/master/a1/README.md

相关问题