Creating fresh fields using AngularJS

I'm looking to dynamically create a new form whenever an item is added to an array. The form remains consistent, but the conditional count increases each time.

Here's an example:

<span ng-show="companydata.selectedloc.length == 0">
    <div angucomplete-alt id="ex1"
    selected-object="selectedLocation"
    ></div>
</span>

<span ng-show="companydata.selectedloc.length == 1">
    <div angucomplete-alt id="ex1"
    selected-object="selectedLocation"
    ></div>
</span>

<span ng-show="companydata.selectedloc.length == 2">
    <div angucomplete-alt id="ex1"
    selected-object="selectedLocation"
    ></div>
</span>

Each code block adds an item to companydata.selectedloc when selected (using an autocomplete select input).

Check out the JavaScript function:

$scope.selectedLocation = function(selected){
    $scope.companydata.selectedloc.push(selected)
}

Instead of manually increasing the condition and adding more code blocks up to a limit of 10, is there a more elegant way to accomplish this task?

Answer №1

To fully utilize Angular's capabilities, consider incorporating the ng-repeat directive.

Here is a functioning Code Playground

In the provided code sample, I included track by $index since the specific selected values were not given. This addition serves to prevent duplication errors often encountered in Angular.

In the example provided, I initialized the companydata variable in this manner:

$scope.companydata = {
  selectedloc: [] // Initialized with an empty array
}

If you wish to have preset values, the process is straightforward:

$scope.companydata = {
  selectedloc: [0, 1, 2] // Initialized with desired value(s)
}

For a more elaborate demonstration, refer to this revised Code Playground where I introduced simulated "location" objects.

<span ng-repeat="loc in companydata.selectedloc">
    <div angucomplete-alt id="ex1"
    selected-object="selectedLocation"
    ></div>
</span>

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

What is the best way to achieve line breaks in text that auto-wraps in JavaScript/PHP?

My resizable div contains text/sentences. As I adjust the size of the div, the text wraps itself to perfectly fit within the available space in the container div. Now, I am faced with the task of converting this dynamic text into an image using php and th ...

What is the best way to eliminate the additional slash from an optional parameter at the first level in a URL

Is it possible to make the first parameter optional for the login state? Below is the .state definition that I am using: $stateProvider .state("login", { url: '/:team/login/', templateUrl: 'app/user/login.html', ...

Error Encountered: POST method not supported in ajax request using djangoIs this a

I am currently encountering an issue while trying to pass form data values through ajax. I keep getting a method not allowed error when attempting to add a comment on a blog post. The form below is located inside the blog_detail page: <form id="co ...

Tips for properly implementing a bcrypt comparison within a promise?

Previously, my code was functioning correctly. However, it now seems to be broken for some unknown reason. I am using MariaDB as my database and attempting to compare passwords. Unfortunately, I keep encountering an error that says "Unexpected Identifier o ...

Watching a Computed Value in EmberJS

What causes the discrepancy between the two sets of code? Utilizing computed: computed: Ember.computed('selected', function() { console.log('computed'); return this.get('selected'); }), observer1: Ember.observer(&ap ...

Steps for eliminating double quotes from the start and end of a numbered value within a list

I currently have the following data: let str = "1,2,3,4" My goal is to convert it into an array like this: arr = [1,2,3,4] ...

Interactive hover image that reveals hidden information when clicked

I am trying to implement 3 rollover images as triggers to display text boxes underneath each image. However, when I click on the image, it disappears and does not function properly. I am currently focusing on getting the first one to work. To view my code ...

Creating a HMAC-SHA-256 signature in JavaScript for datatrans: A step-by-step guide

I'm currently working on an Angular project that involves implementing the Datatrans payment system. Unfortunately, I have been facing difficulties in generating a sign for the payment. I have been following the process outlined in this link (enter l ...

What is the best way to switch the visibility of a div on click from another div?

My goal is to make a div toggle visible or hidden when another div is clicked. The only connection between the two divs is that they are both nested within the same parent div. There's a DIV element with the class of "comment" which contains a DIV ele ...

Ways to inform an observer of an Object's change?

Is there a way to ensure that an observer receives notification of a change, regardless of Ember's assessment of property changes? While the ember observer pattern typically works well for me, I've encountered a specific issue where I'm unc ...

Tips on adding an array value to the XPath syntax while conducting a search in Selenium IDE

As a novice in Selenium, I might not be articulating my query clearly. I am working with Selenium IDE version 3.17.0 and attempting to validate the presence of device names on a web page under test. These device names are stored in an array: execute scrip ...

The values obtained from the previous parameter object of the React setState hook can vary and are not always

In my code, I am using a useEffect hook to update the state with setState. However, I'm encountering some unusual and inconsistent behavior with the previous parameter: useEffect(() => { setCurrentPicturesObject((existing) => { ...

The combination of ng-class and ng-click is causing issues and not functioning properly

I'm facing an issue with using ng-class and ng-click together. I am trying to add a class to a div when a button is clicked, but it's not functioning as expected. Here is the code snippet: <header> <div id="headerContainer"> ...

Navigation bar failing to show all content on Safari web browser

When navigating to this website, http://www.togethermutualinsurance.co.uk, using any browser except for Safari on Windows, the menu displays correctly. However, in Safari, the title of the menus and submenus with images does not display properly. Despite ...

Is it possible to insert a second hyperlink into a JavaScript-occupied anchor?

Check out my reference page at: To change the content in a 'containerarea' div, I am utilizing Dynamic Drive's "Dynamic Ajax" script. Below is an example of the anchor code used: <a href="javascript:ajaxpage('videos-maintenance/app ...

Understanding the concept of objects in JavaScript can be quite essential for

As I delve into a JavaScript file, I stumble upon the following lines: var myPage = new Object(); var myDocument = document.all; After some code, there is another interesting snippet: myPage.Search = myDocument.Search; myPage.Search.searchType = "Descri ...

Transitioning from one CSS id to another during page loading

Wondering how to fade in one CSS id on page load and then smoothly transition to another after a few seconds? Here are the ids: #background { background: url("images/am_photography_bg.jpg") no-repeat center -25px fixed; background-size: 100%; ...

JavaScript Lint Warning: Avoid declaring functions inside a loop - unfortunately, there is no way to bypass this issue

In my React JS code snippet, I am attempting to search for a value within an object called 'categories' and then add the corresponding key-value pair into a new map named sortedCategories. var categoriesToSort = []; //categoriesToSort contains ...

"Enhancing user experience with Ajax and seamless page updates

I'm currently in the process of developing a web application that includes a feature to trigger a backend action that may take up to 5 minutes. This backend process will run independently from the web app's front-end and back-end functionalities. ...

Switching between API requests through a live feed

Hey there: import Rx from 'rxjs'; function mockApi(endpoint, time, response) { return new Rx.Observable(observer => { console.log(`${endpoint}: Request initiated.`) let active = true; const id = setTimeout(() => { cons ...