Leaving a state in Angular after selecting an empty option in the ng-repeat on a select element triggers

When working with angular.js, I am dynamically generating options for a <select> element using the ng-repeat directive.

Instead of using ng-options, I opted for ng-repeat because this is for an empty form where I needed to set default values for selected and disabled, as well as have a final option not in the model.

var form = {}; // This object will store form data, including form.boro

var boros = {"BK":"brooklyn","Q":"queens","NY":"manhattan","BX":"bronx","SI":"staten island"}

<select class='form-control capitalize' name="city" ng-model='form.boro' >
    <option value="" >City</option> 
    <option ng-repeat="(k, val) in boros" value="{{k}}">{{val}}</option>
    <option value='other'>Other</option>
</select>

Although this setup successfully generated the intended element and options, it caused the following error:

TypeError: Cannot read property '$$phase' of null

This error was triggered by setting value="" in

<option value="">City</option>

The application continued to function without crashing, but I am interested in understanding why this occurs upon state exit and if there might be a mistake in my implementation.

Answer №1

It appears that adding the attributes selected and disabled to the initial empty option resolves the issue.

<option value="" selected disabled >City</option>

Seems like I missed that detail :/

Answer №2

It seems like there may be an issue with the {{city}} selection in the dropdown menu. There might not be a corresponding model available for it. If we display both the {{boro}} as a value and the {{city}} as text, there needs to be a relationship established between the city and boro. Another approach could be storing all cities in an array of objects and retrieving the city value by passing the boro key to a controller function like {{getCity(boro)}}. The boro can then be set using ng-model="boro".

Answer №3

Upon examining your code snippet, it seems that the issue lies in not placing your objects in an array. It appears that ng-repeat operates on a collection of objects. To address this, you can organize your options in an array using the following format for example: [{code: BQ, city: Brooklyn}]. See the updated code below:

app.controller('MainCtrl', function($scope) {
    $scope.form = {}; 
    $scope.boros = [
      {code: "BK", city: "brooklyn"}, 
      {code: "Q", city: "queens"},
      {code: "NY", city: "manhattan"},
      {code: "BX", city: "bronx"},
      {code: "SI", city:"staten island"}
    ]
});

Here is the revised template:

<select class='form-control capitalize' name="city" ng-model='form.boro' >
    <option value="" >City</option> 
    <option ng-repeat="boro in boros track by $index" value="{{boro}}">{{boro.city}}</option>
    <option value='other'>Other</option>
</select>

You can view the changes in action on this Plunker link.

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

Invert the motion within a photo carousel

Is there anyone who can assist me with creating a unique photo slider using HTML, CSS, and JS? Currently, it includes various elements such as navigation arrows, dots, and an autoplay function. The timer is reset whenever the arrows or dots are clicked. Ev ...

Creating a specialized pathway with variable inputs within the URL

As a Node beginner, I am facing a challenge with an Express exercise on dynamic routes. The task at hand is to create a route that can accept dynamic arguments in the URL path and respond with a quote from the respective author. Here's a snippet of th ...

The Ajax query returned a successful response, yet it unexpectedly triggered an error

Currently, I am delving into the realm of mongodb. I have integrated Express, Body-Parser, and Mongoose into my project, and I'm retrieving data from an online mongodb database hosted on mlab. Everything seems to be functioning smoothly as I've t ...

Utilizing React with Firebase involves executing several Firebase requests simultaneously and ensuring the completion of all promises

I'm facing a challenge with the current code where it hits Firebase's 10 item limit in an array. My goal is to iterate through all teamIds and execute a Firebase query for each individual teamId. However, I'm unsure how to ensure that the ex ...

Step by step guide to verifying email addresses with Selenium WebDriver

A feature in my EXTJS application includes a page with an Email button. When this button is clicked, it generates a link to the page contents and opens the default email client with this link in the body. Upon inspecting the DOM, I found that the Email bu ...

