Using AngularJS, learn how to populate array objects within a JSON object

I'm trying to load array objects from a multi-select control, then populate a model object called "name" with its name and age values. After that, I want to load an array from a select element into the model object. However, the ng-model directive on the select control doesn't seem to be working.

<input type="text" class="form-control" ng-model="model.name" placeholder="Enter your name..." />
<input type="text" class="form-control" ng-model="model.age" placeholder="Enter your age..." />

<!--Select pets for the person model-->
<select ng-repeat="pet in arrayFromApi" class="selectpicker" multiple>
   <option id="{{pet.id}}" ng-model="model.pets.id">{{pet.name}}</option>
</select>


<script>
   var app = angular.module("myApp", []);
   app.controller("myCtrl", function($scope) {

    $scope.model = { "name":"", "age":"", "pets" :[ {"id":""} ] };

    $scope.arrayFromApi = function() {
          ......
        // This function retrieves IDs and names
     }
 });
 </script>

Answer №1

To achieve this, consider utilizing ng-options. Alternatively, you can experiment with ng-repeat, but limit it to the option tag.

Answer №2

It's advisable to avoid using ng-repeat when dealing with dropdowns as it can lead to performance issues. Instead, opt for ng-options.

If you want to set up a model with fields like name, age, and pets, take a look at the mixData function.


    <input type="text" class="form-control" ng-model="model.name" placeholder="Enter your name..." />
    <input type="text" class="form-control" ng-model="model.age" placeholder="Enter your age..." />

    <!-- Steer clear of using ng-repeat in dropdowns -->
    <!-- Choose pets for the person model -->
    <select ng-change="mixData()" class="selectpicker" multiple ng-model="myPets" ng-options="pet.id as pet.name for pet in arrayFromApi">
       <option value="">Select...</option>
    </select>

    <!--<select ng-repeat="pets in arrayFromApi" class="selectpicker" multiple>
       <option id="{{pet.id}}" ng-model="model.pets.id">{{pet.name}}</option>
    </select>-->


    <script>
       var app = angular.module("myApp", []);
       app.controller("myCtrl", function($scope) {

        $scope.model = { "name":"", "age":"", "pets" :[ {"id":""} ] };

        $scope.arrayFromApi = function() {
              ......
            // this function retrieves ids and names from the API
         }

        $scope.mixData = function(){
           $scope.model.pets = $scope.myPets;
        };
     });
    </script>

Answer №3

If you want to follow best practices in Angular, it's recommended to utilize select along with the angular standard ng-options. This allows you to manage everything within your view and have multiple return types as an array to your controller like {id: n}.

