ng-option featuring a stationary link option

How can I create a static option that links to another page using ng-options?

<select class="form-control"
        ng-model="person"
        ng-options="person.name for person in persons">
</select>

I am trying to use the select element with ng-options and a predefined list of persons, where each person is an object. I attempted to use ng-repeat instead, but it was unsuccessful:

<select ng-model="person" onChange="window.location.href=this.value">
    <option value="#/home">Anywhere</option>
    <option value="#/current" ng-repeat="person in persons">{{person.name}}</option>
</select>

The variable $scope.person holds the value "#/current". In this case, the linking works, but ng-model fails. The variable $scope.person should represent the selected person.

I expect that $scope.person will have the selected value, unless the user chooses "Anywhere", in which case they should be redirected to another page.

"#/home" and "#/current" represent different URL locations. "#/home" is the home page and "#/current" is the current page. The onChange event redirects the user to the home page or reloads the current page.

Therefore, when the user selects "Anywhere," they should be redirected to the home page. For any other option, the user's page should remain unchanged.

Answer №1

It's important to avoid mixing native JavaScript and AngularJS unless you fully understand what is happening.

Instead of using onchange, use ng-change and check if the value is 'Anywhere'. If it is, then route accordingly; otherwise, take no action. In your current approach, you are redirecting in both cases.

<select ng-model="person" ng-change="selectHandler()">
    <option value="">Anywhere</option>
    <option value="{{prsn}}" ng-repeat="prsn in persons">
        {{prsn.name}}
    </option>
</select>

$scope.selectHandler = function(){
    if($scope.person == ''){
        console.log("route to /home");
        //ROUTE WITH $location.path
    }
}

You can view a working FIDDLE for demonstration purposes.

Answer №2

When using ng-repeat, ensure your syntax is correct:

ng-model="person"

This will not work because the correct syntax is ng-repeat="person in persons"

Instead, use:

ng-model="persons"

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 with SharePoint Rest API search query functionality

Hey there! I'm currently facing issues with calling the Sharepoint Rest API for a search query. I can't seem to figure out why it's not working. Additionally, I'm unsure if my URL input is correct. Below is the code snippet I've w ...

I keep encountering a persistent net::ERR_CONNECTION_REFUSED error when attempting to make a POST request to https://localhost:5000/users/add. Despite trying various solutions recommended online, I still cannot

I'm currently developing a workout tracker app using the MERN stack. As part of this project, I have a React JS component that is responsible for adding a new user to the database when the submit button is clicked. To achieve this functionality, I am ...

Retrieve information dynamically from a JSON file using the get JSON function and iterate through the data

I possess a JSON file that I wish to utilize in creating dynamic HTML elements with the JSON content. Below is the provided JSON data: { "india": [ { "position": "left", "imgurl":"3.jpg" }, { ...

Guide to activating a reaction following an occurrence in a React component

I have started developing a React application that loads blog posts along with their associated comments. The challenge I am facing is how to trigger a refresh of the comments component and display the new comment immediately after it has been submitted. ...

Troubleshooting AngularJS: Diagnosing Issues with My Watch Functionality

I need to set up a watch on a variable in order to trigger a rest service call whenever its value changes and update the count. Below is the code snippet I have: function myController($scope, $http) { $scope.abc = abcValueFromOutsideOfMyController; ...

Is there a way to eliminate duplicate elements from 2 arrays in Angular?

Imagine I have a scenario with two arrays: arr1 = ["Tom","Harry","Patrick"] arr2 = ["Miguel","Harry","Patrick","Felipe","Mario","Tom"] Is it possible to eliminate the duplicate elements in these arrays? The desired output would be: arr2 = ["Miguel"," ...

Poor internet connection causing issues with rendering AngularJS app

I was initially enthusiastic about learning AngularJS, so I dove right in. However, my excitement turned to disappointment when I realized that AngularJS does not handle content well on slow internet connections, as evidenced by the screenshots. My Flask ...

A step-by-step guide on incorporating box-shadow for the jackColor in the Switchery Plugin

I am looking to add a box shadow to my iOS7 style switches for checkboxes when they are checked. Here is the code I have so far: var elems = Array.prototype.slice.call(document.querySelectorAll('.js-switch')); elems.forEach(function (html) { va ...

Tips for accessing the values of fields in React Material UI components

When I console log the object, it shows: { "week":undefined, "name":undefined, "code":undefined } Additionally, is it appropriate to wrap all Material UI components in a form tag and treat the entire code as a form? Here is ...

Unable to Retrieve Response from jQuery AJAX in a Function

Having some trouble with a jQuery AJAX function that is supposed to retrieve data from a file. I can't seem to get the function to return the actual value. Any suggestions? $(document).ready(function () { function fetchData() { ...

NodeJS process that combines both client and server functionality

Attempting to develop a test echo server with both client and server in the same node process. When the code is split into two files (server and client), it functions correctly, but when combined into one file, it fails. How can I make it work within a sin ...

Add items to a separate array only if the material UI checkbox is selected

Exploring the world of React, I decided to create a simple todo app using React JS and Material UI. With separate components for user input (TodoInput.js) and rendering individual todos with checkboxes (TodoCards.js), I aim to display the total number of c ...

If you invoke revokeObjectURL, Chrome will fail to display Blob images

-----update------ After some investigation, I found that commenting out window.URL.revokeObjectURL( imgSrc ); fixed the issue in all browsers. It seems like Chrome was revoking the URL too early. I am curious to understand why this behavior occurs, and if ...

What is the best way to transmit two distinct sets of data from a child component to the v-model of a parent component?

Currently, I am working on a project using vuejs 2 and typescript. In this project, I need to pass two different sets of data - data and attachments - within the parent component. I am utilizing vue-property-decorator for this purpose. However, I am facing ...

What are the differences between using attachShadow with the "mode" set to open compared to closed

I've recently delved into the world of Shadow DOM through some casual video watching. It seems like many people are quick to dismiss this feature, with comments like "Just keep it open" and "It's less flexible when closed." attachShadow( { mode ...

Securing AJAX Requests: Encrypting GET and POST Requests in JavaScipt using Node.js

Looking for a way to secure ajax post and get requests using JavaScript. The process would involve: Server generates private and public key upon request Server sends the public key to client Client encrypts data with public key Server decrypts data wit ...

Issues with the .change(function() JavaScript in Internet Explorer versions less than 9

I'm experiencing issues with this script in Internet Explorer versions below 9. Can someone please help me identify what is wrong with my script? Thank you. IE7 and IE8 are showing the following error: SCRIPT87: Invalid argument. Found ...

Angularfire2: Access Denied Error When User Logs Out

When utilizing the following method: login() { this.afAuth.auth.signInWithPopup(new firebase.auth.GoogleAuthProvider()) .then(() => { this.router.navigate(['']); }); } An error occurs during logout: zone.js:915 Unca ...

Keeping track of both the search query and the results

I have stored the current search term in a state using e.target.value as searchField, but when I clear the input value, I can no longer use it. I want to display a message in the body informing the user that their specific searched term yielded no results, ...

The footer is not extending all the way to the bottom when using a flex layout

While working on my website, I attempted to create a sticky footer. To achieve this, I used JavaScript to dynamically generate the <footer> element in order to keep it at the bottom of the page at different screen widths. My goal was to append the f ...