Coding Away Coding Away - 2 months ago 7
AngularJS Question

angular ui-router state how is controller being called

I have see people post things online about using Angular ui-router and i see these types are code that do not explicitly even show an controller name, so how is it even suppose to know how to call the controller?

state('new-rp', {
url: '/new/:portfolioId',
templateUrl: 'new.html',
controller: function($scope, $stateParams) {
$scope.portfolioId = $stateParams.portfolioId;
}
})


Code of mine that I TRIED that does NOT list the controller like above

.state("deviceDetail", {
url: "/devices/:DeviceId", // param is required which specific device id
templateUrl: "app/devices/deviceDetailView.html", // ui elements
controller: function($scope,$stateParams) {
$scope.DeviceId = $stateParams.DeviceId;
}

});


Problem is the controller is NOT hit

But this code explicitly uses the controller name and the controller gets hit, thus i'm having trouble with how this type of code would hit a controller

controller: function($scope,$stateParams) {
$scope.DeviceId = $stateParams.DeviceId;
}


HOW does it know? (doesn't work for me )

Answer

You can declare controllers in two ways in UI router states:

//1
.state('new-rp', {
  url: '/new/:portfolioId',
  templateUrl: 'new.html',
  controller: function($scope, $stateParams) {
  $scope.portfolioId = $stateParams.portfolioId;
  }
})

//2
 .state('new-rp', {
  url: '/new/:portfolioId',
  templateUrl: 'new.html',
  controller: PortfolioController
})
.
.
.
//PortfolioController definition

In method #1, your controller is created for you inline, while in #2, UI Router is looking for an explicitly declared controller called PortfolioController

Comments