Join the Stack Overflow Community
Stack Overflow is a community of 6.4 million programmers, just like you, helping each other.
Join them; it only takes a minute:
Sign up

I am new to typescript and am trying to use UI Router's $state to navigate in my typescript controller. Unfortunately, I am still receiving a state is not defined error that I cannot resolve.

Here is my controller:

module MyApp {
export class LoginController {
    email: string;
    password: string;
    loginForm: any;
    state: any;

    constructor($state: ng.ui.IStateProvider) {
        this.state = $state;
    };

    login() {
        if (this.loginForm.$invalid) {
            return;
        }

        console.log(`Login was clicked, email is ${this.email} and password is ${this.password}`);
        state.go('Dashboard');
    }
}
}

angular.module('myApp').controller('loginController', MyApp.LoginController);

Any help would be appreciated.

share|improve this question
2  
I'm using Angular 1.5 – cfly24 Feb 16 at 16:42

You're assigning $state to this.state on controller construction.

This means that it should be referred as this.state all over the object.

share|improve this answer

You will need to use this.state to access the $state variable inside login function. you can check below corrected implementation of your code.

JSFiddle Typescript Implementation

// Typescript

module MyApp {
  export class LoginController {
    email: string;
    password: string;
    loginForm: any;
    state: any;

    constructor($state: ng.ui.IStateProvider) {
      this.state = $state;
    };

    login() {

      if (this.loginForm.$invalid) {
        this.formError = "invalid form data";
        return;
      }

      this.formError = "";

      console.log(`Login was clicked, email is ${this.email} and password is ${this.password}`);
      this.state.go('Dashboard');
    }
  }
}

let app = angular.module('myApp', ['ui.router'])
app.config(function($stateProvider, $urlRouterProvider) {
  $stateProvider
    .state('login', {
      url: '/login',
      template: `
      	<div ng-controller="loginController as lc">
          <form name="lc.loginForm" ng-submit="lc.login()">
            <div>Email:<input ng-model="lc.email" ng-required="true" /></div>
            <div>Password: <input ng-model="lc.password" ng-required="true" /></div>
            <button type="submit" ng-click="lc.login()">Click</button>
          </form>
        </div>      
      `
    })
    .state('Dashboard', {
      url: '/Dashboard',
      template: '<div> I am Dashboard </div>'
    });

  $urlRouterProvider.otherwise('/login');
});

app.controller('loginController', MyApp.LoginController);
<!-- HTML -->
<div ng-app="myApp">
  <div ui-view></div>
</div>

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.