Unlocking the Power of Angular: Transforming Input into Results

I'm currently exploring how to utilize an input field and fetch a response using Angular directly within the script. As a beginner, I came across this script on codepen. At the end of the code, I've attempted to make a call but haven't completely grasped it yet. This particular script compares an input color with a set array of colors and outputs the closest match. Please excuse any misuse of terminology as I'm still in the learning process.

angular.module('myApp', [])
.controller('control', function($scope, $filter){
  
  var colors = ["27b69d", "23a68f", "1aa48c", "17846f", "0f8b7d", "0e7e72", "0a876e", "097b64", "0a584d", "095046", "ffffff", "000000", "7e888e", "737c81", "383d40", "33373a", "272727", "018391", "017784", "db1e39", "c71b34", "fffee8", "ffb661", "fafafa", "e8e8e8", "d8d8d8", "e7f5f3", "5d6468", "4c5256", "31343b", "2f3335"];

  $scope.colors = colors;

  $scope.submit = function() {
    $scope.new = $scope.newColor; 
    var res = [];
    angular.forEach(colors, function(value, key) {
      res.push(getDiffColor(value, $scope.newColor));
    });
    $scope.colors = $filter('filter')(colors, colors[res.indexOf(Math.min.apply(null, res))]);
  };
  
  $scope.raz = function () {
    $scope.newColor = null;
    $scope.colors = colors;
  }
  
  getDiffColor = function(cola, colb) {
    a = hexToRgb(cola);
    b = hexToRgb(colb);
    return Math.sqrt(Math.pow((a.r - b.r),2) + Math.pow((a.g - b.g),2) + Math.pow((a.b - b.b),2));
  }

  function hexToRgb(hex) {
      var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
      return result ? {
          r: parseInt(result[1], 16),
          g: parseInt(result[2], 16),
          b: parseInt(result[3], 16)
      } : null;
  }
  
  var input = "FFFFFF";
  var result = $scope.submit(input)
  console.log(result);

}) ;  `

In my attempt to achieve this, I appended the following snippet at the end, although I acknowledge it's not correct. The challenge lies in determining what should go inside "result".

Answer №1

Thanks for checking this out.

                <!DOCTYPE html>
                <html ng-app="myApp">
                <head>
                    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.3/angular.min.js"></script>
                </head>
                <body ng-controller="myController">
                    <div>
                        <label> Here is the input: </label>
                        <input type="text"
                               ng-model="newColor"
                               ng-minlength="6"
                               ng-maxlength="6"/>
                        {{input}}
                        <button type="button" ng-click="submit()">Click to Submit</button>
                        <hr />
                        New Value:
                        {{new}}
                        <hr />
                        Closest Color : {{colors | json}}
                        <hr />
                        {{getDiffColorErrors}}
                        <hr />
                    </div>

                    <script type="text/javascript">
                        angular.module('myApp', [])
                            .controller('myController', function ($scope, $filter) {
                                $scope.newColor = "FFFFFF";
                                $scope.new;
                                var colors = ["27b69d", "23a68f", "1aa48c", "17846f", "0f8b7d", "0e7e72", "0a876e", "097b64", "0a584d", "095046", "ffffff", "000000", "7e888e", "737c81", "383d40", "33373a", "272727", "018391", "017784", "db1e39", "c71b34", "fffee8", "ffb661", "fafafa", "e8e8e8", "d8d8d8", "e7f5f3", "5d6468", "4c5256", "31343b", "2f3335"];

                                $scope.colors = colors;

                                // Triggered on click event
                                $scope.submit = function () {
                                    $scope.new = $scope.newColor;
                                    var res = [];
                                    angular.forEach(colors, function (value, key) {
                                        res.push(getDiffColor(value, $scope.newColor));
                                    });
                                    $scope.colors = $filter('filter')(colors, colors[res.indexOf(Math.min.apply(null, res))]);
                                };

                                $scope.reset = function () {
                                    $scope.newColor = null;
                                    $scope.colors = colors;
                                }

                                getDiffColor = function (cola, colb) {
                                    a = hexToRgb(cola);
                                    b = hexToRgb(colb);
                                    if (!a || !b) {
                                        $scope.getDiffColorErrors = "Error in getDiffColor : !a || !b"
                                        return;
                                    }
                                    return Math.sqrt(
                                        Math.pow((a.r - b.r), 2) +
                                        Math.pow((a.g - b.g), 2) +
                                        Math.pow((a.b - b.b), 2));
                                }

                                function hexToRgb(hex) {
                                    var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
                                    return result ? {
                                        r: parseInt(result[1], 16),
                                        g: parseInt(result[2], 16),
                                        b: parseInt(result[3], 16)
                                    } : null;
                                }
                            });
                    </script>
                </body>
                </html>

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

Input a new function

Trying to properly type this incoming function prop in a React Hook Component. Currently, I have just used any which is not ideal as I am still learning TypeScript: const FeaturedCompanies = (findFeaturedCompanies: any) => { ... } This is the plain fun ...

Send the output of MPDF back to the browser by utilizing JSON in combination with ExtJS

I am currently using mpdf to generate a PDF report in my PHP code. I have successfully been able to save the PDF file and view it by using Output($pdfFilePath), but now I need to send it back to the browser using JSON without saving it on the server. To ac ...

methods to add an object to formData in vuejs

I am having trouble appending an object to FormData using Axios. I do not want to send data by JSON.stringify() data () { return { product: { title: '', description: '', properties: { ...

A method for retrieving the variables from the initial API function for use in a subsequent API function

$.getJSON(url, function (data) { $.getJSON(url_wind, function (data2) { //perform actions with 'data' and 'data2' }); }); While attempting to use the data from the initial getJSON() call in the second getJSON() call ...

Unexpected Results: React Multiline MUI Text Box Fails to Show Intended Content

In the process of developing a React application, I have come across a requirement to implement a multiline text box for editing job advertisements. The text box should initially display a default value containing dynamic placeholders such as [displayTitle ...

Navigating through cors in next.js

Currently, I have set up my front end using Netlify and my backend using Heroku with Next.js For the fetch request on the front end, here is an example: fetch(`https://backendname.herokuapp.com/data`, { method: 'POST', headers: { & ...

