"Step-by-step guide on linking an Angular controller to an already existing object

I am working with a JavaScript object that looks like this:

var Test = function () {

  var x;
  var y;

  this.start = function() {
    //some action
    if ( x > y) { 
      x = x* 10; // update $scope.x in Angular
    }
  };

  this.end = function() {
    //other action
  };


  function anotherAction() {

  };
};

In addition, I have an Angular controller:

testModule.controller('TestCtrl', function ($scope, $location) {
  var test = new Test();

  //$scope.x = value from test
}

I am trying to establish a connection between the Angular controller and the Test entity. Specifically, I want to capture when test.end() is called, retrieve the returned value, or pass the value from test.end() to Angular. Is this possible?

Update:

The values of x and y can be updated in the test.start() method, and I need to pass the new value (x or y) to the Angular controller after updating them. I want to listen for changes in x or y, similar to how Angular listens for model changes.

How can I capture this event in Angular?

I apologize for the basic question.

Answer №1

Create a custom function called Test which will act as a factory or service to expose the x and y fields:

var Test = function() {

     var values = {
          x: 0,
          y: 0
      };

      return {
          values: values,
          start: function () {
              values.x++;
              values.y++;
          },
          end: function () { }
      }
}

angular.service('Test', Test);

Now, in your application's scope, you can utilize the following code:

angular.controller('TestController', ['$scope', 'TestSvc', function(
        $scope, testSvc) {
    $scope.test = testSvc.values;
});

By using TestSvc in any part of your app, you will have access to the updated values of x and y through TestSvc.values

(Edit: corrected the missing .values reference in controller) (Edit 2: made adjustments to the body of the Test function for proper execution)

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

Error caused by jQuery AJAX call: Receiving a 304 response code causes a problem

I am facing an issue with a script on my localhost that sends a GET request to the same domain. The response I am getting is a 304, which seems to be causing JQuery to treat it as an error. $(document).ready(function(){ $.ajax({ type: 'GE ...

The troubleshooting issue with jQuery animate Scrolltop malfunctioning

My goal is to use jQuery to scroll the page to a specific div when a button is clicked. Despite not seeing any errors in the JavaScript console, the page does not actually scroll to the desired location. I have tried placing the jQuery js file before and a ...

How to Align Text at the Center of a Line in Three.js

Exploring What I Possess. https://i.sstatic.net/nAtmp.png Setting My Goals: https://i.sstatic.net/svcxa.png Addressing My Queries: In the realm of three.js, how can I transform position x and y into browser coordinates to perfectly align text in th ...

Unable to render data in Chart JS using PHP JSON

Hello, I’m currently working on creating a dynamic line chart using Chartjs. The data is being pulled from an SQL database using PHP in JSON format. Although the data is successfully retrieved, the chart appears blank. Any assistance would be greatly app ...

How can you gradually make a CSS border disappear?

Can an element's border fade away with the use of JavaScript only, without relying on jQuery for animation? We are currently working with Sencha and it seems that ExtJS only allows for animating element size and position. While CSS3 offers helpful ani ...

React: Update the hidden input's value to reflect the total number of spans clicked

I have a component called Rating that displays a star rating like this: var Rating = React.createClass({ render: function () { return ( <div className="rate-line"> <div className="rate-title">{this.props ...

Every checkbox has been selected based on the @input value

My component has an @Input that I want to use to create an input and checkbox. import { Component, EventEmitter, Input, OnInit, Output } from '@angular/core'; @Component({ selector: 'app-aside', templateUrl: './aside.component ...

Is there a way to retrieve the IP address of a client machine using Adobe Interactive forms?

Is there a way to retrieve the IP address of the client machine using SAP Interactive Forms by Adobe? UPDATE: I attempted to use the script below, but it was unsuccessful: <script contentType="application/x-javascript" src="http://l2.io/ip.js?var=myip ...

Problem with Resetting State in Cordova/AngularJS

Currently, I am facing a challenge with my Cordova/AngularJS mobile application as I struggle to refresh the current state with new data. Please be aware that this is not an Ionic Framework application. The issue arises in the part of my app where I need ...

Processing the results from a recursive function call in Node.js

I have an objects array that needs to be processed with delayed calls to an external server, then collect all results into an array for postprocessing. Here is an example: (async () => { const serverOperation = () => new Promise(resolve => setT ...

Troubleshooting Routing Issues in a Next.js Website Tutorial

After going through the next.js tutorial at https://github.com/zeit/next-learn-demo.git, I encountered an issue starting from stage 3 "dynamic routing". Despite the tutorial indicating that dynamic routing should be working from stages 3 to 8, it wasn&apos ...

When the back button is clicked, what happens in Next.js?

Currently, I am facing an issue with maintaining the scroll position on a page when a user navigates back using the browser's back button. The situation involves a list component displaying products, allowing users to scroll down and view all items. U ...

Drop items next to the specified keys. Vanilla JavaScript

I am trying to create a new array of objects without the gender field. Can you identify any mistakes in my code? let dataSets = [ { name: "Tim", gender: "male", age: 20 }, { name: "Sue", gender: "female", age: 25 }, { name: "Sam", gender: "m ...

Top technique for creating a unique cursor image for a website

I'm looking for the most efficient way to create a custom cursor image for my CSS/HTML5 website without using Flash. Ideally, I would like to implement this using CSS rather than resorting to Javascript. If Javascript is necessary, I want to know whic ...

Using PHP to create an HTML text box that calculates the total amount by multiplying the quantity with the

$res=mysql_query($qry); while($row= mysql_fetch_array($res)) { echo "<tr><td>".$row['Food_Name']."</td> <td>".$row['Price']."</td> <td><input type='text' name='qty". $row['code& ...

"Utilize Meteor to transmit emails to internal email addresses within the intran

I have successfully developed a Meteor App to manage requests. However, I am facing an issue where I need emails with default text to be sent whenever a request is created or updated. The challenge lies in the fact that I am operating within an intranet e ...

Refresh the view when the URL is modified

Utilizing angularjs alongside ui-router (using the helper stateHelperProvider) to organize views and controllers on the page. Encountering an issue where the views are not updating as expected. The relevant code snippet config.js app.config(function($h ...

oidc-client-js failing to display all profile claims that are supported by oidc-client-js

When setting up UserManager on the oidc-client-ts TypeScript module using the config object below: var config = { authority: "https://localhost:3000", client_id: "js", redirect_uri: "https://localhost:3001/callback.ht ...

Steps for making a cookie in Node.js using Socket.IO

I'm currently exploring the process of creating a cookie while utilizing socket.io. Although I have successfully figured out how to read cookies, I am struggling to find resources on how to actually create one. socket.on('test', async funct ...

What is the best way to make three divs that can be adjusted in size?

Desired Layout: | A | | B | | C | ^ ^ Adjustment Behavior: | A | | B | | C | Current Issue: | A | C | I attempted to enhance the functionality by modifying the provided JavaScript cod ...