AngularJS controllers and “use strict”

前端 未结 4 707
野趣味
野趣味 2021-02-01 16:18

I recently started using JSHint and it is requiring me to use the function form of \"use strict\". Since then, AngularJS throws an error:

\"Error: Argument \'webAddressC

4条回答
  •  清酒与你
    2021-02-01 17:17

    I guess that JSHint is trying to tell you here is to avoid global variables (which is obviously a very good practice!).

    AngularJS has slightly different opinion about solving the same problem (that is - avoiding global variables) and allows you to define controllers in modules (using a global angular namespace). You could rewrite your example using modules like this:

    angular.module('myApp',[]).controller('webAddressController', function($scope) {
        // Do things
    });
    

    Here is the jsFiddle illustrating this in practice: http://jsfiddle.net/t3vBE/1/

    With this approach you are not polluting global namespace with controller constructors.

    You will need to change the JSHint configuration to allow angular global variable if you want to use the strict mode. Alternatively you could also wrap your whole code (once again, using modules) into a function that gets executed imediatelly:

    (function () {
        "use strict";
    
    angular.module('myApp',[]).controller('webAddressController', function($scope) {
    
        $scope.name = 'World';
        // Do things
    });
    
    }());​
    

    Here is the jsFiddle: http://jsfiddle.net/t3vBE/4/

    For me this makes sense only if you want to define pure JavaScript, "helper" functions, otherwise I would rely on AngularJS services.

提交回复
热议问题