Handle changes to input values on ng-click even if they were made outside of Angular's control

Looking to pass input values on ng-click even when they are changed outside of Angular. Everything works fine when manually typing, but once the inputs have dynamic values, ng-click passes empty form data. Below is the HTML code snippet:

<form id="form" action="" style="margin:0;">
    <img src="jCrop/images/imagename.jpg" id="imgcrop"/>
    <input type="text" name="hdnx" id="hdnx" data-ng-model="thumbnail.hdnx" ng-change="alert('test')" />
    <input type="text" name="hdny" id="hdny" data-ng-model="thumbnail.hdny" />
    <input type="text" name="hdnw" id="hdnw" data-ng-model="thumbnail.hdnw" />
    <input type="text" name="hdnh" id="hdnh" data-ng-model="thumbnail.hdnh" />
    <button ng-click="save()">Crop Image & Save Selection</button>
</form>

Below are the AngularJS scripts for this functionality:

angular.module('blogAdmin').controller('ThumbnailsController', ["$rootScope", "$scope", "$location", "$http", "$filter", "dataService", function ($rootScope, $scope, $location, $http, $filter, dataService) {
  $scope.thumbnail = {};
  $scope.save = function () {
    if ($scope.thumbnail) {
        console.log($scope.thumbnail);  //log remains empty when values change from outside of Angular
    }
  }
}]);

I've found that using $scope.$apply(); might be the solution, so how can I implement this in the above form?

UPDATE 1

The values are being updated by jQuery code directly placed on the HTML page:

<script type="text/javascript">
    $(function () {
        $('#imgcrop').Jcrop({
            onSelect: getcroparea,
            aspectRatio: 1  //square selection for cropping
        });
    })
    function getcroparea(c) {
        $('#hdnx').val(c.x);
        $('#hdny').val(c.y);
        $('#hdnw').val(c.w);
        $('#hdnh').val(c.h);
        console.log(c.h + " : " + c.w);
        $('#selectedSize').html("Selected region " + c.h + "px : " + c.w + "px");
    };
</script>

UPDATE 2

"$scope is not defined" error encountered

    function getcroparea(c) {
        $('#hdnx').val(c.x);
        $('#hdny').val(c.y);
        $('#hdnw').val(c.w);
        $('#hdnh').val(c.h);
        console.log(c.h + " : " + c.w);
        $('#selectedSize').html("Selected region " + c.h + "px : " + c.w + "px");

        $scope.$apply();
    };

Answer №1

To ensure proper functionality, it is recommended to enclose the form and croppable area within a directive. This allows for easy access to the DOM element where the third-party library is applied, facilitating direct changes to the scope variable instead of altering the input text value.

Answer №2

Although there may be an easy solution, I managed to solve this issue by utilizing the following code:

<script type="text/javascript>
$(function () {
    $('#imgcrop').Jcrop({
        onSelect: getcroparea,
        aspectRatio: 1  //square selection to crop
    });
})
function getcroparea(c) {
    $('#hdnx').val(c.x);
    $('#hdny').val(c.y);
    $('#hdnw').val(c.w);
    $('#hdnh').val(c.h);
    console.log(c.h + " : " + c.w);
    $('#selectedSize').html("Selected region " + c.h + "px : " + c.w + "px");
    $scope.thumbnail = { "id": $scope.id, "hdnx": c.x, "hdny": c.y, "hdnw": c.w, "hdnh": c.h, "imgcrop": $scope.firstImageSrc };
};
</script>

The line $scope.thumbnail = .. is a new addition in the above code snippet, which updates the scope variable each time.

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

Tips for extracting HTML entities from a string without altering the HTML tags

I need assistance with removing HTML tags from a string while preserving html entities like &nbps; & é < etc.. Currently, I am using the following method: stringWithTag = "<i> I want to keep my ->&nbsp;<- element space, bu ...

unable to adjust the maximum height limit

I've been struggling to set a maximum height on the slider I'm currently using. No matter what height value I input, it doesn't seem to take effect. Additionally, I attempted setting the width for the echo img row in the PHP section but enco ...

Redirecting in Next.js without the use of a React component on the page

