[AngularJS] Best Practise - Controller

ControllerAs

Use thecontrollerAs syntax always as it aids in nested scoping and controller instance reference.

Bad:

<div ng-controller="MainCtrl">
  {{ someObject }}
</div>

Good:

<div ng-controller="MainCtrl as main">
  {{ main.someObject }}
</div>

Use the router to couple the controller declarations with the relevant views by telling each route what controller to instantiate.

Best:

复制代码
<!-- main.html -->
<div>
  {{ main.someObject }}
</div>
<!-- main.html -->

<script>
// ...
function config ($routeProvider) {
  $routeProvider
  .when('/', {
    templateUrl: 'views/main.html',
    controller: 'MainCtrl',
    controllerAs: 'main'
  });
}
angular
  .module('app')
  .config(config);
//...
</script>
复制代码

This avoids using $parent to access any parent controllers from a child controller, simple hit the mainreference and you've got it. This could avoid things such as $parent.$parent calls.

 

ControllerAs as this keyword:

The controllerAs syntax uses the this keyword inside controllers instead of $scope. When usingcontrollerAs, the controller is infact bound to $scope, there is a degree of separation.

Bad:

复制代码
function MainCtrl ($scope) {
  $scope.someObject = {};
  $scope.doSomething = function () {
  
  };
}
angular
  .module('app')
  .controller('MainCtrl', MainCtrl);
复制代码

Because in router, already defined controllerAs:

  $routeProvider
  .when('/', {
    templateUrl: 'views/main.html',
    controller: 'MainCtrl',
    controllerAs: 'main'
  });

Threrefore, no need to use $scope. 

Good:

复制代码
function MainCtrl () {
  this.someObject = {};
  this.doSomething = function () {
  
  };
}
angular
  .module('app')
  .controller('MainCtrl', MainCtrl);
复制代码

Also:

复制代码
function MinCtrl(){
    var vm = this;
    vm.someObject = {};
    vm.doSomething = function(){};
}

angular
    .module('app')
    .controller('MainCtrl', MainCtrl);
复制代码

These just show examples of Objects/functions inside Controllers, however we don't want to put logic in controllers...

 

Avoid Controller Logic:

Avoid writing logic in Controllers, delegate to Factories/Services.

Bad:

复制代码
function MinCtrl(){
    var vm = this;
    vm.someObject = {};
    vm.doSomething = function(){};
}

angular
    .module('app')
    .controller('MainCtrl', MainCtrl);
复制代码

Good:

function MainCtrl (SomeService) {
  var vm = this;
  vm.doSomething = SomeService.doSomething;
}
angular
  .module('app')
  .controller('MainCtrl', MainCtrl);

This maximises reusability, encapsulated functionality and makes testing far easier and persistent.

posted @   Zhentiw  阅读(339)  评论(0编辑  收藏  举报
(评论功能已被禁用)
编辑推荐:
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
点击右上角即可分享
微信分享提示