📜 ⬆️ ⬇️

Light controllers with AngularJS

In addition to this post.

Who does not know, there is such a thing ui-router . Replacing the standard router Angulyar. Considering that in Angulyar 2.0 they plan to cut something similar, soon this router will become the standard.

Using it, you can build an application, for example, like this:

Main module
$stateProvider.state('main', { abstract: true views: { 'body': { templateUrl: '/main/views/body/template.html' }, 'header@main': { controller: 'mainBodyHeader' templateUrl: '/main/views/body/header/template.html' }, 'footer@main': { controller: 'mainBodyFooter' templateUrl: '/main/views/body/footer/template.html' } } }); 

/main/views/body/template.html
 <body> <ui-view name="header"></ui-view> <ui-view name="content"></ui-view> <ui-view name="footer"></ui-view> </body> 

')
Article module
 $stateProvider.state('article', { parent: 'main', abstract: true, views: { 'content@main': { templateUrl: '/article/views/content/template.html' }, 'navigation@article': { controller: 'articleContentNavigation' templateUrl: '/article/views/content/navigation/template.html' }, 'sidebar@article': { controller: 'articleContentSidebar' templateUrl: '/article/views/content/sidebar/template.html' } } }); $stateProvider.state('article.popular', { url: '/article/popular', views: { 'list': { controller: 'articleContentListPopular', templateUrl: '/article/views/content/list/popular/template.html' } }, }); 

/article/views/content/template.html
 <content> <ui-view name="navigation"></ui-view> <ui-view name="sidebar"></ui-view> <ui-view name="list"></ui-view> </content> 

Thus it is possible to split the application into as many parts as you like.

You can also write your directives. If controllers, by and large, are used for unique things, then the directive is to wrap any components found in the application several times. By the way, directives may have their own controllers.

 app.directive('demo', function () { return { templateUrl: '/directives/demo/template.html', controller: 'demo' }; }); 


There are also directives ng-include and ng-controller , which, in general, are not needed, but can help if you use a standard router.

There are services in which it is worth making a common code.

There is a router resolve, where you can do common asynchronous operations so as not to drag them into each controller.

Why am I writing all this? To the fact that the problem of fat controllers sucked from the finger. Using standard tools, you can write an arbitrarily large application, where the average controller will occupy 200 lines of code.

Source: https://habr.com/ru/post/222065/


All Articles