I need to redirect a page using HTTP programmatically only. The following code achieves this: export const getServerSideProps: GetServerSideProps = async (context) => { return { redirect: { destination: '/', permanent: false, ...

tips for retrieving global variables from ajax calls using promises

Currently, I am retrieving data and storing it in global variables in a less than optimal way. Here is the current method: var tranlationJson = $.ajax({ type: "GET", url: "translation.xml", contentType: "text/xml", dataType: "xml", ...

Node.js error message: Unable to load HTTP module

Recently starting with Node.js, I decided to install the latest version (4.2.1) on my Windows 7 PC. However, when trying to include the HTTP module by writing: var http = require("http"); I'm receiving an undefined error message. Can someone help me ...

Using JSON for saving HTML code

Currently delving into the world of AngularJS and thrilled about organizing data in JSON format. I have decided to create a practical application for hands-on learning. The app is an online magazine where I store the essential data for each article in art ...

List of Nodes with five links

I'm encountering an issue when trying to reference the final node. The expected output is: Linked List with 5 nodes Node Value: Head Node / Next Node Value: Second Node / Last Node Value: null Node Value: Second Node / Next Node Value: Third N ...

Linking Google Form Data to a MongoDB Database

Looking to integrate Google form with mongodb for data collection. Need help setting it up using NodeJs. Any advice on how to approach this? ...

Stop a loop that includes an asynchronous AJAX function

Embarking on my Javascript journey as a beginner, I find myself facing the first of many questions ahead! Here is the task at hand: I have a directory filled with several .txt files named art1.txt, art2.txt, and so on (the total count may vary, which is ...

What could be causing render_template to fail when attempting to update the same parameters more than once?

Lately, I've dived into the world of Flask, MongoDB, and ElasticSearch. So far, my MongoDB and ElasticSearch setups are running smoothly. However, I've encountered an issue with generating a list of dictionaries and displaying them on my HTML we ...

"Stay current with real-time updates in seconds using React technology

Check out this code snippet: const currentTime = new Date().getTime(); const targetTime = new Date('November 15, 2020').getTime(); const difference = currentTime - targetTime; let seconds = Math.floor(difference / 1000) % 60; setInterval(functio ...

Vuejs is throwing an uncaught promise error due to a SyntaxError because it encountered an unexpected "<" token at the beginning of a JSON object

I am currently attempting to generate a treemap visualization utilizing data sourced from a .json file. My approach involves employing d3 and Vue to assist in the implementation process. However, upon attempting to import my data via the d3.json() method ...

Show information when table is clicked

I currently have a 9 x 9 table with unique content in each cell. Is there a way to enable the following functionality: Upon clicking on the text within a specific cell, all related content would be displayed right below that same cell? For instance, if ...

Best Practices for Angular and Managing Database Access

By now, I have a good understanding that angular.js is a client-side framework, which means any database communication involves sending requests to a server-side script on the server using methods like get/post (with node, php, asp.net, or other technologi ...

Encountering an issue: Module """ not located at webpackMissingModule

I'm facing an issue while trying to webpack my express application. Specifically, I encounter the following problem whenever I attempt to access the / page: Encountering Error: Cannot find module "." at webpackMissingModule Below is a snippet of c ...

What's the most effective method to incorporate additional events into this element using the conditional operator?

Looking for help with this code snippet: <span role="link" tabindex="0" :class="tabDetails.showPayment ? 'link' : ''" @click="tabDetails.showPayment ? cTab('payments') : null" ...

Restrict the Angular ng-repeat directive to specific rows only

Suppose we have a JSON dataset listing all languages of books: $scope.data = [{ "title": "Alice in wonderland", "author": "Lewis Carroll", "lang": ["en"] }, { "title": "Journey to the West", "author": "Wu Cheng'en", "lang": [" ...

How to change a POST request to a PUT request using Express and keeping the

In my express app, I have set up two routes like this: router.post('/:date', (req, res) => { // if date exists, redirect to PUT // else add to database }) router.put('/:date', (req, res) => { // update date }) W ...

Tips for showcasing a personalized design using ng-repeat

Upon reflection, I realized that my original question needed improvement, so here is the revised version. Hello! I am new to Angular and I am attempting to create a custom layout for my data list using ng-repeat. I want to display different model values w ...

Passing a variable from a service to a controller in AngularJS

I recently developed a basic app that includes user authentication based on the guidelines found in this useful resource. The core components of my app are a userAccountService, which manages communication with the server, and a login controller that over ...