[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 @ 2014-11-25 16:40  Zhentiw  阅读(336)  评论(0编辑  收藏  举报