Is it possible to simplify the use of two ng-shows and two dropdowns in AngularJS by utilizing just one dropdown

Is there a way to use a single dropdown that satisfies both conditions?

<div ng-show="user == 'admin'">
     <div class="col-md-8 col-sm-12 col-xs-12">
         <select   ng-model="li"  >
             <option  ng-repeat="li in list">{{li.name}}</option>
         </select>
     </div> 
</div>

 <div ng-show="user != 'admin'">
     <div class="col-md-8 col-sm-12 col-xs-12">
         <select   ng-model="li"  >
             <option  ng-repeat="li in list|limitTo:1">{{li.name}}</option>
         </select>
    </div> 
</div>

View the code on Plunker

Answer №1

If you want to give it a shot, here's an alternative approach:

<div ng-if="user == 'admin'">
        <div class="col-md-8 col-sm-12 col-xs-12">
            <select ng-model="li">
                <option  ng-repeat="li in list">{{li.name}}</option>
             </select>
        </div>
    </div>
    <div ng-if="user != 'admin'">
        <div class="col-md-8 col-sm-12 col-xs-12">
            <select ng-model="li">
                  <option  ng-repeat="li in list" ng-if="$first">{{li.name}}</option>
            </select>
        </div>
    </div> 

Make sure to use ng-if instead of ng-show, and utilize ng-if="$first" instead of using the limitTo:1 filter.

For an updated plunker demonstration, you can visit this link:http://plnkr.co/edit/Cwc9prHQrULCKY8UmbSE?p=preview

Answer №2

One possible solution is to utilize a filter function in your AngularJS application.

`<!DOCTYPE html>
<html ng-app="plunker">

  <head>
    <meta charset="utf-8" />
    <title>AngularJS Plunker</title>
    <script>document.write('<base href="' + document.location + '" />');</script>
    <link rel="stylesheet" href="style.css" />
    <script data-require="<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="4928272e3c25283b67233a0978677d6731">[email protected]</a>" src="https://code.angularjs.org/1.4.3/angular.js" data-semver="1.4.3"></script>
    <script src="app.js"></script>
    <script>
      var app = angular.module('plunker', []);
      app.controller('MainCtrl', function($scope) {
         $scope.user="admin";
          $scope.list = [
          {id:1,name:"first",tc:100},
          {id:2,name:"second",tc:103},
          {id:3,name:"third",tc:105}
        ]
        console.log("hi");
        console.log($scope.modes);
        $scope.filterrole=function(item){
          return $scope.user=="admin"?true:$scope.list[0]==item;
        }
      });
    </script>
  </head>
  <body ng-controller="MainCtrl">
    <div >
    <div class="col-md-8 col-sm-12 col-xs-12">
                        <select   ng-model="li"  >
                          <option value="">select {{user}}</option>
                            <option  ng-repeat="li in list |filter: filterrole">{{li.name}}</option>
                        </select>
                    </div> 
                    </div>
                    <br>
                    <div><input type="button" value="admin" ng-click="user='admin'">
                    <input type="button" value="other" ng-click="user='other'"></div>
  </body>
</html>`

http://plnkr.co/edit/orL8oLOKSm7H4DJwXQyx?p=preview

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

"Utilize Selenium to navigate and select a menu option with a

In my dropdown menu, I am trying to use Selenium to move the mouse to the Documentation menu item and click on the App Configuration option within it. The mouse hover function is working properly, but I am unable to click on the App Configuration element. ...

Discover the steps for integrating an object into a Ext.grid.Panel using Sencha Ext Js

