Manipulate fields dynamically in Angularjs based on selected options

I am working on a function to show or hide a field based on the selected drop-down option. Additionally, if the field is active, I want to ensure it is not displayed in the Add filter dropdown list. You can view the plunker I created here.

So far, when I click on the remove field button (x), the field is hidden successfully. However, if I add the same field from the add filter option and then try to remove it again, it does not work as expected. I believe there may be a more effective way to achieve this functionality. Could someone please lend a hand?

Controller

angular.module('app', [])
.controller('Main', ['$scope', function($scope) {

$scope.title = "hello";
$scope.isName = true;
$scope.isDropdown = true;

$scope.hideName = function() {
  $scope.isName = false;
  $scope.removeFilterOption($scope.isName);
};

$scope.hideDropdown = function() {
  $scope.isDropdown = false;
};

$scope.removeFilterOption = function(value) {
  if (value != $scope.isName) {
    $scope.add_options.splice(1, 1);
  } else {
    $scope.add_options.splice(1, 0, {
      text: "Name",
      value: "name"
    });
  }
};

$scope.add_options = [];
$scope.add_filter = $scope.add_options[0];

$scope.selected = function(value) {
  if (value === "name") {
    $scope.isName = true;
  } else if (value === "cars") {
    $scope.isDropdown = true;
  }
}

}]);

Template

<body ng-controller="Main">
{{title}}
 <div ng-show="isName">
  <label> Name
   <span>
    <button ng-click="hideName()">&times;</button>
   </span>
  </label>
  <div>
   <input/>
  </div>
 </div>

<div ng-show="isDropdown">
 <label> Cars 
  <span>
    <button ng-click="hideDropdown()">&times;</button>
  </span>
 </label>
<div>
  <select>
    <option value="volvo">Volvo</option>
    <option value="saab">Saab</option>
    <option value="mercedes">Mercedes</option>
    <option value="audi">Audi</option>
  </select>
 </div>
</div>

<div>
 <h5>Add filter</h5>
  <select 
    ng-model="add_filter" ng-selected="selected(add_filter.value)" 
    ng-options="x.text for x in add_options track by x.value">
  </select>
 </div>
</body>

Answer №1

If you want to simplify things, just remove the tracking and focus on using ng-show and ng-hide. Take a look at the code snippet below, which demonstrates how easy it can be when you use ng-show and ng-hide effectively. This approach is much clearer and easier to understand compared to other methods. Remember to strategically show and hide elements where needed.

angular.module('app', [])
.controller('Main', ['$scope', function($scope) {
  
   $scope.title= "hello";
   $scope.isName = true;
   $scope.isCar = true;
   
   $scope.hideName = function() {
      $scope.isName = false;
    };
    
    $scope.hideCar = function() {
      $scope.isCar = false;
    };

    $scope.getOption = function() {
      var selected = $scope.selected;
      switch(selected) {
        case "Name":
          $scope.isName = true;
          break;
        case "Cars":
          $scope.isCar = true;          
          break;
      }
      $scope.selected = ""; // Reset Drop down
    }

}]);
<!DOCTYPE html>
<html ng-app="app">

<head>
 <link rel="stylesheet" href="style.css" />
   <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.16/angular.min.js"></script>
   <script src="script.js"></script>
</head>

<body ng-controller="Main">
  {{title}}
  <div ng-show="isName">
    <label> Name
      <span>
        <button ng-click="hideName()">&times;</button>
      </span>
    </label>
    <div>
      <input/>
    </div>
  </div>

  <div ng-show="isCar">
    <label> Cars 
      <span>
        <button ng-click="hideCar()">&times;</button>
      </span>
    </label>
    <div>
      <select>
        <option value="volvo">Volvo</option>
        <option value="saab">Saab</option>
        <option value="mercedes">Mercedes</option>
        <option value="audi">Audi</option>
      </select>
    </div>

  </div>
  
        <h5>Add filter</h5>
  <select ng-model="selected" ng-change="getOption()">
    <option value=""> </option>
    <option ng-hide="isName" value="Name">Name</option>
    <option ng-hide="isCar" value="Cars">Cars</option>
  </select>


</body>

</html>

Answer №2

Exploring alternative approaches can lead to more efficient solutions. Consider utilizing filters to assign values to 'name' and dropdown instead of relying on 'isName' and 'isDropDown' variables.

Answer №3

[Updated] I have made some adjustments to your functions and now everything is functioning correctly. It's important to note that using the Splice method in the way you were could cause issues by continuously adding names or cars every time the cross button is clicked:

Below is the updated code :

$scope.hideName = function() {
  $scope.isName = false;
  $scope.removeFilterOption($scope.isName,"name","Name");
};

$scope.hideDropdown = function() {
  $scope.isDropdown = false;
  $scope.removeFilterOption($scope.isName,"car","Cars");
};

$scope.removeFilterOption = function(value,type,text){
  if($scope.add_options.length>0){
  for(var i=0;i<$scope.add_options.length;i++){
    if(type=='name'){
     $scope.add_options.splice(i,1,{
      text: "Name",
      value: "name"
    });

    }else{
      $scope.add_options.splice(i,1,{
      text: "Cars",
      value: "car"
    });
    }
   }
  }else{
    $scope.add_options.push({
      text:  text,
      value: type
    });

  }

};

