在angularJs中定义控制器的最佳方法 [英] Best way of defining controller in angularJs

查看:64
本文介绍了在angularJs中定义控制器的最佳方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是angularJs的新手.我很困惑哪一种是为ng-app="mainApp"创建控制器的最佳方法.在编程时,我曾经研究过的其他编程语言建议将相关数据保持在一起.但是在angularJs中,当我们可以在主应用程序模块上定义控制器时,最好为控制器添加新模块.如果我们在mainApp上创建控制器,它将保留控制器并绑定其他语言所需的内容.

I am new to angularJs. I am confused which one is best way to create a controller for ng-app="mainApp". In programming other programming languages that I had worked on suggest to keep relative data together. But in angularJs it's considered best practice to have new module for controllers when we can define controller over main app module. If we create controller on mainApp it will keep controller and bind which is what we want in other languages.

var myapp = angular.module("mainApp", []);
myapp.controller("testController", function($scope)
{
    $scope.value = "test";
})

//OR

angular.module("mainApp", ["moduleController"]);
angular.module("moduleController", []).controller("testController", function($scope){
    $scope.value = "test";
})

对于生产环境,应使用其中一个.?

For production environment which one should be used.??

推荐答案

选项1:

var myapp = angular.module("mainApp",[]);
myapp.controller("testController",function($scope)
{
    $scope.value="test";
})

选项2:

angular.module("mainApp", ["moduleController"]);
angular.module("moduleController",[]).controller("testController",function($scope){
    $scope.value="test";
})

选项2 更好,因为这将使您可以在单独的文件中编写控制器.结果,您的代码将更具可读性.如果您想在其他AngularJS项目中重用控制器,也将为您提供帮助.

Option 2 is better because this will allow you to write your controllers in separate files. As a result your code will be more readable. It'll also help you if you want to reuse your controllers in other AngularJS projects.

例如,您可以在一个文件中编写以下代码,例如app.js:

For example, you can write the following code in one file e.g app.js:

angular.module('mainApp',['ngRoute', 'appController']);

您可以将控制器写入另一个文件,例如controllers.js:

And you can write the controller in another file e.g controllers.js:

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

appController.controller('testController', ['$scope',
    function($scope) {
        $scope.value="test";
    }
]);

现在,您只需在项目中添加controllers.js文件并将依赖项添加到app.js文件中的appController,即可在另一个项目中重用控制器.

Now, you can reuse the controllers in another project by just adding the controllers.js file in the project and adding dependency to appController in the app.js file.

这篇关于在angularJs中定义控制器的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