2013-03-15 57 views
0

我有带指令和模块的控制器的应用程序模块。angular.module.controller的替代语法

angular.module('ValidationWidgets', []) 
    .directive('validationfield', function() { 
     .... 
    }); 


angular.module('MyPage', ['ValidationWidgets']) 
     .controller('MyFirstController', function ($scope) { 

     .... 
    }); 

有一些漂亮的语法来声明在应用模块许多控制器,因为.controller('MyFirstController', function ($scope) {很糟糕?

我想写类似:

var myPage = angular.module('MyPage', ['ValidationWidgets']); 

myPage.controllers.MyFirstController = function($scope) { 
    ... 
} 

回答

3
var app = angular.module("myApp", []); 
app.controller("my controller", function(){}); 

var app = angular.module("myApp", []); 
var controllers = {}; 
controller.myController = function(){}; 
app.controller(controllers); 

这个视频http://egghead.io/video/angularjs-thinking-different-about-organization/

整个系列是惊人的,说实话看看。

+0

我相信你也可以让你的路由器从函数声明中加载到控制器中。尽管这使得函数声明确实是一个控制器不太明显。 – 2013-04-21 01:32:31

+0

我认为应该读取'controllers.myController' ...但我无法进行单个字符编辑。谢谢! – ptim 2014-06-11 01:28:13

+0

是的,你是对的,我不能编辑它 – Will 2014-07-09 11:42:34

0

要展开什么@Jacob道尔顿说,你可以这样做:

设置你的路由:

function View1Ctrl($scope, $http) { 
} 

function View2Ctrl($scope, $http) { 
} 

app.config(['$routeProvider', function($routeProvider, $locationProvider) { 
    $routeProvider. 
     when('/view1', {templateUrl: 'partials/view1', controller: 'View1Ctrl'}). 
     when('/view2', {templateUrl: 'partials/view1', controller: 'View2Ctrl'}). 
     otherwise({redirectTo: '/view1'}); 
}]); 

然后,你可以通过简单地声明一个函数声明你的控制器

这些功能将作为控制器自动连线。然而,如前所述,这使得这些功能是控制器并不那么明显。

+0

View1Ctrl应该在全球范围内,是吗?或者这个函数可以在其他对象范围内? – 2014-03-11 12:54:13