AngularJS: Exploring the Connection with Array Elements

When working with AngularJS, I've noticed that I can easily bind text inputs to elements within arrays:

<input type="text" ng-model="foo[2]" />

Is this a feature provided by AngularJS or simply happening by coincidence?

However, when attempting to bind select elements or checkbox inputs to array elements, they do not seem to function properly - for example, the select element does not update the displayed value upon selection and the checkbox remains unchecked even after being clicked.

Could there be something that I am overlooking in my code?


Update: Interestingly, it seems to work perfectly fine in JSFiddle: http://jsfiddle.net/azFzc/

Answer №1

Yes, this code snippet is functional with certain elements

To see it in action, check out this jsfiddle http://jsfiddle.net/fStE8/

Here's the HTML snippet:

<div ng-app>
<div ng-controller="MyController">
    Select
<select ng-change="changed()" 
        ng-options="option.value as option.label for option in options" ng-model="ar[0]">
 </select>
</div>
</div>

And here's the corresponding JavaScript:

function MyController($scope){
    $scope.options = [
        { label : "first element", value : 0 },
        { label : "second element", value : 1 },
    ]

    $scope.ar = [];
    $scope.ar[0] = 0;

    $scope.changed = function(){
         console.log($scope.ar[0]);
    }
}

Answer №2

In the following demonstration, I have customized the example to illustrate non-numeric array assignment through binding. This technique proves most beneficial when dealing with intricate data structures or when your array utilizes a key system for updating and accessing values.

Check out the modified example here

HTML

<div ng-app>
<div ng-controller="MyController">
    Select
<select ng-change="changed()" 
        ng-options="option.value as option.label for option in options" ng-model="ar['SomeId']">
 </select>
</div>
</div>

JS

function MyController($scope){
    $scope.options = [
        { label : "first element", value : '1' },
        { label : "second element", value : '2' },
    ]

    $scope.ar = [];
    $scope.ar['SomeId'] = '1';

    $scope.changed = function(){
         console.log($scope.ar['SomeId']);
    }
}

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

Unit testing different views in UI-Router with angularJS $stateProvider: Best practices

Seeking guidance on unit testing various views for the following scenario .state('app.sr.product.upload', { name: 'upload', url: '/upload', data: { tags: [], ...

How to open a new tab and redirect page in ASP.NET when a dropdown list item is selected, using the selected index changed event

I need assistance with redirecting a page in a new tab. I am looking for a solution either through script or c# code. Any help is greatly appreciated. <asp:DropDownList ID="ddlcomplaint" CssClass="list-item-width1" runat="server" AutoPostBack="true ...

Building an HTML5-powered mobile application that runs seamlessly across all platforms

My task is to create a tablet application using HTML5/JS/CSS that is not dependent on any specific platform. Here are the requirements: It should be a cross-platform mobile/tablet application It needs to have offline capability and storage (working witho ...

Pass a variable value as a parameter to a jQuery function using code-behind

Within my code behind, I am retrieving the [IDphoto] from an SQL database. My goal now is to pass this IDphoto as a parameter to a jQuery function upon onClick. How can I achieve this? Code behind sb.AppendFormat("<a onclick='popup()' href=& ...

Transform a string into an array using a specific key

Can anyone help me with converting a string into an array? Here is the string I have: <enq fiscal="no" lastcommanderror="no" intransaction="no" lasttransactioncorrect="yes" /> The expected output array should look like this: array( ['fisk ...

Choose components identified by a dot

If I have a simple script that displays an element based on the option selected, how can I handle periods in the values? For instance: <select id="my-selector"> <option value="cat.meow">Cat</option> <option value="dog.bark"> ...

AngularJS Templates With In-line Logic

Is it possible to include inline logic in an AngularJS template? I am trying to achieve the following: <div ng-repeat="item in items"> {{item.isValid ? 'Valid item' : 'Invalid Item'}} </div> ...

Retrieving a value using forEach in protractor - Dealing with closures

I am facing an issue with the helper code below, as it is not returning the correct number of occurrences of a string. this.getActualFilteredStatusCount = function(strFilter){ return this.getTotalRows().then(function(count){ var totalCount = ...

AngularJS: Enhancing Dropdown Menus

I currently have a pair of drop down lists. The first dropdown looks like this: <select ng-model="vm.eesAdminSetupData.Type" class="form-control" id="Type" name="Type" required> <option value="Form">Form</option> <option value="List ...

Modify the color of the select element when it is in an open state

If you're new to Material UI, I have a select element that I would like to change the color of. When 'None' is selected, I want the background color of the input field above it to match the 'None' section. Then, when the dropdown m ...

Distinguishing Jquery and Ajax

Could someone kindly provide a comparison of the distinctions between Jquery and Ajax? ...

Do not include any null or empty objects when assigning to an array in Mongoose

When using mongoose's find() or findOne() methods, the returned value will be [] and null, respectively, if the where conditions are not met. This can cause issues when assigning these values to an array. Currently, I am filtering out the null values ...

What is the reason behind not being able to reference a variable in an object with v-bind parameters

I'm having trouble passing the variable showAlert1 from the object alertObj. In the code snippet below, only #3 seems to work. Can anyone explain why this is happening? Additionally, I am curious about how #3 works. Does it retrieve the first boolean ...

What is the best way to create an array of objects in the main function?

In my code, I have a constructor that creates an array of person objects: public class Group { final int MAX =10; private Person[] _groupOfPersons; private int _numOfPersons; public Group() { _groupOfPersons = new Person [MAX ...

When making axios calls from React to a Node.js server, sometimes the `req.body` object

Attempting to send the two IDs (book_id, user_id) from axios to node.js results in an empty object when I console.log(req.body). When using console.log("bookid", book_id, "user", user_id) in axios, the output is: https://i.sstatic.net/d5HgQ.png Upon con ...

What could have caused these errors, since they never made an appearance?

'Link' component cannot be utilized within JSX. The type 'ForwardRefExoticComponent<LinkProps & RefAttributes<HTMLAnchorElement>>' is not a valid element for JSX. The type 'ForwardRefExoticComponent<LinkPro ...

What is the simplest method for moving cells between two tables using drag and drop?

Is there a way to select random cells from a table and move them to another table using drag and drop functionality? I'm looking for a library that can help achieve this with JavaScript and PHP. Additionally, I need to save the ID of the selected cel ...

What is the syntax for defining "skills[]" in an AngularJS input field of type text?

When working with PHP, we often use name="skills[]" to retrieve data from a form as an array. How can this be achieved in AngularJS? For example, in PHP: <input type="text" name="skills[]" /> I am attempting to achieve the same functionality in An ...

Convert the button element to an image

Can someone please explain how to dynamically change a button element into an image using javascript when it is clicked? For instance, changing a "Submit" button into an image of a check mark. ...

What is preventing me from loading a JavaScript script using a regular working URL?

After inserting the following line into my HTML file: <script type="text/javascript" src="http://static.citygridmedia.com/ads/scripts/v2/loader.js"></script> (whether inside or outside the <head></head> tags), I am encountering a ...