The art of toggling input values with Angular JS

I have a simple application where users input string values into two fields and the text is incorporated into a sentence.

I am looking to add a button that, when clicked, will switch the values in the fields.

HTML

<body>
 <div ng-app="myApp" ng-controller="myCtrl">
    Old Value: <input type="text" ng-model="oldValue"><br>
    New Value: <input type="text" ng-model="newValue"><br>
    Prefix: <input type="text" ng-model="prefix"><br>
    <br>
    UPDATE {{ prefix }}_options SET option_value = replace(option_value, 'http://{{ oldValue }}', 'http://{{ newValue }}') WHERE option_name = 'home' OR option_name = 'siteurl';<br>

    UPDATE {{ prefix }}_posts SET guid = replace(guid, 'http://{{ oldValue }}','http://{{ newValue }}');<br>

    UPDATE {{ prefix }}_posts SET post_content = replace(post_content, 'http://{{ oldValue }}', 'http://{{ newValue }}');<br>

    UPDATE {{ prefix }}_postmeta SET meta_value = replace(meta_value,'http://{{ oldValue }}','http://{{ newValue }}');<br>
</div>
</body>

JAVASCRIPT (Angular)

var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
    $scope.oldValue= "oldvalue";
    $scope.newValue= "newvalue";
    $scope.prefix= "wp";
});

Upon clicking a button, 'oldvalue' and 'newvalue' will swap positions.

Any assistance on this matter would be highly appreciated.

Answer №1

To accomplish your goal, you will need to create a button and utilize the ngClick directive. Here is an example:

<button type="button" value="swap" ng-click="swap()">Swap</button>

Next, you can create a function that swaps your variables. There are various ways to achieve this. One way is:

$scope.newUrl = [$scope.oldUrl, $scope.oldUrl = $scope.newUrl][0];

Alternatively, with ES6:

[$scope.oldUrl, $scope.newUrl] = [$scope.newUrl, $scope.oldUrl];

Here is a functioning code snippet:

var app = angular.module('app', [])
  .controller('mainCtrl', function($scope) {

    $scope.oldUrl = "oldurl";
    $scope.newUrl = "newurl";
    $scope.prefix = "wp";
    $scope.swap = function() {
      $scope.newUrl = [$scope.oldUrl, $scope.oldUrl = $scope.newUrl][0];
    }
  });
<!DOCTYPE html>
<html ng-app="app">

<head>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.7/angular.min.js"></script>
</head>

<body ng-controller="mainCtrl">
  Old URL:
  <input type="text" ng-model="oldUrl">
  <br> New URL:
  <input type="text" ng-model="newUrl">
  <br> Prefix:
  <input type="text" ng-model="prefix">
  <br>
  <button type="button" value="swap" ng-click="swap()">Swap</button>
  <hr>
  UPDATE {{ prefix }}_options SET option_value = replace(option_value, 'http://{{ oldUrl }}', 'http://{{ newUrl }}') WHERE option_name = 'home' OR option_name = 'siteurl';
  <br> UPDATE {{ prefix }}_posts SET guid = replace(guid, 'http://{{ oldUrl }}','http://{{ newUrl }}');
  <br> UPDATE {{ prefix }}_posts SET post_content = replace(post_content, 'http://{{ oldUrl }}', 'http://{{ newUrl }}');
  <br> UPDATE {{ prefix }}_postmeta SET meta_value = replace(meta_value,'http://{{ oldUrl }}','http://{{ newUrl }}');<br>
</body>

</html>

Answer №2

$scope.changeUrl = function () {
   var prevUrl = angular.copy($scope.previousUrl);
   $scope.previousUrl = angular.copy($scope.newerUrl);
   $scope.newerUrl = prevUrl;
}

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 display a div after a form submission?

I recently added a contact form to my website and successfully set it up so that when the user clicks the contact button, the form pops out. However, instead of redirecting the user to a separate result page after submitting the form, I want a result div ...

How to retrieve the width of a document using jQuery?

Having a strange issue with determining the document width using $(document).width() during $(window).load and $(window).resize. The problem arises when the browser is initially full screen and then resized to a narrower width, causing content to require ...

Distinguishing between setting a value in the state directly versus setting a value within an object in the

I have noticed a difference in behavior based on whether I am using a boolean value with useState directly, or if I am using a boolean value inside an object with useState. The following code snippet demonstrates how the hidden text will be displayed when ...

