StuffedPoblano
StuffedPoblano

Reputation: 695

keep user from going to other view ui-route

I am trying to add some sort of resolve/promise to this to keep the user from moving on to certain pages until they have created a profile, added a friend, etc. I have an app, a controller, and a service. Any guidance would be helpful!

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

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

        $urlRouterProvider.otherwise('/');
        $stateProvider

//#1 Initial Page
        .state('home', {
            url: '/',
            templateUrl: 'views/templates/home.html'
        })

//#2 Landing Page(new users' profile page) - User is taken here when they submit the initial form on the Home page.
        .state('landing', {
            url: '/landing',
            templateUrl: '/views/templates/landing.html'
        })
//#3 Search for Friends - User can access this page only after they submit the initial form on the Home Page.
        .state('friend-search', {
            url: '/friend-search',
            templateUrl: '/views/templates/friend-search.html',
            controller: 'friendSearchCtrl'
        })
//#4 Upadte Profile Information - User can access this as soon as they submit the initial form on the Home page.
        .state('update', {
            url: '/update',
            templateUrl: 'views/templates/update.html',
        })
//#5 Other users' profile page. User is taken here after clicking button on image overlay on the friend-search page.
        .state('friend-profile', {
          url: '/friend-profile/:id',
          templateUrl: 'views/templates/friend-profile.html',
          controller: 'friendProfileCtrl'
        })
//#6 New users' friends list. Only can access after they have added a friend.
        .state('friends', {
            url: '/friends',
            templateUrl: '/views/templates/friends.html'
        });
  });

Controller code:

app.controller('mainCtrl', function($scope, $state, mainSvrc){

  $scope.$state = $state;
  $scope.$on('$stateChangeStart', function(event, toState, toParams, fromState, fromParams){
    // Check whether user input form is submitted
    if(!formSubmitted){
     event.preventDefault();
    }
  });
//Local storage for new user profile and updated profile.//
  $scope.currentUser = JSON.parse(localStorage.getItem('profile'));

  var formSubmitted = false;
  $scope.createUser = function(obj, $event) {
    $scope.currentUser = mainSvrc.createUser(obj);
    formSubmitted = true;
    $state.go('landing');
    swal(
      '',
      'Your Information has been saved!',
      'success'
      );
  };
});

Service Code:

app.service('mainSvrc', function() {

//Stores users' data in local storage after clicking the save button on either form.
  this.createUser = function(user) {
    localStorage.setItem('profile', JSON.stringify(user));
    return user;
  };

HTML code:

<form class="form-home">
                <input type="text"
                ng-model="newUser.name"
                placeholder="Full Name"
                onfocus="this.placeholder = ''"
                onblur="this.placeholder = 'Full Name'" />

                <input type="text"
                ng-model="newUser.tagline"
                placeholder="Tagline"
                onfocus="this.placeholder = ''"
                onblur="this.placeholder = 'Tagline'">

                <input type="text"
                ng-model="newUser.profileUrl"
                placeholder="Profile Image Url"
                onfocus="this.placeholder = ''"
                onblur="this.placeholder = 'Profile Image Url'">

                <textarea rows="15" cols="50"
                ng-model="newUser.bio"
                placeholder="Bio"
                onfocus="this.placeholder = ''"
                onblur="this.placeholder = 'Bio'">
                </textarea>

                <button type="submit" ng-click="createUser(newUser, event)"
                >
                    Save Changes
                </button>
            </form>

Upvotes: 1

Views: 85

Answers (2)

Nitheesh
Nitheesh

Reputation: 19986

You Could use the $locationChangeStart event in angular js to validate the exit event of the user from a controller.

  $scope.IsUserNavigatable = function(){
     var createdUsers = $scope.UserList;
     var isUserCreated = createdUsers.length > 0;
     return isUserCreated;
  }

  $scope.$on('$locationChangeStart', function (event, newUrl, oldUrl) {

        if ($scope.IsUserNavigatable() ) {
            //Here the user can move to next page
        }
        else {
            event.preventDefault();
        }
  });

The $locationChangeStart event will be triggered on the user trying the change the URL. On validating the navigation condition, the user can be redirected to another page. $scope.IsUserNavigatable() refers to your method that validates the navigation condition of the user. If that fails, prevent the user navigation by triggering event.preventDefault()

Here I have shown a sample function to check whether a user have been created or not while exiting from the page. In that function it returns the Length of user list created at that time. The user can navigate if the length of the user array is greater than zero.

Upvotes: 1

Ravi Teja
Ravi Teja

Reputation: 1107

You can use $stateChangeStartevent to check whether form is submitted or not.

$stateChangeStart event triggers each time you try to navigate to a different page, in you case $state.go('landing').

$scope.$on('$stateChangeStart', function(event, toState, toParams, fromState, fromParams){
  // Check whether user input form is submitted
  if(!formSubmitted){
   event.preventDefault();
  }
});

I believe, you should be having a ng-click event when form submit button is clicked. So, inside the function associated with that click event set formSubmitted variable to true.

For Example:

var formSubmitted = false;
$scope.createUser = function(profileObj, $event) {
    // I don't  think you need to preventDefault here, but not sure what you are trying to do. 
    // If you just wrote the $event.preventDefault() so that user will not be navigated to landing page, you don't need it here.
    //$event.preventDefault();
    $scope.userProfile = profileObj;
    userProfService.createUser(profileObj);
    formSubmitted = true;
    $state.go('landing');
    swal(
        'Welcome to the Club!',
        'Your Information has been saved!',
        'success'
    );
};

Upvotes: 1

Related Questions