Passing a $scope.property as a reference to a factory object

I am in need of a Factory object that can be linked with a $scope.property to produce a certain result. Additionally, I require the ability to detect changes in either the modifier within the factory instance or the $scope.property in order to update the result. It is possible that my understanding of this pattern could be flawed.

app.factory('MyFactory',
    function () {

        var MyFactory = function (name, modifier) {
            this.name = name;
            this.result = 0;
            this.modifier = modifier;
        }

        //I may want to invoke this method when the modifier or MyProperty changes
        MyFactory.prototype.modifyingMethod = function () {
            this.result = this.modifier * //externalProperty;
        }

        MyFactory.prototype.watcher = function () {
            //uncertain about the purpose of this method or if it's necessary at all
            // A recalculation of the result similar to using $watch is needed here
            this.modifyingMethod();
        }

        return MyFactory;
    }
)

app.controller('MyCtrl'
    function($scope, MyFactory) {

        $scope.MyProperty = 42;

        $scope.MyFactoryOptions = [
            new MyFactory('Option1', 1),
            new MyFactory('Option2', 2),
            new MyFactory('Option3', 3),
            new MyFactory('Option4', 4),
            new MyFactory('Option5', 5)
        ];
    }

The challenge lies in monitoring both MyProperty and the modifier (potentially altered by users) through $watch to update the result accordingly. When the Property is a value type, passing it into the Factory constructor might not suffice. One solution could be passing a function that returns MyProperty.

Is it feasible to implement an internal $watch within the factory? If done externally, in the controller, a separate watch would be required for each instance. Would establishing a register method on the factory object be a better approach?

Any suggestions for patterns or alternative methods that could prove useful in this scenario?

Answer №1

Essentially, your Factory can be thought of as a gateway to a group of objects (such as an array or associative array, or even a plain JavaScript object).

I must say, I find your approach using Objects quite intriguing and believe that similar results can be achieved. However, I have created a demo that demonstrates how I would tackle the issue:

Following the MVC pattern, your Factory serves as the model, keeping the controller simple while the HTML with directives represents the view.

Your controller observes user changes ($scope.MyProperty with $watch). Meanwhile, the model is aware of external property changes it depends upon. It's important to note that changes to the ExternalObject service/factory will only be detected if they are non-primitive values. This is why the ExternalObject factory returns the entire object.

In an ideal scenario, you wouldn't need to use an interval to listen for changes; instead, you'd receive a JavaScript event. If possible, opt for this method! Updates to objects outside Angular's scope will require a $scope.$apply() to reflect the changes in the view. Both $interval and $timeout trigger a $scope.apply(), making them best practices.

There is still a lot of refinement needed in this code, but it should provide you with a fundamental understanding of how to implement an alternative structure:

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

Typescript loading icon directive

Seeking to create an AngularJS directive in TypeScript that wraps each $http get request with a boolean parameter "isShow" to monitor the request status and dynamically show/hide the HTML element depending on it (without utilizing $scope or $watch). Any ...

Choose a random cell in Jquery every second

I am searching for a method to choose one div out of sixteen and change its CSS backgrounds. This selection needs to occur every second, so a new div is selected from the group each second. I am struggling with implementing the "every second" functionalit ...

Can someone break down the meaning of "returning $http.post" in Angular while developing a factory service?

I've been grappling with the concept of return $http.post('/some link') and can't seem to fully grasp it. Imagine I have a node/express backend and am utilizing Angular for my frontend. Within my api, there is a function like this: v ...

The young ones whose height is 80% that of their taller parent's

Achieving the Desired Height In order to set a div with 80% of the height of its parent element without a defined height, I am aiming for a responsive effect. The Layered Layout Issue Within my layout consisting of five layers - .header, .site, .contain ...

What is the best way to apply a datepicker to all textboxes with a specific class using jQuery?

I have enclosed multiple fields within div elements in order to specify them with a datepicker for a better user experience. For example: <div class="need-date" > <label>Appointment Date</label> <input id="id_appointment_date" ty ...

Interpolating UV is not allowed: 'flat': Using a reserved word in an illegal manner

As a beginner, I recently learned that UV coordinates are not interpolated in WebGL, allowing for exact pixel values to be retrieved. However, when attempting to use the 'flat' keyword, I encountered an error. By adding 'flat' before t ...

What is the process for implementing a fallback image in Material UI?

Hey there! I'm currently looking to customize the fallback image of a Material UI Avatar with my own original image. Does anyone have any tips on how I can achieve this? const fallbackImage = "../../fallback/img.png" const AvatarWithBadge = ...

Submitting a form with dynamic columns and rows can be achieved by carefully designing the form to

Below is the form structure: <table id="participants" class="table table-bordered table-hover table-responsive text-center"> <form action="unique-controller.php" method="post" id="uniqueForm" enctype="multipart/form-data"> <input type="hidd ...

issues encountered with sending a multidimensional array using ajax, specifically with the index[0]

I'm struggling with sending a multidimensional array from PHP to Javascript/jQuery, encountering a peculiar issue. Upon transmitting index 0 through json_encode($array);, the desired response format is successfully received by the client: [[0,0],[1, ...

Tips for accessing and manipulating the parent, sibling, next, and previous elements of the current element with AngularJS

Below is an example of HTML code where I have linked $scope properties and values to controls: https://i.sstatic.net/NRP0i.png This is the function that triggers when an image is clicked and changes the path of the images: $scope.ratingClick = function( ...

Leveraging Vue 2.0 and webpack to integrate components from an npm package

As I venture into setting up a project with webpack and Vue 2.0, I encountered a slight hiccup when trying to incorporate components from npm packages (such as vue-parallax) into my project. Upon installing the package, everything seems to be in place, bu ...

Issue detected in React Rollup: the specific module 'name' is not being exported from the node_modules directory

Currently in the process of creating a library or package from my component. The tech stack includes React, Typescript, and various other dependencies. Encountering an error while using Rollup to build the package: [!] Error: 'DisplayHint' is ...

Tips for creating a partial matching filter on an array using elements from a separate array

My goal is to filter an array by finding partial matches from another array. To illustrate, consider the following arrays: Array1 = categories: 292300, categories: 300, categories: 292500280 Array2 = 300, 498 After filtering, ...

Can the appearance of the model be adjusted when using the GLTF or GLB format in Three.js?

Initially, I encountered an issue where my model appeared completely black. Although some sources suggested it was due to lighting, adjusting the light did not improve the model. Ultimately, I discovered that the problem lied within the model itself, and I ...

As I embark on building my web application using next.js, I begin by importing firebase from the "firebase" package. Unfortunately, a particular error unexpectedly surfaces in the terminal

I am currently developing a next.js web application and I have decided to utilize firebase for both database management and authentication. However, when attempting to import firebase in a specific file, I encountered the following error: Error - ./firebas ...

AngularTS - Using $apply stops the controller from initializing

Every time I launch the application, the angular {{ }} tags remain visible. Removing $scope.$apply eliminates the braces and displays the correct value. I am utilizing Angular with Typescript. Controller: module Application.Controllers { export class Te ...

Dynamic SVG circles with timer and progress animation

Is there a way to modify the following: var el = document.getElementById('graph'); // get canvas var options = { percent: el.getAttribute('data-percent') || 25, size: el.getAttribute('data-size') || 220, lineW ...

Having trouble with the ionic ion-nav-buttons not working on initial load?

My table view triggers the PixCtrl controller when a cell is clicked. If the connection is successful, data is retrieved using $http.get, otherwise sqlite is used. This setup works fine. However, I am facing an issue with my ion-nav-buttons being dynamic. ...

Deciphering Encrypted JSON Data

In need of help with our app that generates complex JSON objects where properties and values are in hexadecimal format. How can we convert them back to strings? Example Object: { "636f756e747279": { "6e616d65": "43616e616461", "6 ...

Consistently Incorrect Date Formatting in Bootstrap Display

I have a potential issue with my date display. It should show a default "Start Date" in a short date format, but when the "Sale Date" DropDownBoxFor is toggled, it should display an AJAX result date. However, the display always appears in a date and time f ...