Currently, I am utilizing Sencha Ext Js 4 and have integrated an Ext.grid.Panel into my project. I am interested in adding another element inside the header, such as a textbox. Is this achievable? {filterable: true, header: 'Unique' /*Here i w ...

Making an API request in React based on user input

As a beginner, I am in the process of creating a simple weather application. However, the code below is not functioning as expected. I need assistance in getting user input and submitting it. Can someone please provide guidance? class App extends Component ...

Implementing AngularJS to include an HTML page as a widget

I am currently in the process of learning Angular js. My goal is to incorporate another website as a part of my own webpage; within a "div" element. Here is the code I have been working on to achieve this: However, the external website may contain hyperl ...

Unable to retrieve information from the API

I have created some Graphs using Graph js and now I want to visualize the data within them. Even though I am able to fetch the data and display it in the console, I am facing issues with displaying it in the actual graph. Despite trying multiple methods, ...

Personalize the 'Standard', 'Fresh', and 'Modify' aspx widget devoid of Share Point or Infopath integration

As I work on developing a Sharepoint 2010 page to meet my team's needs, I am faced with restrictions on using Sharepoint Designer and InfoPath. This means I am unable to customize the default form for adding, editing, or viewing items on my individual ...

Merge JSON objects while retaining duplicate keys

I am looking to merge two arrays containing JSON objects while retaining duplicate keys by adding a prefix to the keys. In this specific scenario, the data from 'json2' is replacing the data from 'json1' due to having identical keys, bu ...

What is the best way to transfer a request parameter from a URL to a function that generates an object with matching name in JavaScript?

I need to figure out how to pass a request parameter from an express router request to a function that should return an object with the same name. The issue I'm facing is that the function is returning the parameter name instead of the object. Upon c ...

Order of setTimeout calls in React's execution sequence

I am currently trying to wrap my head around the functionality of this React component (which is designed to delay the rendering of its children): function Delayed({ children, wait = 500 }) { const [show, setShow] = React.useState(false); React.useEff ...

Transcluding code within an each loop does not function properly with the last element

The issue I am facing in this particular scenario involves a transcluded directive within an ng-each. Strangely, the transclusion only appears on the final iteration of the each loop! var app = angular.module('testApp', []); app.directive (&a ...

Does applying a style to an element that already has the same value result in a decrease in performance? Alternatively, do all browsers simply overlook it?

Assuming I have an element with the style top: 5px, and then I execute element.style.top = "5px";, will the browser readjust its position and trigger a layout again? Or does it recognize that there is no need to change anything? (Is this behavior specified ...

After refreshing the page in Next JS, there is a delay in loading the Swiper Js styles. The Swiper slides appear stretched while waiting for Next JS to load the styles. Any suggestions

Having an issue with my Next 14.0.3 app and tailwind CSS. I recently installed swiper JS version 11.0.5 using npm. The problem arises when I reload the page, it takes about 1 or 2 seconds for the swiper styles to load. During this time, the swiper slides s ...

Encountering difficulties with updating customer information in postgreSQL

I am attempting to perform CRUD operations using pg-promises and stored procedures in PostgreSQL. Here is my code: controller.js: const db = require("./../index.js"); exports.getAllData = async (req, res, next) => { try { const data = ...

What is the best way to present progress bar numbers in Bootstrap beneath the bar?

I have successfully implemented a progress bar using Bootstrap. Now, I am looking to display numerical values below the progress bar, similar to this: https://i.sstatic.net/3QG8d.png Is there a way to achieve this without utilizing JavaScript graphing l ...

Effortlessly move and place items across different browser windows or tabs

Created a code snippet for enabling drag and drop functionality of elements within the same window, which is working smoothly. var currentDragElement = null; var draggableElements = document.querySelectorAll('[draggable="true"]'); [].forEach ...

In JavaScript, the Else statement fails to run

Hi there, I'm currently working on creating a function to check the validity of a string input. This is what I have so far: function validatePassword(){ passW = prompt ("Enter Password:"); if (passW == 'Pass123'){ document.write ('Y ...

Setting the default value of a multi-select dropdown in AngularJS from the controller

Currently, I have implemented AngularJS multi select drop down functionality on my website. The code for this can be found at the following source: MultiSelectDropDown In my HTML page, I have included the same drop down twice and I want to customize the ...

Tips for accessing req.fields variables while utilizing Express-Formidable

For some reason, I am encountering difficulties when trying to access variables parsed within req.fields using Express-Formidable. Upon executing a console.log() of req.fields, the output is as follows: { 'registration[username]': '1', ...

interactive division element

I'm facing an issue with making my div tag clickable in a five-star rating system. The stars are supposed to represent different values from 1 to 5. Even though the image changes on mouseover, clicking the div tag does not yield any result. This is ...

Sequentially calling URLs in Selenium NodeJS to retrieve the page source of each

I am trying to open URLs based on the IDs available in an array and retrieve the unique PageSource for each. However, when I run the code below, only the PageSource of the last element is being returned. For example, if the body of each URL looks like: ...