Is it possible to utilize md-select from Angular Materials to execute a function?

Encountering a peculiar issue with the md-select element - I may be using it incorrectly. The goal is to redirect to a new page or sign out based on the selected option, but instead, I'm faced with this error:

Error: Failed to execute 'removeChild' on 'Node': The node to be removed is not a child of this node.

Here is the HTML code:

<md-select placeholder="DISRUPTIVE" ng-model="activePage" ng-change="changeSelected()">
   <md-option value="settings">Settings</md-option>
   <md-option value="logout">Sign Out</md-option>
 </md-select>

And the controller code:

$scope.changeSelected = function(){
      switch ($scope.activePage) {
      case "settings":
        $location.path( '/account');
        break;
      case "logout":
        $scope.logout();
        break;
    }

    };

The error occurs after navigating to the selected page or logging out. Is it possible that md-select cannot be used in this manner?

Update: The issue seems to be related to leaving the page before md-select completes its action. Adding a $timeout resolves the error, albeit not an ideal solution:

$scope.changeSelected = function(){
      $timeout(function() {
        switch ($scope.activePage) {
        case "settings":
          $location.path( '/account');
          break;
        case "logout":
          Auth.logout();
          break;
      }
    }, 1000);

Answer №1

If you want to listen for changes on a select element, all you need to do is include an ng-change directive. Take a look at this straightforward example:

<div ng-app="selectDemoBasic" ng-controller="AppCtrl" layout="column" layout-align="center center" style="min-height: 300px;">
  <md-select placeholder="Pick" ng-model="someVal" ng-change="selectChanged()">
    <md-option value="1">One</md-option>
    <md-option value="2">Two</md-option>
  </md-select>
</div>

Here is the corresponding JavaScript code:

angular.module('selectDemoBasic', ['ngMaterial']).controller('AppCtrl', function($scope) {
  $scope.selectChanged = function(){
    alert("value changed-->"+$scope.someVal);
    if ($scope.someVal==1){
      $scope.otherFunction();
    }
  };

  $scope.otherFunction = function(){
    alert("in the other function");
  };
});

For a live demo, you can visit http://codepen.io/Eylen/pen/dobbqg/

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

Issue encountered while sending binary data to the server

After attempting to read a local file on the client side and sending it to the server, I encountered an error while trying to retrieve the image. JavaScript let req let rsp async function _post(url,data) { req = await fetch(url,{method: 'POST' ...

Guide to presenting JSON data with ajax

I am trying to dynamically display data based on the selected value from a drop-down list using Ajax's GET method. The idea is to modify the URL by appending the selected item in order to retrieve relevant data from the server: Here is an example of ...

What is the best way to utilize mapping and filtering distinct values in an array using TypeScript?

What is the best way to filter and map distinct elements from an array into another array? I've experimented with various methods but keep encountering a syntax error stating "Illegal return statement". My objective is to display only unique items f ...

Titanium: Warning upon initiation

Is it feasible to trigger an alert immediately after a window finishes loading? I am using a create window function followed by an alert message, then returning. function NewView() { var self = Ti.UI.createWindow({}); alert("A basic or confirm al ...

Exporting data acquired from a MongoDB query using Node.js

I am currently working on exporting the contents of a MongoDB collection by using exports.getAllQuestions = async function (){ MongoClient.connect(url, function(err, db) { if (err) throw err; var dbo = db.db("Time4Trivia"); ...

What are the best ways to resolve the warning from webpack in Express?

I have set up webpack to bundle both the server and client side code... Below is my webpack configuration: const webpack = require('webpack'); const path = require('path'); const HtmlWebpackPlugin = require('html-webpack-plugin&a ...

Skipping code in JavaScript/jQuery function on window load

I have created a function that applies specific CSS rules to elements when the window is fully loaded. Check out my code below: function applyHover() { $('.view_preloader .overlay').css('opacity',1); $('.view_pre ...

How can I eliminate unwanted zombie events in Vue JS?

How do you get rid of a zombie event? When navigating back and forth, the events run multiple times. MainApp.vue <template> <input type="button" @click.prevent="handleClick()" value="Click Me"> </template> <script> export defa ...

Issue with directive in AngularJS: When trying to access scope.data, it appears

Initially, I came across the API address in this discussion: Laravel 4 and Angular JS and Twitter Bootstrap 3 Pagination Now, I am delving into this topic, and my script snippet goes like this: var app = angular.module('category', [ &ap ...

Check if the content key Json exists by implementing Vue

Can anyone help me with checking the existence of "novalue"? For instance: { name: "maria", city_id: "novalue" .... } What would be the best way to do this in Vue? Should I use <div v-if="condition"> or a function? ...

Ways to showcase numerous records in Ember.js template using hasMany relationship?

The model I have defined looks something like this: App.Question = DS.Model.extend({ title: DS.attr( 'string' ), answers: DS.hasMany('App.Answer') }); App.Answer = DS.Model.extend({ title: DS.attr( 'string&ap ...

Is there a way to customize CKEditor to prevent it from continuously adding <p></p> tags within the textarea automatically?

As I was going through the CKEditor tutorial, I implemented the following: $( '#editor' ).ckeditor(function(){}); //it's working great!! However, after submitting the form, I noticed that by default, the textarea displays <p></p ...

"What is the process of inserting data into an array using the push() method in

Could someone please explain how to use push() to add data after a button is clicked? Any assistance would be greatly appreciated. function myCtrl($scope){ $scope form ={companyName :"company1",companyAddress:"company address",staff[{name:"men",id:"123" ...

Updating a JSON property in JavaScript on the fly

I am looking to dynamically replace the content of "placeholder" with {"John": "Dough"} using a function call. This initial method seems to work fine: a = {foo:{bar:{baz:"placeholder"}}}; a.foo.bar.baz = {"John" : "Dough"}; console.log(JSON.stringify(a)) ...

Adding query parameters dynamically in Vue without refreshing the component

I'm attempting to update the Query Parameters in Vue without refreshing the component using Vue-Router. However, when I use the code below, it forces a component reload: this.$router.replace({query: this.filters}); Is there a way to prevent the comp ...

In Vue.js, leverage the power of slots to access content from deeply nested child components

Recently, I came across this example: This child component serves as the foundation for all the components that follow. <template> <div class="content-box"> <div class="boxtitlecontainer titleColor"> <slot name="title"> ...

Is there a way to create a list of languages spoken using Angular?

I am in search of a solution to create a <select> that contains all the language names from around the world. The challenge is, I need this list to be available in multiple languages as well. Currently, I am working with Angular 8 and ngx-translate, ...

Testing AngularJS components with header response verification

After a successful login on my web, the backend sends me an 'x-token'. In my frontend, I validate this token by setting $rootScope.authenticated = true;. If the token is missing from the header response for any reason, my frontend sets $rootScope ...

What is the best method for compressing and decompressing JSON data using PHP?

Just to clarify, I am not attempting to compress in PHP but rather on the client side, and then decompress in PHP. My goal is to compress a JSON array that includes 5 base64 images and some text before sending it to my PHP API. I have experimented with l ...

Is there a viable substitute for websockets that can be utilized on shared hosting platforms?

Are there any viable alternatives for websockets that can be used with shared hosting? While I'm aware of node.js, socket.io, and Express.js, I'm unable to use them in a shared hosting environment. If there are other options available for creatin ...