Creating a multi-page form in AngularJS with Tab navigation

Hello, I am currently working on implementing a multi-stage form using AngularJS Tabs. Instead of using routes in this application, I am trying to achieve the desired functionality solely through tabs.

app.controller('createProjectController', ['$scope', 'resourceProject', function ($scope, resourceProject) {

  this.tab = 1;

  this.setTab = function (newValue) {
    this.tab = newValue;
  };

  this.isSet = function (tabName) {
    return this.tab === tabName;
  };

  $scope.project = {};

  $scope.postProject = function () {

    // console.log("Post Here");
    // $scope.project.Id = null;
    resourceProject.postEvent().save($scope.project)
      .$promise.then(
      function (response) {
        console.log("Saved");
        //console.log(response);
        $scope.project = response;
        //Unable to change tab
        console.log(this.tab);
// Not Working
        this.tab = 2;
// Not working setTab(2);

      },
      function (error) {
        console.log("It was broken !");
      });
  }
}]);

In the HTML, I have structured it as follows:

  <section class="tab" ng-controller="createProjectController as tab">
            <ul class="nav nav-pills">
                <li ng-class="{ active: tab.isSet(1) }">
                    <a href ng-click="tab.setTab(1)">Project Information</a>
                </li>
                <li ng-class="{ active: tab.isSet(2) }">
                    <a href ng-click="tab.setTab(2)">Further Information</a>
                </li>
                <li ng-class="{ active: tab.isSet(3) }">
                    <a href ng-click="tab.setTab(3)">Groups</a>
                </li>
                <li ng-class="{ active: tab.isSet(4) }">
                    <a href ng-click="tab.setTab(4)">Chart</a>
                </li>
                <li ng-class="{ active: tab.isSet(5) }">
                    <a href ng-click="tab.setTab(5)">Specification</a>
                </li>
            </ul>

            @*First Tab Project Info*@

            <div ng-show="tab.isSet(1)">
                <h4>General Project Information</h4>
                <div>.....General form...</div>
    </div>
       <div ng-show="tab.isSet(2)">
                <h4>Further Information</h4>
                <blockquote>And so on </blockquote>
     </div>
// Other tabs follow similar structure....

The issue I am facing is that while the tabs are switching correctly with ng-click events, I am unable to change tabs successfully upon the completion of the post event in the controller function.

I would greatly appreciate any assistance or guidance. Note: I am relatively new to AngularJS.

Answer №1

The reason for the issue in your promise then function is that the "this" keyword does not refer to the controller's "this". To solve this, you can create a new variable to reference "this" and use it in the return function. In this code snippet, I have named the variable as rootThis:

app.controller('createProjectController', ['$scope', 'resourceProject', function ($scope, resourceProject) {

    this.tab = 1;

    var rootThis = this;

    this.setTab = function (newValue) {
        this.tab = newValue;
    };

    this.isSet = function (tabName) {
        return this.tab === tabName;
    };

    $scope.project = {};

    $scope.postProject = function () {

        // console.log("Post  Here");
        // $scope.project.Id = null;
        resourceProject.postEvent().save($scope.project)
            .$promise.then(
            function (response) {
                console.log("Saved");
                //console.log(response);
                $scope.project = response;
                //Does not recognize this action
                console.log(rootThis.tab);
                // Not Working
                rootThis.tab = 2;
                // Not working setTab(2);

            },
            function (error) {
                console.log("It was broken !");
            });
    }
}]);

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

Tips for filtering table data with AngularJS filter based on a selected value

I have a table with a column of Status, and I want to filter the table based on their status using a selection element. Below is my code for the selection: <select class="form-control" ng-model="OrdinanceStatus"> ...

Django RGBField cannot locate jQuery