Can I add the object to the DOM and hold off on executing any events until the next

Just came across this intriguing interview question (shown below). Could someone please provide an explanation of the question and then offer a solution? Develop a function that takes an object and adds it to the DOM, ensuring that events are stored unt ...

Error: Unable to access document property as it is null and cannot be read

Trying to launch a new window from another new window triggers the error above. This is my SystemModal.js const SystemModal = (props) => { console.log(props) const [visible, setVisible] = useState(false); return ( <Row> ...

Incorporate an external JavaScript script using code

I'm currently working on integrating a map widget from 'Awesome Table' into the codebase of an open-source CRM platform. The specific code snippet I need to add is <div data-type="AwesomeTableView" data-viewID="-KLtnY5OHJPgnEOX1bKf"> ...

AngularJS postback method fails to trigger

Seeking assistance with my angularJS AJAX postback method. Below is the HTML code I have created: <html xmlns="http://www.w3.org/1999/xhtml" ng-app> <head runat="server"> <title></title> <script src="Scripts/angular.js ...

angular not routing properly

I have set up an index.html page where I have included 2 links: <!DOCTYPE html> <html ng-app="test"> <head> <title>My Angular App!</title> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.1/angular. ...

Utilize AngularJS binding to pass a JavaScript object seamlessly

I am trying to use AngularJS bindings to pass an object with multiple string values to another component. const personName = { firstName: this.conversation.customer.firstName, lastName: this.conversation.customer.lastName }; const template = ` ...

Failure to receive results from $.getJSON request

I am currently working on developing a web page that allows users to search and retrieve Wikipedia pages based on their search results. Below is the relevant HTML code for the search feature: <form class='search-form' onsubmit='return f ...

Converting a one-dimensional array into a two-dimensional array in JavaScript explained

Below is the code snippet const arrayColumn = (arr, n) => arr.map(x => x[n]); const pcorr = (x, y) => { let sumX = 0, sumY = 0, sumXY = 0, sumX2 = 0, sumY2 = 0; const minLength = x.length = y.length = Math.min(x.length, y.le ...

Encountering a connection error while running a Node.js Selenium test case on Chrome. The specific error message received is: "Error: ECONNREFUSED - Connection refused to 127.0

When attempting to run a test case on a Selenium Node.js server, an error was encountered: Error: ECONNREFUSED connect ECONNREFUSED. The test case script is as follows: var assert = require('assert'), test = require('selenium-webdriver ...

What is the method by which AngularJS retrieves the values for parameters such as data, status, etc?

Forgive me if this is a silly question, but I'm struggling to understand: function login(email, password){ return $http.post('/api/v1/login/', { email: email, password: password }).then(loginSuccessFn, loginError ...

When implementing components, Material UI encounters errors in trying to read properties of null

Currently, I am facing a challenge in displaying text using MUI in Next.js. I initialized my Next app using npx create-next-app. To troubleshoot the issue, I have attempted deleting node-modules and running npm i, repeating the process in the parent direct ...

Tips for finding the *index* of distinct values in an array

My goal is to identify the indexes of unique values in an array. While I've come across various methods for removing duplicate values from an array, such as those found here: How to get unique values in an array I'm currently struggling to find ...

Watching the $scope variable using $watch will result in triggering even when ng-if directive is used, displaying

Encountering an unusual behavior in AngularJS that may appear to be a bug, but there could be a logical explanation. A certain value is being passed to a directive as an attribute. Within this directive, the parameter is being watched using $scope.$watch. ...

Is there a way to invoke bootstrap 5 modals using JavaScript without the need for jQuery in the scripts?

Despite the existence of similar inquiries regarding this issue, I am determined to discover a solution that does not involve integrating jQuery into my scripts. Currently, I am encountering an error when attempting to invoke bootstrap 5 modals using JS. M ...

Angulating Service Testing

I am encountering an issue that I'm not sure how to resolve because I am inexperienced when it comes to testing. Currently, I am testing a service that includes the following code: import { Injectable } from '@angular/core'; import { Endpo ...

Retrieving a nested sub collection within each object of a Firebase collection in a React application

I'm working on a React app that retrieves elements from Firebase and displays them in a grid. I want to show a list of subcollection elements for each grid line, but I'm unsure how to achieve this. Here's where I currently stand: export defa ...

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