Вопрос:

AngularJS 1.6.7 controller breakdown and refactor into components

angularjs angularjs-controller angularjs-components

364 просмотра

1 ответ

11 Репутация автора

i'm having angularJS app where all controllers are in one file , i want break it down and seperate each controler then refactor it to component based as it's recommended for angularJS 1.5 and above. my current structure looks like this:

.controller('HomeController', ['$scope', function ($scope){
    //logic
}
])

and the same for all other controllers are in the same file "controllers.js", in my app.js i do:

    var app = angular.module('app', [
      'services',
      'controllers',
]);

what you advice to break down the controllers into components, thank you for answers and recommendations.

Автор: phpguy Источник Размещён: 08.01.2018 09:16

Ответы (1)


3 плюса

7252 Репутация автора

Provided that you are using $scope, you could start by changing from scope to controllerAs syntax, that is, $scope.foo = 'bar' -> <p>{{ foo }}</p> would become this.foo = 'bar' -> <p>{{ ctrl.foo }}</p>.

controllerAs Syntax

From this:

app.controller('HomeController', ['$scope', function ($scope){
    $scope.title = 'Home';
}]);

To this:

app.controller('HomeController', [function (){
    this.title = 'Home';
}]);

declaring components

Afterward, you'd be able to declare your components in two ways:

Partial refactor using the existing controller:

app.component('homeComponent', {
    controller: 'HomeController'
});

Or, full refactor replacing the controller:

app.component('homeComponent', {
    controller: [ function (){
        this.title = 'Home';
    }]
});

refactoring routers

Assuming that you are using ui-router (it's very similar to ngRoute so it wouldn't be a problem).

From this:

$stateProvider
  .state('home', {
    url: '/',
    templateUrl: 'home/home.html',
    controller: 'HomeController'
})

To this, for ui-router 1.0+:

$stateProvider
  .state('home', {
    url: '/',
    component: 'homeComponent'
  })

Or this, for older versions:

$stateProvider
  .state('home', {
    url: '/',
    template: '<home-component></home-component>'
  })

Ref.: Guide: Route to Component

final thoughts

There's a pretty good style guide for angularjs written by John Papa that you should have a look at and use what's worth for you. However, as it's been told by @MikeFeltman it's not accurate with angularjs 1.5 components application style practices; therefore, you should have a look at Todd Motto's revised version of the guide including component application practices.

Disclaimer: I see no point in converting a controller to a directive before making the component, you can declare the component directly because components are special directives and they carry a controller so it's convenient for you.

Автор: lenilsondc Размещён: 08.01.2018 12:19
Вопросы из категории :
32x32