Working on a project that utilizes an RGBField, the following script is injected into the template (nested deep within django's structure, as its exact location remains elusive): <script type="text/javascript"> (function($){ ...

How to change a value within an array stored in local storage using Vanilla JavaScript?

I recently started learning vanilla JavaScript and followed a tutorial on creating a shopping cart. While the tutorial was helpful, it was cut short and I had to figure out how to update a value in a local storage array by clicking a button on my own. Can ...

Modify input value using jQuery upon moving to the next step

When you type into an input[text] and press the tab button, it automatically moves to the next input. If you fill out all the inputs and then want to re-fill them, the values will be highlighted in blue. However, I wanted to achieve this without having to ...

What is the process for removing globally declared types in TypeScript definitions?

There are numerous libraries that cater to various platforms such as the web, Node servers, and mobile apps like React Native. This means they can be integrated using <script /> tags, require() calls, or the modern import keyword, particularly with t ...

How can I prevent users from inputting negative numbers in a cellEditable material-table?

In my project, I am utilizing a material table with editable cells. I need to implement a restriction that prevents users from entering negative numbers in the field and displays an error validation message. How can I achieve this functionality? Check out ...

Moving files by dragging and dropping rather than deleting them

I have successfully implemented a feature using JavaScript to drag and drop multiple files, followed by displaying those images. The code below is fully functional without any errors. Need help with: I am now looking to add the ability to remove these ima ...

Is there a way to have the headline gently fade in and subtly rise when the page loads using CSS?

Is it possible to make the headline fade in and move up slightly on the home page using CSS after the user lands on the website? For a visual reference, check out this example on . I know it can be achieved with translateY, but I have never tried it before ...

Is AngularJS known for its ability to bind variables across different components effortlessly

In the beginning of my Angular controller, I use Promises to download JSON data and then store it in variables: app.controller('mainController', ['$scope', '$http', '$q', function($scope, $http, $q) { var req1 = $ ...

Is there a native feature in Vue.js that allows for the addition of a duplicate of a constantly saved object to an array that is repeated

Having an issue with my Vue.js app where adding a newItem to a list of items results in the added object being bound to the input. Here's what I've tried so far: new Vue({ el: '#demo', data: { items: [ { start: & ...

Adding a Bearer Token to a GET request using location.href: A step-by-step guide

At the moment, I have all my ajax requests sending an Authentication token. However, I have created a service for exporting to excel and since ajax doesn't support that, I am using location.href for the get request. Is there a way to include the token ...

Issue: Incompatibility in metadata versions detected for module .../ngx-masonry/ngx-masonry.d.ts. Level 4 version identified, whereas level 3 version

When using ngx-masonry, I encountered the following error message- ERROR in Error: Metadata version mismatch for module .../ngx-masonry/ngx-masonry.d.ts, found version 4, expected 3 Specifications: Angular 4 ngx-masonry 1.1.4 ...

Storing a temporary value within an ng-repeat iteration in AngularJS

A unique and interesting query arises when dealing with random value generation. Here is a snippet of code that showcases how to achieve this: function randomize() { return function (input) { if (input !== null && input !== undefined & ...

Browsing through items within arrays to evaluate their values

I am facing an issue with two arrays that consist of objects. The first array contains restaurant objects with attributes such as name and averagePrice, while the second array has price objects (cheap, medium, expensive) with properties like label, lowEnd, ...

How can I effectively retrieve configuration data from multiple JSON files and use it within the $scope of a controller in Angular 1.6?

I am trying to fetch and store 2 JSON data sets in $scope within my controller before performing a basic operation. However, the $http service in my factory is returning the state object as it returns a promise. Here is my Provider as a factory object: ( ...

Guide to sending a POST request from within my application

I'm facing an issue with using $resource for making a post request in my app. Here is the code snippet from my Angular module: angular.module('myApp').factory('Product', ['$resource', function ($resource) { ...

Could using 'require' in node.js lead to a memory leak issue?

I have been working on a program that experiences continuous heap growth. The program is quite simple - it repeatedly tries to load an external file (SyntaxError) using require. However, this external module fails to load due to a syntax error present in i ...

What is the best way to incorporate a transition on transform using Styled-components?

I attempted to add a transition on the transform property, but unfortunately, it did not produce any visible changes. I tested other properties such as: background-color, color... and they worked perfectly fine. live code: source code: // styled-compo ...

Navigate to the end of the progress bar once finished

I have a solution that works, but it's not very aesthetically pleasing. Here is the idea: Display a progress bar before making an ajax call Move the progress bar to the end once the call is complete (or fails) Keep the progress bar at 90% if the aj ...

Having trouble with the "next" pagination button not loading cards, even though the numbered buttons are working perfectly

My pagination numbers are functioning correctly, but I'm having trouble with my "next" or "previous" buttons. I am using Bootstrap 5 and jQuery to load cards from an array. The issue seems to be with the currentPage variable in my displayList function ...