繁体   English   中英

在AngularJS和控制器中使用jshint

[英]Using jshint with AngularJS and Controllers

我正在尝试将JSHint合并到我的构建过程中。 我正在构建的应用程序使用AngularJS。 目前,我有一个不确定的解决方法,我有一个冲突。 构建应用程序时,出现JSHint错误,提示:

   src\app\app.js
      3 |var myApp = angular.module('myApp', []);
             ^ Redefinition of 'myApp'.

>> 1 error in 2 files
Warning: Task "jshint:source" failed. Use --force to continue.

我收到此错误,因为在我的.jshintrc文件中,我具有以下内容:

“ predef”:[“ angular”,“ myApp”],

如果删除“ myApp”,则会收到另一个错误,提示:

src\app\account\welcome.html.js
   3 |myApp.controller('WelcomeController', ['$scope', function($scope) {
      ^ 'myApp' is not defined.

1 error in 2 files

之所以定义这样的控制器,是因为根据AngularJS文档 ,您不应在全局范围内定义控制器。 如您所见,就像我被该死,否则我被该死。 在构建过程中仍包含JSHint的同时,我如何遵循AngularJS的最佳建议?

谢谢!

我认为您可以使用.jshintrc文件中的全局密钥来解决此问题

{
    "node": true,
    "browser": true,
    "esnext": true,
    "bitwise": true,
    "camelcase": true,
    "curly": true,
    "eqeqeq": true,
    "immed": true,
    "indent": 4,
    "latedef": true,
    "newcap": true,
    "noarg": true,
    "quotmark": "single",
    "undef": true,
    "unused": true,
    "strict": true,
    "trailing": true,
    "smarttabs": true,
    "multistr": true,
    "globals": {
        "myApp": false
    }
}

为什么要完全定义myApp变量? 我用这种方式定义我的应用程序,控制器等。 您可以链接多个控制器,工厂等:

angular.module('myApp',[])

.controller("MainCtrl", function($scope) {
    $scope.person = {
        nfname: 'John',
        lname: 'Deighan',
        email: 'john.deighan@gmail.com',
    };
});

最后一个给出的示例很好,但是如前所述,如果您调用.module()并将空数组作为第二个参数,则将重新定义模块依赖性。 为了避免这种情况,只需将模块名称传递给.module()

angular.module('myApp')

.controller("MainCtrl", function($scope) {
    $scope.person = {
        nfname: 'John',
        lname: 'Deighan',
        email: 'john.deighan@gmail.com',
    };
});

原因:

为什么要重新定义?

因为你设置myApp作为PREDEF .jshintrc文件,jshint认为myApp已经在这个项目目录中的所有文件进行定义。 因此,当您定义myApp ,将重新定义错误。

为什么未定义?

因为在同一文件中没有myApp的定义。 我猜你在app.js文件中定义它。 如您所见,在Angularjs文档中,它们的控制器均在myApp之后定义,它们位于同一文件中。

解:

不需要在.jshint中将myApp设置为.jshint或global,建议在定义控制器或配置时执行以下操作:

angular.module('myApp')
.controller('myController', 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM