Notification of value changes within a service

Within this particular instance, I am looking to trigger the submitOption function in my service when a change is made to an item's option value.

Can this be accomplished without relying on ng-click/ng-change or making alterations within the form element?

Being new to Angular, I may not be approaching this in the most effective way. However, my objective is to monitor changes in the item's value and automatically submit it to the server upon modification.

I do understand about $scope.watch(), but I have come across warnings against passing scope into a service.

Answer №1

If you want to monitor changes within the controller, consider using $scope.$watch instead of a Service:


$scope.records.items.forEach(watchRecordValue);

function watchRecordValue(record){
    $scope.$watch(function(){ return record.option; }, function(newVal, oldVal){
        if(newVal !== oldVal){
            $scope.records.submitOption(record);
        }
    });
}

However, this workaround is not ideal and should be avoided for cleaner, more maintainable code. It would be better to utilize ng-change as it is simpler and faster. Simply modify the input tag in your HTML as follows:

<input name="options" 
       type="radio" 
       ng-model="item.option" 
       ng-change="records.submitOption(item)" 
       ng-value="option.id" />

(The only difference being the addition of

ng-change="records.submitOption(item)"
)

EDIT (Added "wrapper" solution):

If changing the form directly is not an option, consider wrapping the form in a custom directive. Here's an example:

myApp.directive('myWatch', [function () {
    return {
        restrict: 'A',
        scope: {
            myWatch: '=',
            myHandler: '@',
        },
        link: function(scope, element, attr) {
            scope.$watch('myWatch', function(newVal, oldVal){
                if(newVal !== oldVal){
                    scope.$parent.$eval(attr.myHandler);
                }            
            });
        }
    };
}]);

This allows you to keep your form unchanged by wrapping it:

<div my-watch="item.option" my-handler="records.submitOption(item)">
    <form> <!-- Your original form contents here --> </form>
</div>

Here's the modified JSFiddle with this wrapper: http://jsfiddle.net/shjejb34/

Note: In most cases, using the ng-change solution mentioned earlier is recommended over creating a new directive for this purpose.

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

MaterialUI makeStyles in NextJS causes custom css to revert back when the page is refreshed

Currently, I am working on a NextJS website with some unique styling applied through MaterialUI's makeStyles. Initially, everything looks perfect but then all the custom styling is reset on the second load. It seems to be related to the route, as it o ...

"Learn the technique of adding a comma after each object and transforming it into an array using JavaScript in React JS

Is there a way to add commas after each object and transform it into an array? Below is the response data: {"url":"example.com/john","age":"32"}{"url":"example.com/mike","age":"42& ...

What is the best way to transmit multiple files to the server in node.js?

As a newbie to the world of web development (I've only been coding with luau for around a year), I'm encountering an issue when trying to send multiple files when my server is pinged. Specifically, I want to include a separate style.css file and ...

Is it possible to provide an offset to the raycaster in three.js?

I am currently working on developing a pool game using three.js. As part of the gameplay, I have incorporated a helper ruler that indicates the direction of the hit. This ruler is represented by an ArrowHelper and is positioned at y=0, which aligns with ...

How can you change an array of objects into an array of arrays?

Here we have a JSON object structured like this: var items = [{ title: 'example 1', image: 'http://www.lorempixel.com/700/600/' }, { title: 'example 2', image: 'http://www.lorempixel.com/900/1200/' ...

Retrieving remote JSON data by utilizing a local HTML file with JavaScript and jQuery

I am working on a small utility using a local HTML file (checker.htm) with JavaScript (utilizing jQuery) on my desktop. This utility is designed to request data from my website every 10 minutes. If data is found, it takes no action. However, if no data is ...

Trigger the immediate collapse of all active elements in the Vuetify v-list-group

I have successfully constructed a navigation within a permanent drawer using the v-list component, following the provided instructions. When the drawer is collapsed, only the icons are displayed. Upon hovering over the collapsed drawer, it expands to reve ...

Retrieve servlet input with JavaScript and use Ajax to set the value to a text box

I am working on a servlet that retrieves values from properties files. I need to pass these values to my JavaScript using AJAX and set them in a textbox. As I am new to Ajax, I would appreciate if someone could help me by analyzing the code. SERVLET ...

Jest and Enzyme failing to trigger `onload` callback for an image

I'm having trouble testing the onload function of an instance of the ImageLoader class component. The ImageLoader works fine, but my tests won't run properly. Here's an example of the class component: export default class ImageLoader extend ...

Ever since updating my Node JS, the functionality of the MaterializeCSS carousel methods has ceased to work

Recently, I encountered some issues with my React project that features a materialize-css carousel. The problem arose after updating my nodeJS version from 14.8.1 to 16.13.0. Specifically, these errors kept popping up: TypeError: Cannot read properties o ...

How can I display a Material-UI Drawer that is nested within a Grid component?

I'm currently working on a web application using Material-UI. The main page is structured into 3 grids, all with a fixed height of 500px. I have a requirement to include a drawer within the middle grid that contains some action options. However, my cu ...

Mistakes in design when transforming inline SVG to PNG format

One of my main objectives is to convert a <div> element that contains multiple inline svg images into a png file. The entire process must be carried out within the client's browser using JavaScript. I have experimented with various techniques: ...

JS Equal Heights is a JavaScript plugin designed to ensure

Good evening, A while back, I implemented a JavaScript code snippet to create equal height columns on my website. The initial script looked like this: <script type="text/javascript"> var maxHeight = 0; $(".level").each(function(){ maxHe ...

How can I implement two dropdowns in jquery?

One of my dropdown menus is currently utilizing this code to fetch the selected value: $(document).on('change','#DropDown1',function() { var value1 = $(this).children("option:selected").val(); var data = {"key": value1}; ...

Utilizing Ajax to update the login form without reloading the page and displaying any errors

I have created a login form that utilizes ajax to handle login errors such as "incorrect password" from my login.php file. Instead of reloading a new page with the error message, it now displays the errors on the same login form, which is working perfectly ...

The AJAX POST request encountered an UNKNOWN_PROTOCOL error and did not successfully send the query

I'm encountering an issue while attempting to save a gjson feature in a mongodb using my own server.js file. "use strict"; // Customizable port settings var config = { httpPort: 8080, mongoPort: 27017 } var express = require('expre ...

How can I dynamically preload state in React / Redux using different techniques?

Struggling with initializing state in React / Redux. Before flagging this as a duplicate, I’ve already delved into the following resources: http://redux.js.org/docs/recipes/reducers/InitializingState.htm Redux - managing preload state What are your be ...

Ionic is having trouble transmitting the information

I'm facing an issue with getting and sending data in my service and controller. I have tried creating them but still struggling to make it work. Any suggestions or help would be greatly appreciated. Here is the code snippet: Factory angular.module(& ...

Three.js - Rotation does not follow local orientation accurately

In my current project, I have created an extensive array of objects centered around a focal point within a scene. My goal is to manipulate these objects along their local axes. Initially, I aligned all the objects to face the origin by using a reference ob ...

What is the best way to close a dropdown when clicking away from it on the body?

I wish for the dropdown menu to lose its "show" class when clicked anywhere in the body or window, even if it already has the class "dropdown.menu.show". The show class gets removed and added before utilizing the code `(window.onclick = function(event){})` ...