Having difficulty implementing two-way binding on SELECT element within Angular JS programmatically

Struggling with implementing two-way binding for SELECT elements. Attempting to dynamically change the selected element through code. While I've come across examples on Stackoverflow for binding the change event for SELECT, finding resources on the application code changing the selected element has been scarce.

Although some solutions involve using ng-repeat on an OPTION element, I haven't had much success making it work and it doesn't seem aligned with the "Angular Way".

HTML Code:

<div ng-controller="SIController">
<select id="current-command" ng-model="currentCommand"
ng-options="c as c.label for c in availableCommands track by c.id"></select>
<button ng-click="changeSelectedOption()">Select "open"</button>

Controller Code:

var myApp = angular.module('myApp', []);

function SIController($scope) {

    $scope.availableCommands = [
        {id: 'edit', label: 'Edit'},
        {id: 'open', label: 'Open'},
        {id: 'close', label: 'Close'}
    ];

    $scope.currentCommand = "close";
    $scope.changeSelectedOption = function() {
        $scope.currentCommand = 'open';
    };  
};

Despite confirming that $scope.currentCommand changes when the button is clicked, the OPTION element does not appear to be selected.

Access Fiddle here

Answer №1

Here is the functional fiddle: http://jsfiddle.net/bzhkkw18/9/

In order to clarify what was done, there was a discrepancy in the function name between the ng-click and the controller.

The key aspect was the definition of the option. In the ng-options, you assigned the entire object. If that is your intention, then you need to do the same for your currentCommand like so:

//Object 2 is close
$scope.currentCommand = $scope.availableCommands[2];

Answer №2

Dealing with a similar issue not too long ago, I found a solution that might help you out. Check out my response. You may need to adjust how ng-options is defined.

function NewCtrl($scope) {
    $scope.choices = [
        {name : "Option 1", id : 1},
        {name : "Option 2", id : 2},
        {name : "Option 3", id : 3}
    ];
    $scope.selectedChoice = $scope.choices[0].id;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.2/angular.min.js"></script>
<div ng-app ng-controller="NewCtrl">
    <select ng-model="selectedChoice" ng-options="selectedChoice.id as selectedChoice.name for selectedChoice in choices"></select>
    Selected Choice: {{selectedChoice}}
</div>

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

The ReCaptcha and AJAX Integration

I am attempting to display the ReCaptcha image using its AJAX API. I have been following the instructions from this documentation and observing the behavior of this demo. Despite my efforts, I am still unable to create a functional fiddle. I have added jsf ...

Browser displaying a CSS error: "Invalid property name" while applying pseudo-element :after

I encountered an issue in Chrome and Explorer while attempting to set a CSS property for a pseudo element :after. (I'm trying to create a styled burger nav icon) The error message I received was: 'Unknown property name' This happened wh ...

Retrieve the URL with a GET request and remove a specific object

Currently, I am working on developing a CRUD (Create, Read, Update, Delete) App using Express and LowDB. So far, I have successfully implemented the create and read functions, but I am facing issues with the delete function. This is an example of what th ...

Changing characters to asterisks using Javascript

I am currently working on a function that transforms all characters after the first word into asterisks. For example, if I have MYFIRSTWORD MYSECONDWORD, I would like it to show as: MYFIRSTWORD *** Currently, I'm using the code below which replaces ...

Issue with Hover Effect on Safari Browser

Encountering a peculiar issue exclusively in Safari - when hovering over a link in the header, the links to the right of the hovered-over link alter their size (appearing smaller) during the hover animation. Once the animation concludes, these links revert ...

Utilizing JavaScript for enhancing the appearance of code within a pre element

Is there a way to dynamically highlight the code inside a pre element using vanilla JavaScript instead of JQuery? I'm looking for a solution that colors each tag-open and tag-close differently, displays tag values in another color, and attributes with ...

Guide to making a JavaScript button that triggers an iframe to open upon user clicking the button

I'm currently enhancing the comment section for posts on my website. I am looking to implement a button in javascript that, when clicked, will open an iframe window displaying comments similar to how Facebook does on their post. If there are other lan ...

Strip away double quotation marks from object attributes except those beginning with a number

I've searched extensively and reviewed various Q&A forums, but I haven't encountered a scenario quite like this. Here's an example of the object I'm working with: props: { "label": "1rem", "text3": "1rem", "text2Button": "1re ...

Can double curly braces be added within an HTML attribute when using Vue?

Suppose I would like to include <input value='{{default}}'></input> in regular HTML. This will display a textbox with {{default}} as the default input. However, when attempting to achieve the same thing with Vue, it does not work as ...

How to incorporate a JavaScript class into a VueJS project

Looking to incorporate a JavaScript class into my Vue application. The class structure is as follows: class className { constructor() { ... } function1() { ... } static funtion2() { ... } } Attemptin ...

Modifications performed on the Xhtml generated from xml and XSLT should be mirrored back into the original XML document

After transforming an XML file with xsl and loading it into a browser as html, I am making the html editable using the content editable attribute of html5. How can I transform their edits back to the original xml document, even if they add new nodes to e ...

The data in Next.js getStaticProps does not update or refresh as expected

As I recently transitioned to working with Next.js, I have encountered several challenges. One issue that arose was related to the use of useEffect in React compared to its behavior in Next.js. In my index file, I have implemented the following code: impo ...

Looking to swap out the final value in a JavaScript array?

My task involves manipulating arrays. I start with an array of numbers called newArr. The length of this array is used to create another array filled with zeros, which I named zeroArr. const newArr = [1,3,5,8,9,3,7,13] const zeroArr = Array.from(Array(newA ...

Can you guide me on how to configure the system proxy settings on Windows operating system?

I'm working on developing a VPN application for Windows and I am interested in setting up a proxy on the system. While there are various methods to accomplish this (such as through the registry or command line), I am searching for a more efficient so ...

Unraveling Complex JSON Structures in React

Having trouble reading nested JSON data from a places API URL call? Look no further! I've encountered issues trying to access all the information and nothing seems to be coming through in the console. While unnested JSON is not an issue, nested JSON p ...

What is the best way to create a list using only distinct elements from an array?

If I have a collection of different colors: Red Blue Blue Green I aim to extract only the unique colors and store them in an array. Subsequently, I plan to incorporate each color from that array into an existing color list. The desired outcome would l ...

What are some methods to boost productivity during web scraping?

Currently, I have a node script dedicated to scraping information from various websites. As I aim to optimize the efficiency of this script, I am faced with the challenge that Node.js operates on a single-threaded runtime by default. However, behind the sc ...

Losing $scope reference when incorporating a directive within the controller scope

I have a scenario in my code where I am using two directives. One directive is within the controller scope, while the other directive is not located in the html section. <div ng-show="isStore==true"> <packgroup-directive> ...

Can a file be transferred from an Electron application to an Express server by supplying the file path?

This is my current objective: A user drags and drops a file into Electron Electron uses a python script via child_process.exec to convert the file The conversion process generates a new file in the same directory as the original With knowledge of the path ...

What is the best way to pre-fetch data using axios in Vue?

My app requires offline functionality for drivers operating in remote areas with limited internet access. To address this, I aim to pre-download all necessary data using Axios requests when an internet connection is available. This way, the app can retriev ...