Angular Controller

更新日期: 2015-12-12 阅读次数: 10740 分类: AngularJS

controller 适合用来做什么

  • Set up the initial state of the $scope object.
  • Add behavior to the $scope object.

controller 的定义方法

推荐的方式

var myApp = angular.module('myApp',[]);
 
myApp.controller('GreetingController', ['$scope', function($scope) {
  $scope.greeting = 'Hola!';
}]);

不推荐的方式

function GreetingController($scope) {
  $scope.greeting = 'Hola!';
}

不推荐的理由:

  • 全局 controller, 未指定 module.
  • 未指定 dependency injection

controller 不适合做什么

  • Manipulate DOM — Controllers should contain only business logic. Putting any presentation logic into Controllers significantly affects its testability. Angular has databinding for most cases and directives to encapsulate manual DOM manipulation.
  • Format input — Use angular form controls instead.
  • Filter output — Use angular filters instead.
  • Share code or state across controllers — Use angular services instead.
  • Manage the life-cycle of other components (for example, to create service instances).

参考

  • http://docs.angularjs.org/guide/controller

微信关注我哦 👍

大象工具微信公众号

我是来自山东烟台的一名开发者,有感兴趣的话题,或者软件开发需求,欢迎加微信 zhongwei 聊聊, 查看更多联系方式

相关文章 🔍