The AngularJS select field is not showing the selected option

I developed an Angular directive like this:

'use strict';

angular.module('countrySelect', [])
  .directive('countrySelect', ['$parse', function($parse) {
    var countries = [
      { code: "af", name: "Afghanistan" },
      { code: "ax", name: "Åland Islands" },
      { code: "al", name: "Albania" },
      { code: "dz", name: "Algeria" },
    ];

    return {
      template: '<select ng-options="c.code as c.name for c in countries">',
      replace: true,
      link: function(scope, elem, attrs) {
        scope.countries = countries;

        if (!!attrs.ngModel) {
          var assignCountry = $parse(attrs.ngModel);

          elem.bind('change', function(e) {
            assignCountry(elem.val());
          });

          scope.$watch(attrs.ngModel, function(country) {
            elem.val(country);
          });
        }
      }
    }
  }]);

In the HTML template, I have a select field set up like this:

<div country-select ng-model="citizenship"></div>

After selecting an option, the model updates with the country code as expected. However, the country name does not appear in the select field until I reselect it.

The current process is as follows:

  1. Click
  2. Select country
  3. Model updates with country code, but name doesn't display in the select field
  4. Click and reselect
  5. Name appears in the select field

How can I make the select field show the country name upon selection?

Answer №1

When utilizing replace: true, the original ng-model="citizenship" will automatically be applied to the select element, eliminating the need to manage select change events for updating ngModel. The directive can be simplified to:

angular.module('countrySelect', [])
.directive('countrySelect', [function() {
    var countries = [
        { code: "af", name: "Afghanistan" },
        { code: "ax", name: "Åland Islands" },
        { code: "al", name: "Albania" },
        { code: "dz", name: "Algeria" },
    ];

    return {
        template: '<select ng-options="c.code as c.name for c in countries"></select>',
        replace: true,
        link: function(scope, elem, attrs) {
            scope.countries = countries;
        }
    }
}]);

Check out the demo here: http://plnkr.co/edit/9aBhrlIqPIGkGTNTwIb6?p=preview

Answer №2

Consider utilizing $apply() to trigger a manual update of the view. Learn more here

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

Refining the data displayed in an angular table based on the value chosen from a dropdown list

In order to filter the JSON data in a table by movie genre selected from a dropdown menu, I am looking to display each genre only once. Currently, all genres are being pulled in for each movie. JSON sample: { Rank: 1, Duration: "1 hr. 47 min.", Descripti ...

Unexpected Disconnection of AJAX Response Moments Before Rebooting the Raspberry Pi

I currently have a LAMP server set up on my Raspberry Pi 4, where a web page is utilizing an AJAX call to trigger a php script that initiates a reboot of the pi. The php script echoes a JSON string response back to the web page indicating that it is prepar ...

Executing function statement

I'm currently learning about React hooks, and I have a question regarding the behavior of two function expressions within different useEffect hooks. In one case, the function expression named timerId in the first useEffect is invoked automatically wit ...

The TypeScript error message reads: "You cannot assign type 'undefined' to type 'ReactElement'."

I'm encountering an error in my react project TypeScript error Argument of type 'ReactNode' is not compatible with parameter of type 'ReactElement<any, string | JSXElementConstructor<any>> | ReactElement<any, string | JSX ...

Ways to update the contents of an individual div within an ng-repeat loop

I am currently working on some Angular code. <div ng-repeat="item in items | filter:search" class="container"> <h3>{{item.name}}</h3> <p>category:{{item.category}}</p> <p>price:INR {{ ...

What makes Safari for Windows stand out when it comes to AJAX?

What sets Safari for Windows apart when it comes to handling AJAX requests? Moreover, are there any potential issues or challenges I should be aware of? ...

Inaccurate Feedback on Maquest Direction Route API

Currently, I am in the process of implementing the MapQuest API Direction Routing function on my website. However, upon submitting a request to the API, it is returning inaccurate routing points between two destinations. Here is the request form that I am ...

Node.js & Express: Bizarre file routes

It's quite strange how my local paths are functioning. Let me show you an example of my directory structure: public > css > bootstrap.css public > js > bootstrap.js templates > layout > page.ejs (default template for any page) tem ...

Unable to utilize jQuery library in AngularJS partial HTML files, despite being loaded in the index.html file

I have been working with a web template that utilizes jQuery image gallery and other elements. Now, I am looking to convert this template into an AngularJS structure. To do so, I have created partial HTML pages like slider.html or contact.html along with t ...

Struggling to develop a Singleton AngularJS Service?

I am in the process of creating a Singleton AngularJS service using the 4th method. The structure of my service is as follows: provider('SocketService', { socket: null, // methods used within the config() of a module connect: functi ...

Utilizing Angular 4 Typescript to create cascading drop-downs within a table

As a newcomer to Angular, I am in the process of building my first application using Angular 4 and TypeScript. I would like to implement Cascading dropdowns within a table using Angular 4. Currently, I am facing an issue where changing the dropdown selec ...

Remove information using Axios in ReactJS by interacting with an API

I have successfully pulled data from the jsonplaceholder API and stored it in my state. However, I am struggling with implementing the deleteContact() method to remove the data. Can anyone provide guidance on how to properly execute the deleteContact() met ...

Allow only specified tags in the react-html-parser white list

Recently, I've been working on adding a comments feature to my projects and have come across an interesting challenge with mentioning users. When creating a link to the user's profile and parsing it using React HTML parser, I realized that there ...

What causes Angular2 to detect both reference changes and primitive changes even when the OnPush flag is enabled?

Take a look at this code snippet import {Component, OnInit, Input, OnChanges, DoCheck, ChangeDetectionStrategy} from 'angular2/core' @Component({ selector: 'child1', template: ` <div>reference change for entire object: { ...

`How can I customize the appearance of individual selected <v-list-item> across various sub-groups?`

As a newcomer to Vuetify and Vue in general, I am struggling to solve a specific issue. I need to create multiple sub-groups where only one option can be selected within each "parent" list. Consider an array of cats: options:["Crookshanks", "Garfield", " ...

How can you access the input value from load dash's debounce function in a Vue.js application?

Is there a way to capture the input entered during the @typing event of the b-autocomplete component in Buefy? During the @typing event, the debounce method is called with specific parameters as shown below- <b-field label="Location"> ...

The "disabled" attribute is no longer recommended, please utilize "disable" instead

Lately, after upgrading AngularJS, I have been receiving a warning whenever I open a ui.bootstrap modal. The warning in Chrome-beta 44 says: angular.js:11655 Use of "disabled" attribute has been deprecated, please use "disable" I'm curious if this i ...

ViewContainerRef fails to render component on the DOM

@Component({ selector: 'my-cmp', template: ` <div #target></div> ` }) export class MyCmp { @ViewChild('target', {read: ViewContainerRef}) target : ViewContainerRef; render() { let component = createComponent(met ...

The null node is causing an error when trying to access the 'name' property

Defining Schema for Campground var campgroundSchema = new mongoose.Schema({ name: String, image: String, description: String, _id: String }); var Campground = mongoose.model("Campground", campgroundSchema); app.get("/campgrounds/:id" ...

Utilizing Webpack to bundle libraries for package management

Hello there, I am currently dealing with a legacy application that relies on various libraries such as jQuery, moment.js, and underscore. These libraries were manually assembled and added to the repository in a loosely coupled manner. My goal is to transi ...