Search code examples
javascriptangularjsangular-ui-routerurl-routingangularjs-routing

AngularJS ui-router template does not loading


I'm new to AngularJS. I've following egghead.io I've set up a controller and model to retrieve message from input component and display it. I'm using ui-router.

Here's my index.html

<!DOCTYPE html>
<html ng-app="app">
    <head lang="en">
        <meta charset="UTF-8">
        <title> </title>
        <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.4.3/angular.js"></script>
        <script src="//angular-ui.github.io/ui-router/release/angular-ui-router.js"></script>
        <script src="app.js"></script>
    </head>
    <body>
        <div ui-view=""></div>
    </body>
</html>

Here's my app.js

angular.module('app',["ui.router"])

            .config([function($stateProvider) {
                $stateProvider
                    .state('index', {
                        url:"",                 
                        templateUrl:"templates/first.html",
                        controller:"FirstCtr as first"
                    });

            });

            .controller("FirstCtr", function FirstCtr() {
                var first = this;
                first.greeting = "First";

            });

Here's my templates/first.html

<input type="text" ng-model="first.greeting"/>
    <div ng-class="first.greeting">
        {{first.greeting}} {{"World"}}
    </div>

After I go to http://localhost:8080, it was blank and throw this error

enter image description here

Please give me some suggestions.


Solution

  • Your state definition should be be declared controller alias in controllerAs option of state, with it you need to remove the semicolon from config block end.

    Also you need to inject $stateProvider dependency properly to avoid error.

    Code

    angular.module('app', ["ui.router"])
    
    //missed `'$stateProvider'` dependency here
    .config(['$stateProvider', function($stateProvider) {
      $stateProvider
        .state('index', {
          url: "",
          templateUrl: "templates/first.html",
          controller: "FirstCtr",
          controllerAs: "first"
        });
    }]) //remove semicolon from here as you are appending app in chain
    
    .controller("FirstCtr", function FirstCtr() {
      var first = this;
      first.greeting = "First";
    });
    

    Working Plunkr