Using the $scope.$watch method in combination with Angular material allows

Is it possible to change the route (ui.router) when a user closes the form in a sidenav?

When I click on cancel, everything works fine and returns to the root URL. However, if I click anywhere on the page and close the sideNav, I remain on the /new URL.

I'm new to Angular and Angular-Material.

(function () {

"use strict";

angular
        .module("ngClassifieds")
        .controller('newClassifiedsCtrl', function ($mdSidenav, $state , $mdDialog, classifiedsFactory, $timeout, $scope){

            var vm = this;
            vm.closeSidebar = closeSidebar;

            $timeout(function(){
                $mdSidenav('left').open();
            });

            $scope.$watch('vm.sidenavOpen', function(sidenav){
                if(sidenav === false){
                    $mdSidenav('left')
                            .close()
                            .then(function(){
                                $state.go('classifieds');
                            });
                }
            });

            function closeSidebar() {
                vm.sidenavOpen = false;
            }
})
})();

In the template:

<md-sidenav class="md-sidenav-left md-whiteframe-z2"
        md-component-id="left"
        md-is-open="vm.sidenavOpen">
<md-toolbar>
    <h1 class="md-toolbar-tools">Add a Classified</h1>
</md-toolbar>
<md-content layout-padding>
    <form>
        <md-input-container>
            <label for="title">Title</label>
            <input type="text"
                   id="title"
                   md-auto-focus
                   ng-model="classified.title">
        </md-input-container>
        <md-input-container>
            <label for="price">Price</label>
            <input type="text"
                   id="price"
                   ng-model="classified.price">
        </md-input-container>
        <md-input-container>
            <label for="description">Description</label>
        <textarea id="description"
                  ng-model="classified.description"></textarea>
        </md-input-container>
        <md-input-container>
            <label for="image">Image Link</label>
            <input type="text"
                   id="image"
                   ng-model="classified.image">
        </md-input-container>
        <md-button class="md-primary"
                   ng-click="vm.saveClassified(classified)"
                   ng-if="!editing">
            Save
        </md-button>
        <md-button ng-if="editing"
                   class="md-primary"
                   ng-click="vm.saveEdit()">
            Save Edit
        </md-button>
        <md-button class="md-warn" ng-click="vm.closeSidebar()">
            Cancel
        </md-button>

        <pre>{{ classified | json }}</pre>
    </form>
</md-content>

Answer №1

Keep an eye on the vm.sidenavOpen variable to detect when the sidenav is closed, specifically triggered by clicking the cancel button and not by clicking outside of it. Instead of relying on vm.sidenavOpen for this detection, consider implementing something like the following:

HTML

<md-sidenav id="sideNav" class="md-sidenav-left md-whiteframe-z2" md-component-id="left" md-is-open="vm.sidenavOpen"> //  add id='sideNav'
    .
    .
    .
</md-sidenav>

Controller

var firstTime = true;    // ignore sidenav closed state on page load
$scope.$watch(function(){
    return (!(document.getElementById('sideNav').getAttribute('class').indexOf('md-closed-remove') != -1) && (document.getElementById('sideNav').getAttribute('class').indexOf('md-closed') != -1))
}, function(value) {
    if(value && !firstTime) {
        $state.go('/classifieds')   // redirect every time sidenav closes (including click outside)
    } else
        firstTime = false;
})

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

Creating a Unique Navigation Bar Design in Bootstrap 4 with Custom Styling for Active

I have successfully added a navigation bar to my page, but I am currently facing issues with the active state. I want the navigation item to be underlined when it is active (when I am on that page) or when it is hovered over, and I also want brackets added ...

Interactive pop-up windows in Bootstrap

I encountered an issue with bootstrap modal forms where the form displays correctly after clicking on the button, but the area in which the form is displayed gets blocked! It's difficult to explain, but you can see the problem by visiting this link. ...

Quantities with decimal points and units can be either negative or positive

I need a specialized input field that only accepts negative or positive values with decimals, followed by predefined units stored in an array. Examples of accepted values include: var inputValue = "150px"; <---- This could be anything (from the input) ...

Mastering the utilization of API routes within the Next JS 13 App Router framework

As a newcomer to React JS and Next.js, I recently made the switch from using the Page Router API in Next.js to utilizing the new App Router introduced in Next.js 13. Previously, with the Page Router, creating a single GET request involved nesting your "JS ...

What is the fastest way to emulate CSS3 box radius for IE in terms of rendering speed?

