Sending a value to a different Ionic page based on a specific condition

Here is the code snippet from my app.js:

var app = angular.module('dbpjkApps', ['ionic'])

app.controller('kategoriCtrl', function($scope) {
    $scope.listKat = [
        {kat: 'math'}, {kat: 'physics'}, {kat: 'English'}, {kat: 'bahasa'},
    ]})
    .config(function($stateProvider, $urlRouterProvider) {
        $stateProvider

        .state('menu1', {
            url: '/menu1',
            templateUrl: 'xxx.html' //this is condition what i mean. 
        })

        .state('login1', {
            url: '/login1',
            templateUrl: 'login1.html'
         });

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

During the initial step, users have to select a category from a dropdown on login1.html.

How can I implement logic to determine if the user selects math or physics, and then direct them to either menu1.html or menu2.html? Additionally, how can I retrieve the selected value from login1.html in menu1.html or menu2.html?

Appreciate any help and guidance. Thank you!

Answer №1

To retrieve the selected value from a combobox, utilize ng-model.

Additionally, ensure to define the state in stateProvider:

.state('menu1', {
            url: '/menu1',
            templateUrl: 'menu1.html' //this is the condition I am referring to. 
        })


.state('menu2', {
            url: '/menu2',
            templateUrl: 'menu2.html' //this is the condition I am referring to. 
        })

Subsequently, validate the ng-model value of the combobox in the Login Controller and include the following lines to redirect the page:

if(condition1){
       $state.go('menu1'); 
}else if(condition2){
       $state.go('menu2'); 
}

Answer №2

Begin by setting up your configuration

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

        .state('menu1', {
            url: '/menu1/:userChoice',
            templateUrl: 'xxx.html' //this is a condition that needs to be met
        })

        .state('menu1', {
            url: '/menu2/:userChoice', //defining parameters for the state
            templateUrl: 'xxx2.html' //another state 
        })

        .state('login1', {
            url: '/login1',
            templateUrl: 'login1.html'
         });

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

In the controller, determine where to navigate to:

    app.controller('kategoriCtrl', function ($scope, $state) {
    $scope.listKat = [
        {
            kat: 'math'
        }, {
            kat: 'physics'
        }, {
            kat: 'English'
        }, {
            kat: 'bahasa'
        },
    ]

    //Define ng-model in the select tag in your HTML template.

    $scope.choice = $scope.listKat[0];

    $scope.changeState = function () {
        if ($scope.choice == "math") {
            $state.go("menu1", {
                userChoice: $scope.choice
            });
        } else if ($scope.choice == "physics") {
            $state.go("menu2", {
                userChoice: $scope.choice
            });
        }

    }
})

To access the params in your math1 controller:

app.controller('math1Ctrl', function($stateParams) {
    console.log($stateParams.userChoice); // will log either 'math' or 'physics'
})

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

When trying to connect to the MongoDB database using Node.js and Express, the content

Currently immersing myself in the world of MongoDB for Node.js Here is my app.js: var express = require('express'), app = express(), engines = require('consolidate'), MongoClient = require('mongodb').MongoClient, as ...

Encountering a Project Oxford error - HTTP 404 while trying to access Computer Vision API with Javascript

I am attempting to retrieve JSON data from Microsoft Project Oxford via an API call. Despite following the API reference, I encounter a 404 error when making the call. <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js">< ...

What's the best way to showcase array values in JavaScript?

I am facing an issue where I am trying to display all values from the array "categories", but I keep getting [object object] or undefined. The problem seems to be occurring in the code within the last lines of the if statement, specifically when I try to ...

Can the order of React lifecycle events be reliably predicted across different components?

Is there a clear documentation on the guarantees of React lifecycle order across separate components? For instance, if I have: <div>{ x ? <A /> : <B /> }</div> When x changes from true to false, one component will unmount and the ...

When I click on my div, the color does not change as expected

Recently, I wrote a code snippet where there are 9 different div elements each assigned a ".spaces" class. The intention was to change the color of these divs upon clicking on them. However, I encountered an issue where only the first div changes its color ...

URL-based authentication using Passport.js

I am currently working on my app using Express JS and Passport JS. My goal is to allow a new user to automatically log in once by accessing a specific URL. I have the ability to retrieve the user information from the database based on the URL provided, re ...

Alas, an error has occurred with eslint npm. The elusive 404 Not Found reared its head once more when attempting to access the es

I'm currently in the process of organizing my JavaScript code and preparing to transition to TypeScript. I recently set up node.js, npm, and eslint on my Ubuntu 20.04 system. After doing so, I executed npm -init and eslint -init. $ npx eslist util.js ...

There was an issue with the Discord.js (v12) Giveaway Command that resulted in an error stating "Error: Cannot read property 'hasPermission' of undefined"

Hey everyone, I'm trying to develop my own Discord bot and I want to add a giveaway command to it. I found an example code online that I tried to implement, but unfortunately, it's not working as expected... const ms = require('ms'); c ...

What could be causing my browser to display twice the height value?

After running the code below on my browser, I noticed that the height value is rendered double. To start off, I tested the following code in about:blank. In the HTML: ... <canvas id="canvasArea" style=" width: 500px; height: ...

Locating elements with Selenium Webdriver using xpath

<a style="color:White;" href="javascript:__doPostBack('dnn$ctr674$Case$gvCaseSearchDetails','Page$777')">777</a> Can anyone help with writing an xpath for the HTML code above? The goal is to locate elements using the identi ...

Creating dynamic ColumnDefs for UI Grid is essential for responsive and flexible data

I am currently facing a challenge with my angular UI Grid setup for populating data in reports. With almost 20 reports to handle, I am looking to streamline the process by using one UI Grid for all of them. To achieve this, I am attempting to dynamically c ...

The second parameter of the Ajax request is not defined

Having an issue with my Ajax request in Vue.js where the second parameter is logging as undefined in the console. I've been trying to fix this problem but haven't found a solution yet. This is the code snippet for $.ajax(): //$.ajax() to add ag ...

Struggling to Retrieve Specific Keys for Individual Values in Firebase with React Native

I am currently experiencing difficulty obtaining a unique key for each value in the 'users1' table. firebase.database().ref('users1').once('value').then(snapshot => { var items = []; snapshot.forEach((child) => { ...

The paths specified in Node.js and Express are having difficulty finding the resource files for CSS and JavaScript

I am currently using Express to develop a basic website. Everything was running smoothly until I attempted to add the following code to handle 404 errors: app.get('/*', function(req, res) { res.render('404.ejs',{ title: ' ...

Enhance Your Angular SPAs with Automated Accessibility Testing Tools

Has anyone had success using an automated accessibility testing tool specifically designed for Angular Single Page Applications (SPA)? I experimented with pa11y, but it was not providing consistent results. I'm curious if there are other tools simila ...

Enhancing data with AngularJS and Firebase

I enjoy using firebase, but sometimes their documentation lacks detail. When updating changes in the database, I follow their instructions. var ref= new $window.Firebase('https://mysite.firebaseio.com/arcade/'+$scope.gameID+'/scor ...

Storing the Token from the AJAX Login API Call in JavaScript: Best Practices for Keeping Credentials Secure

After sending my credentials to a login API, I received a successful response containing user data and a token. I would like to know how I can store this information so that the user doesn't have to log in every time. Is it possible for me to save the ...

Is it possible for (variable or {}) to function seamlessly across all web browsers when using Javascript

When writing code in JavaScript, the if(variable) clause is used to check if a list or array is not null or undefined in order to avoid exceptions. Here's an example: if (list) for (var k in list) { ... if (array) for (var i = array.l ...

Is it possible to modify the contents within the JSP div tag without replacing them through an AJAX call?

In my JSP, I face a scenario where there is a div tag with scriptlet content that pulls data from the database every time a request is received from the server. Previously, I was refreshing the entire page with each update, which not only loaded all the re ...

Viewing an immutable concealed field in Angular

My situation is quite unique as I have an Angular app embedded within a legacy ASP.NET webforms app (specifically in the header and footer). Authentication still happens through Webforms without any token service in place. The challenge arises when Angula ...