var app = angular.module("myApp", []);
app.controller("myCtrl", function($scope) {

  $scope.model = {};

  //from api
  $scope.arrayFromApi = [{
      id: 1,
      name: 'test'
    },
    {
      id: 2,
      name: 'test2'
    }
  ];

  $scope.getDetails = function() {
    console.log($scope.model);
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl">
  <input type="text" ng-model="model.name" placeholder="Put your name..." />
  <input type="text" ng-model="model.age" placeholder="Put your age..." />

  <!--Select pets for model person-->
  <select ng-model="model.pets" ng-options="{id: item.id} as item.name for item in arrayFromApi" multiple></select>

  <button ng-click="getDetails()">save</button>
</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

I'm a complete programming newbie and I want to start learning JavaScript, jQuery, and other programming languages. Where should I

Coming from a design background with zero programming knowledge, I have recently learned XHTML and CSS. Now, I am eager to expand my skills by mastering JavaScript, jQuery, and more. Where should I begin? This will be my first foray into programming. Whil ...

HTML code is not displayed within the ng-template

After passing JSON data in the correct format from my Laravel controller, I'm trying to display it recursively using Angular. However, the HTML inside ng-template is not being rendered. What could be the issue? Note: I've replaced the default An ...

Suggestions for changing sub-component data in Vue

I have a scenario where I am using a component with tabs inside. The Head component (parent) includes the following code: <v-btn @click="setSelectedTab('Set') "> ... <component :is="selectedTab"></component> ...

The process of combining identical data values within an array of objects

Can anyone help me with merging arrays in JavaScript? Here is an example array: [{ "team": team1, "groupname": "group1", "emp-data": [{ "id": 1, "name": "name1", }], }, { "team": team1, "groupname": "group1", " ...

At what stage of the Angular JS application life cycle is this code being loaded?

I am facing a difficult issue with the timing of Angular JS life cycle in relation to the code snippet below. There seems to be a random occurrence where controllers dependent on this code are loaded before it, leading to errors. Even after multiple atte ...

What are the best practices for properly formatting a function that returns a JSON string?

Recently, I embarked on a project utilizing the CityBikes API to access real-time data from bike-sharing stations in cities worldwide (). Initially, I gathered various links to obtain the necessary data and then developed a function called extractStationDa ...

Changing the templateUrl of a directive on the fly using the controller

How can I dynamically pass the templateUrl for the app_modal directive from the "ServerController" controller to allow for different templates for different modals? I have included the URL as an attribute in the "app-modal" tag used in the server_group.htm ...

Upon executing `$('div')`, an empty array is returned

My goal is to retrieve all the div classes on a page using jQuery $('div');. However, the page does not natively support jQuery, so I am loading it through external links until $ === jQuery evaluates to true. Even on Stack Overflow where jQuery ...

What is the reason for JSON.parse throwing errors on the same strings that eval does not?

Imagine having something like this: var a = '["\t"]' When you use: eval('var result = ' + a) Everything runs smoothly. However, if you try: var result = JSON.parse(a) You'll encounter an error: Unexpected token. The s ...

Save the text entered into an input field into a Python variable

Is there a way to retrieve the text from input fields that do not have a value attribute using Selenium? The issue is that these fields are populated automatically, possibly through JavaScript, upon page load and the text does not appear in the HTML source ...

Capture data from ajax effectively by extracting and executing manipulations seamlessly

I have a project where I need to retrieve images from a database using Ajax and display them using a carousel plugin. This is the process: An image URL is saved to the database by an admin The frontend script makes an Ajax call to a PHP file and retrieve ...

What is the best way to define one API route that accommodates two different query combinations?

Is it possible to define 1 API route with 2 different query combination options? We have 2 routes: GET /api/v1/resource?filter=byName&key=restaurant&city=chicago GET /api/v1/resource?filter=byLocation&lat=34&long=78 In soaJS, schema ...

Is it better to use scale.set() or simply increase the size of the model in Three.js?

When it comes to scaling 3D models in Three.js (or any other 3D renderers), what is considered the best practice? Recently, I encountered a situation where I loaded a model only to realize that its size was too small. In order to adjust the size, I used m ...

Having trouble retrieving the array value from xpath

Here is the content of my reg.xml file: <childrens> <child_4 entity_id="4" value="Activities" parent_id="2"> <child_10066 entity_id="10066" value="Physical1" parent_id="4"> <child_10067 entity_id="10067" value="Cricket" parent ...

Turning text into clickable links using JavaScript

I am faced with a scenario where I need to detect phone numbers within a string and convert them into clickable links. At the moment, using an external library is not an option. Here's the progress I've made so far: String: "This is my phone nu ...

The AJAX request encountered an unexpected failure that cannot be identified (Using jQuery)

Are you facing issues with a service that returns JSON data? Check out this URL: If you're attempting a simple AJAX request, here's some sample code to get you started: $.ajax({ type: "get", url: "http://api.drag2droid.shamanland.com/ca ...

Choosing a value in the second dropdown menu based on the selection made in the first dropdown menu can be achieved by retrieving both values from the database using a common list

I have a scenario where I am utilizing two drop-down menus with the same data sourced from a database. When a particular item is selected in the first drop-down, it should not be available in the second drop-down. For instance, the values in the first dro ...

Text box content does not refresh unless the page is reloaded

My text box (tbAdresse) is initially empty. I'm using the following JavaScript code to set its value: origin = document.getElementById("tbAdresse").value; if (origin == "") origin = <%=this.GetFormatStringCoordonnees("Paris")% ...

Conceal any child elements that are cut off as a result of the overflow hidden property

Despite the numerous questions on this topic, none provide a suitable answer. In this scenario, the overflow hidden property is applied to the parent div. The goal is to display only the child elements that are fully visible within this container. In the ...

What steps can be taken to address the error "console is undefined" in PowerShell?

I have a basic .js file saved on one of my drives that contains the following code: var x=3; function numSqaure(x) { return(x*x); } var sentence="The square of" + x + "is" + numSqaure(x); console.log(sentence); When attempting to run this script thro ...