ng-model based on various scenarios

I have two distinct arrays defined as :

var oldarr = ['one','two','three'];

var newarr = ['four','five','six'];

var condi = 1 / 0;

I am using the array values as ng-model options in a select dropdown. However, I want to dynamically switch between the arrays based on the value of the 'condi' variable. If 'condi' is 1, I will use ng-model = oldarr and if 'condi' is 2, I will use ng-model = newarr.

Below is my dropdown menu. Can someone please suggest how I can achieve this?

<select ng-model="oldarr " ng-selected="{{defaultvalue == selectedslastatus}}">
  <option ng-repeat="vals in oldarr ">{{vals }}</option>
</select>

Answer №1

One effective strategy is to incorporate a middle array into your code.

(While it is possible to achieve this using ng-show, ng-if, or ng-switch, opting for a neat HTML Template (View) and maintaining uniform array structures may lead you to shift the logic to the Controller)

For instance:

<select ng-model="modelArr" ng-selected="{{defaultvalue == selectedslastatus}}">
  <option ng-repeat="vals in modelArr ">{{vals }}</option>
</select>

Then, handle the decision regarding which array to use in your controller.

Your controller could be structured as follows:

// 
$scope.$watch('condi', function (){
    if (condi === true)
        $scope.modelArr = newArr;
    else
        $scope.modelArr = oldArr;
})

Answer №2

If we want to switch the views based on a condition that is not strictly a boolean value, like the example with condi, we can use ng-switch in AngularJS. Here's a sample implementation:

var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
  $scope.condi = 1;
  $scope.oldarr = ['one', 'two', 'three'];
  $scope.newarr = ['four', 'five', 'six'];

  $scope.changeCondi = function() {
    $scope.condi = ($scope.condi == 1) ? 0 : 1;
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl">

  <button ng-click="changeCondi()">Change condi</button> : {{condi}}
  <div ng-switch="condi">
    <div ng-switch-when="1">
      <select ng-model="oldar">
        <option ng-repeat="vals in oldarr">{{vals}}</option>
      </select>
      Selected: {{oldar}}
    </div>

    <div ng-switch-when="0">
      <select ng-model="newar">
        <option ng-repeat="vals in newarr">{{vals}}</option>
      </select>
      Selected: {{newar}}
    </div>
  </div>

</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

Showing the Length of Several Videos Simultaneously on a Webpage

I am attempting to showcase the "duration" for each video on the page using JavaScript. This is my current code: var vid = document.querySelector(".mhdividdur"); vid.onloadedmetadata = function() { var x = document.querySelector(".mhdividdur").duratio ...

The callback function is triggered prior to the completion of the request.on function

A custom npm module was developed for downloading files and displaying progress bars using the request and progress libraries. https://github.com/MaxySpark/maxyspark-download However, during testing, the callback function is executing prematurely instead ...

Achieving a consistent scroll value using RxJs

I have a block with a mat-table inside, which has an initial scroll value of 0. I am trying to achieve a scenario where the scroll value changes automatically to 2 or more when you reach a height of 0 and again changes back to 2 when scrolled to the final ...

What could be the reason for the misalignment between md-menu and md-button when ng-href is included in the button?

Check out the demo by clicking here: http://codepen.io/audiodude/pen/vLyNvw The main distinction between the top and bottom sections lies in the fact that the top section utilizes an md-button with an ng-href attribute, which Angular Material compiles int ...

Customizing Axios actions in Vue JS using a variable

I have a form in my Vue component that sends a reservation object to my API for storage. I am exploring the possibility of setting the axios action dynamically based on a variable's value, without duplicating the entire axios function (as both the pos ...

Contrasting a string against an array

I'm having trouble comparing a string variable to elements of a string array in Visual Basic. I'm trying to compare a user-entered string to an array containing the lowercase alphabet, but my "count" variable always ends up at 25 for some reason. ...

``In Internet Explorer, the function to swap the image source when hovering over the parent element

I'm trying to make it so that when I hover over the parent (Li) tag with my mouse, the src attribute of the child img tag changes. This code works correctly in Chrome but not in Firefox and Internet Explorer. <li class="player"> . . //some c ...

Using AngularJS to send a large JSON file to a directive

It seems like I have identified the issue with the chart not displaying properly. The problem is most likely due to the fact that I am loading a large JSON object from a RESTful server and passing it to a directive for chart generation before the JSON has ...

I'm encountering some issues trying to install next-auth in my project built with Next.js and React

I recently set up my Next.js project with React using yarn create next-app. However, I am facing an issue as the next-auth package is not installed in my project. Currently, my node version is LTS 16.15.1, yarn version is 1.22.18, and npm version is 8.9. ...

Developing a website using custom modules in Node.js and Express framework

I am currently encountering an issue when using a custom module within one of my route functions in Express with node. Below is my current setup: In the app.js file, I require the module as follows: c_controller = require( './core/c_controller' ...

Error: Unable to access property 'camera' as it is undefined

After implementing the Raycaster from Three js to detect collision following a MouseMove event, I encountered an error: Cannot read properties of undefined (reading 'camera') Here is the code snippet causing the issue: bindIFrameMousemove(if ...

This particular JavaScript function is only designed to operate on the initial input box in the provided

I have a question regarding echoing rows of $data inside input boxes. I am using a JavaScript function that is supposed to copy the input value to the clipboard when the input box is clicked. However, I am encountering an issue - the function only works ...

Linking two dropdowns in Ember with data binding

I need help with connecting two selectboxes. I want the options in the second one to be determined by what is selected in the first selectbox. I'm new to using Ember and could use some advice on how to approach this problem. I tried using computed pro ...

Utilize React hooks to efficiently filter multiple JSON requests

I am currently working on creating a filter system that can combine multiple filters for users to choose from, such as "big/not-big" and "heavy/not-heavy". Each filter corresponds to loading a JSON file. My goal is to merge the results of these JSON files ...

Guide to using jQuery to input a multi-line text into a field

Dealing with a value that spans multiple lines obtained from PHP has been challenging due to the structure of textareas. The standard method of inserting it into the textarea is not feasible in this case. I resorted to using jQuery for this purpose, but ...

Leveraging Google maps to find nearby stores

I recently created a store locator but hit a roadblock when I discovered that Google Maps does not allow you to iframe the entire page. Is there a workaround for this issue to display the map? Or is there an alternative method that doesn't involve ifr ...

PHP AJAX Request Failing to Transfer Files

I am having trouble with sending files in a PHP AJAX Request: Here is the form code: <form class="frmContact" action="#" method="post"> <div class="col-md-6"> <input type="hidden" name="emailTo" id= ...

What is the best way to ensure that two objects collide with one another?

Issue Description I am currently working on implementing collision detection for two objects. The goal is to determine if the objects are intersecting by calculating their bounding boxes with Box3 and using the .intersectsBox() function to obtain a boolea ...

A Comprehensive Guide to Handling Errors in Angular 4: Passing the err Object from Service to Component

Currently, I am in the process of developing a login page using Angular for the front-end and Spring Security for the back-end. Everything appears to be functioning correctly, except for handling exceptions when attempting to catch errors from the service ...

What methods can be used to incorporate animation when the display attribute transitions to none?

Is there a way to add animation in a Vue app when replacing elements? I would like the transition from, for example, clicking on a div with 'Num 1' to the divs with class 'showing' not disappear abruptly but smoothly, such as moving to ...