What is preventing me from generating a string for transform:translate within Angular.js?

Attempting a new approach here

$scope.graph.transform = "transform: translate(" + 
                          $scope.graph.width + "," + 
                          $scope.graph.height + ");";

Despite my efforts

<h3>transform: <span ng-bind="graph.transform"/></h3>

I'm only receiving

transform: transform: translate(undefined,undefined);

However, I am sure the values are present, as shown by

<h3>transform: <span ng-bind="graph.height"/></h3>

This yields

transform: 336

MORE INFO:

Included in the code is this snippet:

     $scope.graph = {};
     $scope.$watch(function(){
         return $window.innerWidth;
     }, function(value) {
         $scope.graph.width = value * 0.5;
     });

     $scope.$watch(function(){
         return $window.innerHeight;
     }, function(value) {
         $scope.graph.height = value * 0.5;
     });

Answer №1

Due to this scenario:

$scope.graph = {};

you can set defaults as follows

$scope.graph = {
    height: 0,
    width: 0
};

The values for height and width remain undefined until the watch is triggered. Your current implementation of watches does not account for checking if the values are undefined. The initial trigger of the watch is undefined, and it may not trigger again until the screen is resized.

$scope.$watch(function(){ 
    return $window.innerWidth; 
}, function(value) {
    if(value){
        console.log(value);
    }
});

$scope.$watch(function(){ 
    return $window.innerHeight; 
}, function(value) {
    if(value){
        console.log(value);
    }
});

Additionally, a $digest cycle is not automatically triggered on window resize, only during user events. Therefore, you'll need to implement the following:

$window.addEventListener('resize', debounce(function(){
    $scope.$apply();
}, 500));

It's important to debounce the event to prevent it from being called too frequently, which could crash your application. A simple debounce function similar to David Walsh's debounce function is used here, but other libraries like lodash or jQuery may have built-in alternatives.

function debounce(func, wait, immediate) {
    var timeout;
    return function() {
        var context = this, args = arguments;
        var later = function() {
            timeout = null;
            if (!immediate) func.apply(context, args);
        };
        var callNow = immediate && !timeout;
        clearTimeout(timeout);
        timeout = setTimeout(later, wait);
        if (callNow) func.apply(context, args);
    };
}

Furthermore, binding the values in the manner seen above will not be updated by the $watches. To address this, use the following:

<h3>transform: translate({{ graph.width }}, {{ graph.height }});</h3>

An updated plunker link is provided for reference. Resize the right window to trigger the $watch function.

If you prefer to utilize $watchGroup, you can pass an array of functions instead of just a single function like so:

$scope.$watchGroup([function(){
    return $window.innerWidth;
}, function(){
    return $window.innerHeight;
}], function() {
    $scope.graph.width = $window.innerWidth / 2;
    $scope.graph.height = $window.innerHeight / 2;
});

A corresponding demonstration using this plunker is also available.

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

Assign the two values to variables in the CSS script

My challenge lies in passing two values to the CSS within the <style> tags. The values are: (background-color: --placeholder; color: --placeholdtext;). I am able to pass either one of the values successfully, but not both at the same time. When I cop ...

Filtering with AngularJS based on integer comparison will assist in stream

