Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angularjs ui-router abstract state not invoking controller

I am new to UI-Router and am struggling to get my controller invoked. I am using an abstract state as the parent and it does not seem to call the controller. Below is a simplified version of my code.

I binded $stateChangeError onto the console and am not getting an error on the console. I added onEnter and OnExit attributes to my state and only the onEnter function gets called (not included below).

index.html

<!DOCTYPE html>
<html ng-app="plunker">

<head>
  <meta charset="utf-8" />
  <title>AngularJS Plunker</title>
  <script>document.write('<base href="' + document.location + '" />');    </script>
  <link rel="stylesheet" href="style.css" />
  <script data-require="[email protected]"  src="https://code.angularjs.org/1.3.15/angular.js" data-semver="1.3.15">   </script>
 <script src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-router/0.2.14/angular-ui-router.js" ></script>
 <script src="app.js"></script>
</head>

<body>

   <div ui-view="navbar" ></div>

   <div class="container">
     <div ui-view="content" ></div>
   </div>

   <p>We are on the homepage.</p>

</body>
</html>

App.js

var app = angular.module('plunker', ['ui-router']);

app.config(function ($stateProvider, $urlRouteProvider) {
  $urlRouteProvider.otherwise("/");

  $stateProvider.state('site', {
    abstract: true,
    views: {
      'navbar@': {
        template: '<p>This is the {{nav}}</p>',
        controller: 'NavBarCtrl'
      }
    }
  });
});
app.config(function($stateProvider) {
  $stateProvider
    .state('home', {
      parent: 'site',
      url: '/',
      views: {
        'content@': {
          template: '<p>This is the {{content}}</p>',
          controller: 'MainCtrl'
        }
      }
    });
});      
app.controller('NavBarCtrl', function($scope) {
  $scope.nav = 'Navbar'
});    
app.controller('MainCtrl', function($scope) {
  $scope.content = 'content'
});
like image 206
Taahir Hassem Avatar asked Nov 01 '22 04:11

Taahir Hassem


1 Answers

There is a working example

There are two issues. Firstly we have to reference correct module:

// instead of this
// var app = angular.module('plunker', ['ui-router']);
// we need this
var app = angular.module('plunker', ['ui.router']);

And we have to use proper names of the '$urlRouterProvider'

// instead of this
app.config(function ($stateProvider, $urlRouteProvider) {
  $urlRouteProvider.otherwise("/");

// we need this
app.config(function ($stateProvider, $urlRouterProvider) {
  $urlRouterProvider.otherwise("/");

Check it working here

like image 58
Radim Köhler Avatar answered Nov 11 '22 13:11

Radim Köhler