softshipper
softshipper

Reputation: 34071

ui-router controller or angular controller

I am using ui-router for routing my app. On ui-router I can define controller like

myApp.config(function($stateProvider, $urlRouterProvider) {
  //
  // For any unmatched url, redirect to /state1
  $urlRouterProvider.otherwise("/state1");
  //
  // Now set up the states
  $stateProvider
    .state('state1', {
      url: "/state1",
      templateUrl: "partials/state1.html"
    })
    .state('state1.list', {
      url: "/list",
      templateUrl: "partials/state1.list.html",
      controller: function($scope) {
        $scope.items = ["A", "List", "Of", "Items"];
      }
    })

here you can see the controller definition on ui-router state object.

My question is, what is more common, define an angular controller or ui-router controller?

angular.module('controllerExample', [])
  .controller('SettingsController2', ['$scope', SettingsController2]);

Upvotes: 0

Views: 161

Answers (2)

Ben Diamant
Ben Diamant

Reputation: 6206

'What's more common' is a very broad question, but.

There are few things to consider:

  1. What type of state and how nested is it (If its a nested state that only displays a bulk of data that's might be fine)
  2. How large the controller is? (2-3 lines of logic can be handled inline)
  3. How do you structure your app?

In the end, a better practice is to put all in an organized 1 spot and not splitting your controller definition, so if to choose from both approaches, don't define your controller inline.

Upvotes: 1

Radim Köhler
Radim Köhler

Reputation: 123861

I could not say what is more common, just why to use the second approach.

Firstly, if we declare the controller as SettingsController2 (object/function), we can use it multiple times.

Secondly, this approach creates a real type, which could be later easily trakced (found) once you observe the pefromance tools (memory profiler)

Finally, if we will use some JS++ like Typescript or AtScript, we can easily use inheritance and even other features...

So do not use inline def, if possible

Upvotes: 1

Related Questions