These changes have resolved the issue for me.

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

Measuring the space between components

I am looking for a way to dynamically calculate distance on a canvas, similar to the example shown in the figure. I want to be able to drag the highlighted joints in order to adjust the span for calculating distances. Are there any plugins available for th ...

AngularJS linked fade in/fade out animation

After reviewing the official show/hide transition example at the bottom of this page, I attempted to customize it for a smooth fade transition (transition: opacity 0.5s ease-in-out) between two divs placed in the same position on the page. The goal is to h ...

The functionality of document.elementFromPoint(x, y) seems to be faulty in accurately identifying child elements

I've been trying to retrieve the element over which a "drop" event occurs, but I keep getting unexpected results. It consistently returns parent elements instead of the actual child element where the dragged element is dropped on. For a full code exa ...

defineProps withDefaults "The type is lacking the following properties from the specified type"

I am currently working on a custom Button component with some unique functionality: <script lang="ts" setup> import { computed, ref } from 'vue'; const { type = 'button', color = 'primary', disabled = fa ...

Having Trouble Importing a Dependency in TypeScript

My experience with using node js and typescript is limited. I attempted to include the Paytm dependency by executing the following code: npm install paytmchecksum or by inserting the following code in package.json "dependencies": { ... & ...

Deactivate rounding numbers in jQuery AJAX

When using jQuery to send numbers, I noticed that the decimals are not saved correctly. For example, 2.5 is saved as 3 and 17.5 is saved as 18. $("#sendnomreform").on('submit',(function(e) { e.preventDefault(); $('#loading').s ...

Personalize your AngularJS filters by name and date

Hello fellow coders! I'm diving into the world of AngularJS and could really use some guidance ...

What is the best way to retrieve user roles in order to access all instructor posts within my MERN application?

There are 2 models in my code: Post and User. import mongoose from 'mongoose'; const PostSchema = new mongoose.Schema( { title: { type: String, required: true, }, text: { type: String, required: true, ...

Step-by-step Guide on Installing VueJs Medium Editor

After spending countless hours trying to install Medium Editor in VueJs, I finally got it working on a single page vuejs. However, I hit a roadblock when trying to make it work with the webpack file structure: ├── main.js # app en ...

The outcome of comparing with Bcrypt is consistently a negative result

bcrypt.compare() is consistently returning false when used in conjunction with this code within the user model. It appears that this issue is specific to bcrypt-nodejs. User.pre('save', function (callback) { this.password = bcrypt.hashSync(thi ...

Tips for using a button to update data without triggering a postback

Within the GridView in my ASP.net project, I have an ASP.net button with the following code: <asp:Button UseSubmitBehavior="false" runat="server" ID="btnShow" CssClass="btnSearch" Text="View All" CommandName="ViewAll" OnCommand="btnShow_Command" Comman ...

Transferring information from a Jade file to a Node.js server

I'm currently working on creating a data object within my Jade view page that will be used in my server-side JS. The data object involves dynamic HTML generation that inserts input boxes based on user input. function addDetail() { var det ...

I am interested in verifying the presence of the exampleClass HTML element using its element ID with the help of JS/JQuery

Recently I started learning front-end development and I am curious about the functionality of some front-end elements. Specifically, I am interested in checking if an HTML element with a specific ID has a certain class using JS/JQuery. <div class=" ...

Utilize external options for Chart.js datasets with added functionality

Exploring Chart.js for the first time in my project, I have found it to be a great tool. However, I've come across a challenge where I need to provide external filter options for the dataset as well. Currently, the filtering is done by clicking on lab ...

Transform JavaScript variables into CSS variables

Similar Post: Avoiding repeated constants in CSS I am currently working on a javascript file that aims to adjust my site's resolution based on the width and height of the viewport. While I have successfully retrieved these values using JavaScript ...

Determine whether the current page was reached by pressing the back button

Can we determine if the current page was loaded via a back button press? Here is the scenario: index.html (contains a link to page1 in the menu) page1.html (loads content from ajax with a link to page2) page2.html (user presses the BACK button) page1.h ...

"Comparing JSON objects can be done by checking if their IDs match, and if they do, assigning the value to another object

I am working with two sets of data var JSON_Categories = '[{ "id" : "1", "text" : "Category A"}, { "id" : 2, "text" : "Category B" }]'; var JSON_Article = '[{ "id&quo ...

Obtain the value of a promise in AngularJS without accessing its internal properties

Hey there, I have another question about promises. I'm trying to fetch data from an endpoint and use it in ng-repeat. Here is the standard response from the endpoint: {"ebbe5704-4ea5-470e-8ab9-102ee8ca457f":"Foo", "e380a6f7-2f88-46bb-bd54-2517193536 ...

Utilizing the arrow function in Object mapping to rearrange objects within an array

In the code snippet below, I am retrieving an object from a Firebase database using snapshot.val() and extracting names using the map function. database.ref('/destinations').once('value', function (snapshot) { const locations = sn ...

Client_id Based Google Analytics Data Download

For the sake of transparency, I have enabled users on my website to freely download their Google Analytics data. I am looking to avoid dealing with CCPA requests for data personally. My backend is powered by Node.js and I am curious if it is feasible to d ...