Picking the right function through selection in AngularJS

I have 2 dropdowns and a button that triggers a function. The goal is to execute different parts of the code based on whether a location or an assigned item is selected. It even works if both are null in the API, allowing for one selection to be changed.

$scope.edit_location = function() {
    for(var i = 0; i < $scope.inventories.length; i++) {
        if($scope.currentInventory.location){

            console.log('I am in location');
            var copySelectedInv = Restangular.copy($scope.currentInventory);
            copySelectedInv.customPUT({location: $scope.currentInventory.location, assigned: null,  tags: $scope.inventories[i].tags}); 

        }else if ($scope.currentInventory.assigned){

            console.log('I am in assigned');
            var copySelectedInv2 = Restangular.copy($scope.currentInventory);
            copySelectedInv2.customPUT({location: null, assigned: $scope.currentInventory.assigned,  tags: $scope.inventories[i].tags});    
        }
    }
};

Dropdown options in my template

 <select class="input-medium form-control" ng-model="currentInventory.location">
        <option value="">Choose location</option>
        <option value="{{location.resource_uri}}" ng-repeat="location in locations">{{location.name}}</option>  
</select>
<h5>Assign to employee</h5>
 <select class="input-medium form-control" ng-model="currentInventory.assigned">
        <option value="">Choose location</option>
        <option value="{{user.resource_uri}}" ng-repeat="user in users">{{user.first_name + ' ' + user.last_name}}</option> 
</select>

<button class="btn tbn-lg btn-success" ng-click="edit_location()">

Answer №1

I prefer using the ng-options directive:

<select class="input-medium form-control" ng-model="currentInventory.location" 
        ng-options="location.resource_uri as location.name for location in locations">
        <option value="">Choose location</option> 
</select>

If you want to ensure that selecting a value deselects others, here is a quick solution:

$scope.$watch("currentInventory.assigned",function(newValue,oldValue,scope){
    scope.currentInventory.location = null;
});

$scope.$watch("currentInventory.location",function(newValue,oldValue,scope){
    scope.currentInventory.assigned = null;
});

Another approach is binding with the object as the value instead of just the resource_uri property:

<select class="input-medium form-control" ng-model="currentInventory" 
            ng-options="location.name for location in locations">
            <option value="">Choose location</option> 
</select>

Make sure to differentiate between a location and a user:

$scope.edit_location = function() {
    for(var i = 0; i < $scope.inventories.length; i++) {
        if($scope.locations.indexOf($scope.currentInventory)>=0){

            console.log('I am in location');
            var copySelectedInv = Restangular.copy($scope.currentInventory);
            copySelectedInv.customPUT({location: $scope.currentInventory.location, assigned: null, tags: $scope.inventories[i].tags}); 

        }else if ($scope.users.indexOf($scope.currentInventory)>=0){

            console.log('I am in assigned');
            var copySelectedInv2 = Restangular.copy($scope.currentInventory);
            copySelectedInv2.customPUT({location: null, assigned: $scope.currentInventory.assigned, tags: $scope.inventories[i].tags});    
        }
    }
};

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

Prevent cross-site scripting (XSS) when using vue toasted for displaying notifications

Whenever I include js code like "><img src=1 onerror=prompt(document.cookie);> in an input field and click submit, I use vue-toasted. The notification appears as shown in this image: https://i.sstatic.net/Gju9h.jpg and a popup shows the cookie in ...

Utilizing Ionic Storage to set default request headers through an HTTP interceptor in an Angular 5 and Ionic 3 application

I'm attempting to assign a token value to all request headers using the new angular 5 HTTP client. Take a look at my code snippet: import {Injectable} from '@angular/core'; import {HttpEvent, HttpInterceptor, HttpHandler, HttpRequest} from ...

Show off the images once they have finished loading completely?

Is there a way to ensure that the image is shown on the webpage only once it has been completely loaded? <ul id="listcontainer"> <li class="li1"> <img src="images/m1.png"> </li> </ul> ...

Unusual results observed with the Promise.all method

There's a code snippet I'm working on where I need to await 5 promises, wait for 2 seconds, and then continue with another set of 5 promises. However, it seems like the two instances of Promise.all are not being awaited as expected. I wonder if I ...

Require assistance with handling Ajax when a function with an Ajax call is repeatedly invoked