Currently, I have implemented a "price" field on my website using the JQuery-UI slider. This field comprises of two integer values: minPrice and maxPrice. Suppose I possess an array of objects structured in this manner: objarr=[ { 'name'=&ap ...

Dropdown selection returning the text value instead of the designated value

Is it possible to retrieve the text "Region 1" instead of just the value '1' from a dropdown menu in PHP? <select name = 'region' id = 'region'> <option value = '1'>Region 1</option> <select&g ...

How can we include a string in the request body in Node.js using Express?

My reverse proxy is functioning properly: app.post('/geoserver', function (req, res) { apiProxy.web(req, res, {target: serverOne}); }); The request already contains a body like this: I want to append a string to the request body that looks ...

Utilizing timezones with Moment.js

Currently, I am utilizing momemt.js and moment-timezone.js to present time in the browser. At this time, I have received epoch time from the server which has been converted to central time. My goal now is to exhibit the time in EST/EDT format. To achieve t ...

What is the best way to organize React components/modules in order to effectively separate the UI?

Currently, I have developed three key components for a dashboard UI project in React. These components include a sidebar, top navigation bar, and a content container. As someone who is new to React after working with Angular, I am now seeking advice on how ...

Using AngularJS to transfer data from a datepicker to an ng-model

I am currently trying to figure out how to pass the date from a datetimepicker into the model. Unfortunately, I am facing some challenges with this process. I wish I could provide a demo of the issue on a fiddle, but I am unsure of how to do so due to the ...

Clicking on hyperlink within email to open in default web browser

I am facing a problem with my Angular web app. Here is the scenario of the issue: When I send a link to my app via email and try to open it from a mobile email client using a short version of a browser or webview (not sure what it's called), I encou ...

Utilizing JavaScript to Parse RSS XML Feeds Across Domains

Looking to parse an RSS (XML) file without relying on the Google RSS feed. I have attempted using JSONP, but it resulted in downloading the file and throwing an error "Uncaught SyntaxError: Unexpected token < ". $.ajax({ type: "GET", ur ...

Using a JavaScript loop to modify the color of the final character in a word

I am curious to find out how I can dynamically change the color of the last character of each word within a <p> tag using a Javascript loop. For example, I would like to alter the color of the "n" in "John", the "s" in "Jacques", the "r" in "Peter" ...

Tips for ensuring that a JavaScript program does not get blocked by other API calls

My JavaScript API currently has limitations that prevent other APIs from being called or allowing the API to call itself while running. The API involves sleeping for a specific duration, during which I would like other API calls to be made as well. I have ...

How to retrieve data as an array using a promise in an Express application with React and

After including an array in the return statement, everything seems to be functioning correctly with dispatch and rendering in reducer-items.js. However, there is a discrepancy when I update the data as it does not reflect the changes made. export defa ...

Error in compiled.php on line 7772: Laravel throwing a RuntimeException when sending HTTP requests from Angular

Hey there, I've been encountering an error intermittently while using Angular $http methods with a Laravel API. Can someone please explain what this error means and suggest potential solutions? I've shared the error log on CodePen for easier refe ...

Continuous Div Carousel with Looping in jQuery

I have developed a basic carousel to cycle through a series of divs, but I am facing some issues. I want the carousel to loop continuously so that after reaching "slide 07," it goes back to "slide 01." Unlike using a carousel plugin, I prefer having an ove ...

Is it possible for me to include a variable with the xmlhttp response text?

There is a function defined as follows: function call_view_details(viewid) { view_details(viewid); setInterval(function(){view_details(viewid)},5000); } which I invoke when the page loads. Its main purpose is to set intervals for view_details(). ...

Navigating through search results on an XML page using jQuery

Context: I am currently facing a challenge involving the integration of Google search outcomes into a webpage I'm constructing. These findings are presented in XML format. My current approach to importing the XML is as follows: if (window.XMLHttpReq ...

HTML not updating after a change in properties

My template is structured as a table where I update a column based on a button click that changes the props. Even though the props are updated, I do not see the template re-rendered. However, since I am also caching values for other rows in translatedMessa ...

Error in ReactJS: Attempting to access property 'preventDefault' of an undefined value

Looking to implement a simple onClick event/function in ReactJS. Upon clicking the button, I intend to execute a function named "onClick", but I encounter this error message in the console: app.js:62 Uncaught TypeError: Cannot read property 'prevent ...

What is the best way to ensure the options/choices div reaches its ideal width?

Check out my StackBlitz project that I've set up In the styles.css file, you'll notice that I defined a fixed width of 650px for the option dropdown div, which is currently working fine @import '~bootstrap/dist/css/bootstrap.min.css'; ...

Change the attribute to read-only upon modification of the dropdown value

I have a dropdown menu with four options. My goal is to make the "number" input field readonly if the user selects either "option3" or "option4" from the dropdown. <select id="dropdown"> <option value="option1">option1</option> ...