What is the code to convert data to base64 in Javascript when it is not a string?

I am in the process of transferring functionality from an Objective-C iPhone application to a JavaScript iPhone application (using Appcelerator Titanium). In my Objective-C code, I have an NSData object that represents a specific token: //NSData object sh ...

What makes AJAX take so much time to load?

Hey everyone, I’ve been working on compiling and sending some forms to a PHP file but I've been noticing that the process is quite slow. Even when I use var_dump in PHP to only display the POST values, it still takes a considerable amount of time co ...

Is there a way to integrate Prettify with Blogger/BlogSpot?

I am currently utilizing blogger.com as a platform to showcase programming texts and I am interested in incorporating Prettify (similar to Stack Overflow) to enhance the appearance of my code samples. What is the best method for installing the Prettify sc ...

Is there a way to streamline and optimize this React/Material UI code for faster performance?

There seems to be a lot of repetition in the code that needs to be cleaned up. I'm wondering if the switch statement is necessary. It looks like it requires the muiTheme palette to be passed this way. Also, can these theme constants be placed in a sep ...

Steps for handling errors in Node.js when the query result rowCount is 0 and throwing an error in response

If the rowcount is 0, I need to send a response as failed. If the rowcount is 1, I need to send a success status. Can someone please assist me with this? When I try to print (client.query), it displays the result in JSON format (refer to attached image). ...

Ways to include input values

In my form, there are 4 text boxes labeled as customer_phy_tot, customer_che_tot, and customer_bio_tot. I want to add up the values entered in these 3 boxes and display the sum in a 4th input box called customer_pcb_tot. customer_bio_obt.blur(function(){ ...

what is the best way to center list items in material ui?

I have been attempting to align the list items (checkbox, text, and buttons) within a Material UI list in the center, but all my attempts have been unsuccessful. Is there anyone who knows how to resolve this issue? Your help would be greatly appreciated! h ...

Utilizing the power of AngularJS directives along with the functionality of a

I am completely new to angular js, but I have successfully integrated a jQuery UI datepicker into my Angular JS project. Now, I am facing the challenge of formatting the date selected by the jQuery datepicker into ISO date format. Here is the code snippet: ...

Blank YouTube Popup Modal

I am in the process of creating a pop-up modal that contains an embedded YouTube video, but my modal is not displaying properly. I am utilizing Bootstrap and have two separate sections along with JavaScript code. When the modal appears, it remains empty. I ...

"Utilizing Jquery to extract data from a form field and combine it with a URL for maximum value

Today, I am delving into the world of jQuery for the first time and finding myself in need of some assistance with a particular problem. While this issue may seem trivial to experienced individuals, it is posing quite a challenge for me. The dilemma lies ...

Not all API results are being displayed by the Nextjs API function

I am facing an issue with rendering all the returns from the API in my Next.js application. The API, which is created in Strapi, is only displaying 1 out of the 3 possible returns. I am a beginner when it comes to using APIs and I suspect that the issue li ...

Ionic: Error - Unable to access the 'ready' property of an undefined object

I keep encountering this error message: TypeError: Cannot read property 'ready' of undefined Here is the snippet of my code: angular.module('app', ['ionic', 'app.controllers', 'app.routes', 'app.dir ...

Using Reactjs to automatically populate text into a React-Select Input field

I have implemented react-select in my project. Sometimes, I encounter the need to update my react-select input field without directly interacting with it (such as injecting text into it). However, I am unable to find a proper way to achieve this based on ...

What is the process for setting a personalized title for error pages in Remix?

I'm currently working on setting up the 404 page for my Remix app, but I'm facing challenges when it comes to configuring the <title> meta tag for these pages. Within my root.tsx file, I have defined a MetaFunction and a CatchBoundary: exp ...