There are numerous options available in JavaScript, .htc, and jQuery to create rounded corners for IE 6,7,8. (Not compatible with IE 8) http://code.google.com/p/jquerycurvycorners/ http://code.google.com/p/curvycorners/ Which solution offers the faste ...

Is it best practice to display a DIV once it is no longer visible after scrolling down?

Upon opening my website, an information box (div) appears on the screen. However, when the user scrolls down and the box is no longer visible, I want it to always appear in the top right corner while scrolling. I have figured out how to keep it visible at ...

Using JavaScript in Ext JS 4, transform a JSON object into a different JSON object

What is the simplest way to transform JSON A into JSON B using JavaScript? JSON A: { "d": [ {"__type":"Web.Controls.Shared.GeneralService+DropdownKeyValuePair","key":"0","value":"one"}, {"__type":"Web.Controls.Shared.GeneralServic ...

The POST method functions properly in the local environment, however, it encounters a 405 (Method Not Allowed) error in the

After testing my code locally and encountering no issues, I uploaded it to Vercel only to run into the error 405 (Method Not Allowed) during the POST method. Despite checking everything thoroughly, I'm unable to find a solution on my own. Your assista ...

Is there a way to send multiple parameters in an array to a route?

I am working on deleting multiple rows from a MySQL database using checkboxes in my ejs view with node.js and React app. I have successfully deleted a single row, but I am struggling to figure out how to pass an array of parameters for deleting multiple ro ...

Uniquely tag an uploaded file

My code for uploading files is as follows: var xhr = new XMLHttpRequest(); xhr.upload.addEventListener("progress", uploadProgress, false); xhr.open("POST", requestUrl, true); xhr.send(f); I want to draw your attention to the fact that I have attached a l ...

Arrays in Javascript (correlating)

I'm having trouble figuring out what needs to be included in this code (I apologize that it's in German, it's an array corresponding to images for JavaScript.) function namenZuBildern(){ var bilder = new Array( "000227", "000228", " ...

Creating an infinite SVG animation loop using JavaScript

elem = document.querySelectorAll("path"); function task(i) { setTimeout(function() { elem[i].animate({fill: 'green'}, { // timing options duration: 150, iterations: 1 }); }, 150*i); } for(var i=0;i<8;i++){ task(i); } < ...

Guide on how to transform form data into an object containing nested properties

Considering the inputs provided below: <input name="person[1]['first']" /> <input name="person[2]['first']" /> <input name="person[3]['first']" /> The objective is to convert this into an object structure a ...

Setting up Vue CLI 4 with ESLint, TypeScript, Stylelint for SCSS, and Airbnb rules in the VS Code editor with automatic fixes on save

After struggling with configuring Vue CLI 4 with ESLint, Prettier, Airbnb rules, TypeScript, and Vetur, I found myself at a crossroads. The challenges continued to mount as the nature of the problem evolved from my previous attempts.: How to configure Vue ...

Using JavaScript, transform a client's date/time string into a JSON-compatible date/time string

I need to find a way to convert a client's date/time string on a form into a JSON date/time string using JavaScript with moment.js for a Django REST API backend service. Here is the initial attempt: document.getElementById("dt_tm").value = moment(do ...

What is the best way to display JavaScript in a view in ASP.NET MVC 3?

Good day Everyone, I am currently facing an issue with a javascript variable in my view. This is what I have been trying to do... var skinData = null; and then, when the document is ready.... $.ajax({ type: 'POST', ...

JavaScript: The functionality of calling functions through buttons ceases to function once the page is updated without reloading

I am trying to create a program that consists of one HTML page, where I can dynamically update and populate it with different elements using JavaScript. The main feature of the program is a button that remains constant in every version and displays a mod ...

Exploring Next.js with Nested JSON Data

I'm struggling to retrieve the data from a JSON file in my Next.JS project, particularly when it comes to accessing nested arrays. I've managed to successfully display Home, One, and Two using the .map method, but I'm having trouble with Thr ...

Converting the Python/Flask Backend into a Vue.js Frontend Interface

Recently, I delved into the world of frontend to backend communications. To learn more about this concept, I decided to create a small backend program using the boto3 module in Python to fetch data. The backend program I created is functioning perfectly w ...

Executing numerous tests on a single response using Node.js along with Chai, Mocha, and Should

I have a setup similar to the one below that allows me to perform a series of API tests using Mocha. While this method works well, it involves making an individual API call for each test. My goal is to streamline the process by utilizing the same API cal ...