Ionic controller definition

161 Views Asked by At

I am pretty new to angularjs and ionic and I've been running into one problem. Below I posted some code from the app.js file, and I've noticed that any time I define a new controller (the commented out line) causes the app not to load.

I've compared my code to other app templates and it seems like everything in the app.js file is correct so I'm at a complete loss as to what's causing this problem! Has anyone ever seen something like this??

.config(function($stateProvider, $urlRouterProvider) {
  $stateProvider

    .state('app', {
    url: '/app',
    abstract: true,
    templateUrl: 'templates/menu.html',
    controller: 'AppCtrl'
  })

  .state('app.userJobs', {
    url: '/userJobs',
    views: {
      'menuContent': {
        templateUrl: 'views/userJobs.html'
   //     controller: 'ujobsCtrl'
      }
    }

  })
1

There are 1 best solutions below

0
On

Exactly as @Claies said, you would need to define the ujobsCtrl as a controller. That line you're un-commenting isn't a definition - it's actually a request for the ujobsCtrl controller; and if you haven't defined it (I'm assuming you haven't!), then things definitely will fail to work. Some docs to check out: ui-router's docs on controllers; and then AngularJS's docs on Controllers.

The following code would be options for you to use:

Option #1: Use an anonymous function as your controller:

.config(function($stateProvider, $urlRouterProvider) {
  $stateProvider
    .state('app', {
      url: '/app',
      abstract: true,
      templateUrl: 'templates/menu.html',
      controller: 'AppCtrl'
    })
    .state('app.userJobs', {
      url: '/userJobs',
      views: {
        'menuContent': {
          templateUrl: 'views/userJobs.html'
          // controller: 'ujobsCtrl' // <-- Can't use this, it's not defined
          controller: function ($scope, $log){
            $log.log('yay!');
          }
      }
    }
})

Or Option #2, where you define a separate controller, named ujobsCtrl:

.config(function($stateProvider, $urlRouterProvider) {
  $stateProvider
    .state('app', {
      url: '/app',
      abstract: true,
      templateUrl: 'templates/menu.html',
      controller: 'AppCtrl'
    })
    .state('app.userJobs', {
      url: '/userJobs',
      views: {
        'menuContent': {
          templateUrl: 'views/userJobs.html'
          controller: 'ujobsCtrl' // <-- defined below, so we can now use this
      }
    }
})
.controller('ujobsCtrl', function ($scope, $log){
  $log.log('yay!');
})

For larger apps, Option #2 is going to be the cleaner way of having lots of controllers - you can break these out into individual files in a controllers/ directory, and get that logic out of your .config block and the state definitions. For a sanity check though, Option #1 is a good starting place.