简体   繁体   English

初始化角度模块和控制器的正确方法

[英]Proper way to initialize angular module and controller

I am attempting to learn angular.js and have seen a few different ways to initialize the module and controller. 我正在尝试学习angular.js,并看到了几种初始化模块和控制器的不同方法。

here is how i found to do it through debugging one site I have been using as a guide. 这是我发现如何通过调试一个一直用作指南的站点来做到这一点的方法。

var myApp = angular.module("myApp", []);
myApp.controller("myController", myController);

function myController($scope) {
     //some code
}

and her is a way I have seen it done on a few different tutorials 她是我在一些不同的教程中看到的一种方式

angular.moudule('myApp', []).controller('myController', function($scope){
    //some code
}

I understand that this may be a personal preference but I would like to know if there is a preferred way or a cleaner way to do it. 我了解这可能是个人喜好,但我想知道是否有首选的方法或更清洁的方法来执行此操作。 Also if there is a better way to do please mention that as well. 另外,如果有更好的方法也请提及。

Those two ways have more than one difference: 这两种方式有多个不同之处:

  • having a global var 具有全局变量
  • chaining methods 链接方法
  • inline callback function 内联回调函数

That gives us eight total combinations from your two examples, which makes a direct comparison of each tedious. 这使我们从您的两个示例中获得了八种组合,从而直接比较了每个繁琐的操作。 Use whatever you find the most readable to you (and your team) and appropriate for the project (for example, will you need that myApp variable elsewhere in the code such as for loading components from external files, etc). 使用您认为最适合您(和您的团队)并且适合该项目的任何内容(例如,是否需要myApp变量在代码中的其他位置使用,例如从外部文件加载组件等)。 If you still can't decide, there are a couple of Angular style guides online, explore them. 如果仍然不能确定,可以在线找到一些Angular样式指南,以进行探索。

I do also follow john papa's style guide.. as per that you should define controllers as 我也遵循约翰·帕帕(John papa)的风格指南。

/* recommended */

// some.controller.js
angular
    .module('app')
    .controller('SomeController', SomeController);

function SomeController() { }

There are many ways but always reusable one is better and helpful one. 有很多方法,但始终可重用的方法是一种更好且有用的方法。

Keeping module in a separate variable 将模块放在单独的变量中

 var myApp = angular.module('myApp',[]); myApp.controller('FirstController', ['$scope', function($scope) { $scope.greet = 'Hi Im First Controller !'; }]); 
 <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script> <div ng-app="myApp" ng-controller="FirstController"> {{ greet }} </div> 

Chaining the Method 链接方法

 var myApp = angular.module('myApp',[]).controller('SecondController', ['$scope', function($scope) { $scope.greet = 'Hi Im Chained Second Controller !'; }]); 
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script> <div ng-app="myApp" ng-controller="SecondController"> {{ greet }} </div> 

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

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