I am seeking guidance with ajax as I am still new to it. A problem arises when the same ajax call is made multiple times before the previous one completes its execution, resulting in an empty pop-up on the user interface. How can this issue be resolved? Es ...

Whenever I try to use npm install --force, I always encounter this issue

An error occurred while trying to run npm i --force. When attempting to run npm i, a series of errors are displayed. npm ERR! code ECONNRESET npm ERR! errno ECONNRESET npm ERR! network Invalid response body while attempting to fetch https://registry.npmjs ...

``How can I lock the top row of an HTML table containing input fields in place while

Below is the table structure: <table> <tr> <th>row1</th> <th><input type="text"></th> <th><input type="text"></th> <th><input type="text"></th& ...

Conceal a div when clicked outside using TypeScript with Next.js and Tailwind CSS

I am currently working on a modal using TypeScript, Next.js, and Tailwind CSS. My goal is to hide the modal when I click outside of it. However, I am encountering some errors related to types and other issues in my TSX file. The functionality works perfec ...

Graph is vanishing while linked

A unique HTML canvas is included in a standalone file called dashboard.html. To display the dashboard on the main homepage (home.html), we utilize ng-view nested within an ng-if directive. Oddly, clicking on the hyperlink "#" from the home page causes th ...

Using Jquery to Determine User's Location on Google Maps

Here is the script I have: var directionDisplay; $( document ).on( "pageinit", "#calc", function() { directionsDisplay = new google.maps.DirectionsRenderer(); var defaultLatLng = new google.maps.LatLng(34.0983425, -118.3267434); // Defau ...

Ben Kamens has developed a new feature in jQuery Menu Aim where the sub menu will not reappear once it

While exploring Ben Kemens’ jquery-menu-aim, I came across a demonstration on codepen. The code on codepen allows smooth transition from the main menu to the sub menu, but if you move away completely, the submenu remains visible and doesn't disappe ...

Encountering a server glitch while trying to deploy a Node.JS application with Railway

As a beginner in coding, I recently started learning how to deploy a basic web application on Railway. However, I encountered a server error message and I'm unsure about the cause. I checked their help page and tried using this code for the port, but ...

Saving csv data from an XMLHTTPRequest into an Array using Javascript

Attempting to extract data from a csv file, I utilized the following code snippet: (The csv file contains multiple lines representing different rows in a table) var newArray = [] function init() { var xhttp = new XMLHttpRequest(); xhttp.onreadyst ...

When downloading files that I uploaded to Google Drive using React Native, I noticed that the file size is not consistent with the original file

Greetings Everyone! I am aiming to transfer the database (RealmJS) that is currently stored on my device storage to Google Drive using Google Drive API V3. To accomplish this, I have already installed various node modules such as react-native-fs and @reac ...

Is it possible to create HTML content directly from a pre-rendered canvas element or input component like a textbox?

As I delve into learning JavaScript and HTML5, a couple of questions have sparked my curiosity: 1) Can we create HTML from a Canvas element(s)? For instance, imagine having a Canvas shape, and upon clicking a button, it generates the HTML5 code that displ ...

Utilizing AngularJS to interpret and process JSON data

Struggling to properly parse this JSON chunk, as my attempts have not been successful. The structure of the JSON is outlined below. I am aiming to use ng-repeat on all attributes in order to display "Content" and "Title" within a div. JSON: { "Hits": ...

What are some secure methods for integrating iframes into an Angular 7 project?

Is there a secure method to set the URL for an iframe without bypassing security measures like using this.domsanitizer.bypassSecurityTrustResourceUrl(url)? While this approach may be flagged as a high vulnerability by tools such as Veracode, is there a w ...

Is there a way to verify the existence of a username while avoiding cross browser compatibility issues?

I have created a registration form that dynamically checks existing usernames and email addresses in the database. Unfortunately, it is not functioning properly on FireFox or IE, but works fine on Safari and Chrome. Below is the code snippet: <input ty ...

I'm having trouble getting the specific object I need to be returned

I'm currently working with NodeJS and using some JS promises in an attempt to interact with a CMS via a specific web application. The issue I'm facing is when I try to fetch data from the CMS API. While I can successfully log the data to the cons ...

What is the best way to pass a value from a static function to another object?

(function ($, window, undefined) { 'use strict'; class Slider { static init(loop) { Slider.loop = loop; return Slider.loop; } }; $.fn.blueSlider = function(loop, options) { var defaults = { ...