The command "json_encode($array)" does not seem to be encoding the complete array

I ran a test on the following: <? echo json_encode($array) ?> result: ["PG","Kevin Sad","8000","12"] Upon placing it within a form option value to be selected by my script function: <option value=<? echo json_encode($array) ?> > op ...

Is there a way to restrict input to numeric characters exclusively in Swal Sweetalert?

I'm wondering how I can restrict input to only numeric values in this section. { title: "Dollar Amount?", text: "How much is your Dollar Question worth?", inputPlaceholder: "Enter Amount" } I'm currently utilizing a Sweetalert p ...

Tips for updating the value of a $scope variable and running tests with AngularJS Jasmine

For my initial case, the product id should be undefined. var $stateParamsStub = { scheduleId : undefined } Within my controller, I am determining if isUpdate should be true or false. If the productId is undefined, then isUpdate should be false; other ...

Obtain appended data from the formData

After creating a new FormData object and adding 'caption' as the key, how can I retrieve the value 'abc'? Using the .get method doesn't work in mobile Chrome due to lack of support. Is there an alternative method to get the caption ...

Reacting to URL Changes but Failing to Load the Requested Page

Welcome to my App Component import React, { useEffect } from 'react'; import './App.css'; import Navbar from './components/layout/Navbar'; import Landing from './components/layout/Landing'; import { BrowserRouter as ...

Capturing the value of a child element using an Angular directive

When I include scope: {finishcallback: "&"} in my directive, the binding of values with $scope.minutes = 1 to ng-bind="minutes" stops working. I am currently working on creating a countdown timer using Angular directives. However, I am facin ...

Exploring different methods to locate a random ID using XPATH, CSS path, and selector while conducting Selenium c# testing on a CMS tool

Issue: Hey there, I'm currently working on testing a CMS tool with selenium in C#. The problem I'm facing is finding a suitable selector for a small drop-down button due to the random generation of IDs for all selectors. Every time the script run ...

Using Various Initialization Techniques to Find the Difference in Javascript Arrays

Could someone please clarify why there are varying results in the Javascript Console (Node 7.2.0): The behavior of arrays in example I differs from that of examples II and III. EXAMPLE I > var x = new Array(3).fill(new Array(2).fill(0)) > x [ [ 0, ...

What's the reason behind the jQuery tools CDN link directing to an advertisement?

Can you please explain why the link directs to an advertisement? ...

Is it possible to determine the status of the cover by inspecting the element?

Recently, I've been contemplating the idea of adjusting my background image to move around a bit. It seems like a fancy concept and not too difficult to execute. However, I am facing an issue because my background image is currently set to cover (back ...

To resolve the issue in Node, address the following error message: "User validation failed: username: Path `username` is required. Password: Path `password` is required."

I am currently in the process of creating a new user and verifying if the user's email already exists. If it does not exist, a new user is created and saved. Can anyone help me identify and correct the validation error I am encountering? I have attem ...

Encrypting data using pidCrypt in a combination of Javascript and PHP

Currently, I am in the process of developing an encryption system to secure sensitive information on my website. My web hosting service requires an additional fee for SSL, which I am not prepared to invest in at this moment. I experimented with utilizing ...

Utilizing Jquery to locate a link inside a Div and displaying it as specified in the HTML

Looking for a solution to make div elements clickable as links? The usual methods involving window.location or window.open may not be suitable if you have numerous divs with predefined targets. If you're not well-versed in Javascript, finding the righ ...

retrieve fresh information from the API

Hello! I am attempting to retrieve new data from an API by filtering it with a JSON file. My goal is to filter the data from the API using the JSON file and extract any new information. const jsnf = JSON.stringify(fs.readFileSync("./data.json" ...

How can you extract the property names of the first object in an array of objects?

I have an array of objects with the following structure and I want to extract the property names of the first object from this array without including the values. The desired result should only be ["Name", "Account", "Status"] ...