The Angular observation loop

I am looking to develop a unique color picker that integrates RGB sliders with the farbtastic color picker. Here's the current setup:

app.controller('PickAColorController', function ($scope) {
$('#colorpicker').farbtastic(function (col) {
    $scope.$apply(function () {
        $scope.color.setColor(col);
    });
});

$scope.$watch('color.r', function () {
    var color = chroma($scope.color.r, $scope.color.g, $scope.color.b);
    var cp = $.farbtastic('#colorpicker');
    cp.setColor(color.hex());
})

$scope.color = {
    hex:'',
    r: 0,
    g: 0,
    b: 0,
    
    setColor: function (hexCode) {
        this.hex = hexCode;
        var rgb = chroma(hexCode).rgb(); 
        this.r = rgb[0];
        this.g = rgb[1];
        this.b = rgb[2];
    }
};
});

The setup is functioning well without the watch feature, but upon its inclusion, I encounter the following error:

 Error: [$rootScope:inprog] http://errors.angularjs.org/1.3.14/$rootScope/inprog?p0=%24digest
 at Error (native)
 ...

This issue seems to stem from the cyclic nature of color modifications triggering continual watches on variables and ultimately leading to AngularJS error termination. Any suggestions on how to address this cleanly?

Answer №1

To avoid the in progress error, consider using $timeout instead of directly calling $apply. This will push the code to the end of the digest queue.

$('#colorpicker').farbtastic(function (col) {
    $timeout(function () {
        $scope.color.setColor(col);
    });
});

Remember to inject $timeout in your controller.

It's important to note that DOM manipulation should be handled in directives, not controllers.

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

A guide on retrieving real-time data from PHP using Ajax

Being new to Ajax, I am struggling to grasp how to retrieve changing variable values from php. Below is the code snippet that I have been working on: <?php $pfstatetext = get_mypfstate(); $cpuusage= cpu_usage(); ?> <div id="show"> <c ...

directive that is programmatically inserted into an AngularJS application

Currently, I am working on a custom directive that needs to include an ng-click attribute to the element. Despite my attempts to add the ng-click directive in various sections such as compile function, pre and post link functions, I am facing issues wher ...

AngularJS bracket-enhanced template

Why is AngularJS giving an error when brackets are used inside ng-template content? I am trying to create an input field that should accept an array, but I keep getting this error message: "Error: Syntax Error: Token ']' not a primary expression ...

Bug in ExtJS 4 causing the clickrepeater to be disabled when using the datepicker

I've developed a custom subclass of the DatePicker class. Within the update() method, I have implemented logic to disable the prevRepeater if the current month matches the month of the minDate property: me.prevRepeater.setDisabled(me.minDate &&am ...

The error message stating that an arrow function is expected after declaring this type parameter

Encountered an error when trying to start the project with yarn start: $ yarn start yarn run v1.22.17 $ run-s build exec $ babel src/ -d lib/ SyntaxError: .../src/App.js: Expected an arrow function after this type parameter declaration. (8:9) 6 | 7 ...

Google Maps displays grayscale overlays on the latest version update

Hello, I am facing a challenging issue with the Google Maps API. I have come across some similar threads discussing this problem, but unfortunately, they did not provide a solution that suits my specific case. Currently, I am working on an angular.js 1. ...

Continuously receive data from a reactive socket

My current approach involves using this code to receive data from sockets: socket.on('send_image', (message) => { setImage(message.image) console.log(message) }) The server is constantly sending data (images from camera ...

What is the process for assigning custom constructor parameters to an Angular Service during its creation in an Angular Component?

I have been tasked with converting a Typescript class into an Angular 6 service: export class TestClass { customParam1; customParam2; constructor(customParam1, custom1Param2) { this.customParam1 = customParam1; this.customPara ...

angular-cli: Select templates based on the current environment

Currently, I am utilizing @angular/cli: 1.0.0 and aiming to utilize component templates based on the environment. The code implementation is as follows: import {Component} from '@angular/core'; import {environment} from '../environments/env ...

Which specific file name patterns does npm publish consistently exclude?

When using the npm publish command, the documentation mentions that certain files will not be included in the package unless explicitly added to the "files" list in package.json or un-ignored with a specific rule. What exactly are these "certain patterns"? ...

Explore a Variety of Albums with our Bootstrap LightBox Gallery

I'd like to incorporate this code into my gallery website, but I'm encountering a couple of issues. Firstly, when one album's slides finish, I want it to loop back to the first image. Additionally, there seems to be an intermittent problem w ...

Encounter an issue while attempting to generate a multidimensional array in JQuery

I am trying to utilize jQuery to create a multi-dimensional array. Below is the code snippet I have written for reference: GiftData = []; GiftData['boxProduct'] = []; GiftData['boxName'] = jQuery('#giftbox-data .box-data').te ...

Exploring Angular 2 Beta 8: An Introduction to @Query Usage

My attempt to utilize @Query to fetch data regarding an element in my template has not been successful. I made an effort using the following approach: Referenced here. Here is a snippet of my code, import {Component, Query, QueryList, ElementRef} from &a ...

What is the best way to transfer information to a different component using Vue router?

At the moment, I have a component that is displayed on the page. When I check the this.$router variable inside this component, I notice that the full path property is '/hello/reports?report=3849534583957' and the path property is '/hello/rep ...

Leveraging Regular Expressions for Matching Array Elements in Switch Cases

I'm currently developing a fun 'hangman' game for my wife's history course. As part of this project, I've constructed a class that generates the 'gameWord' in both string and array formats. As an additional feature withi ...

Show the predetermined information in the dropdown menu

Objective: I want the modal to display a dropdown list with preselected data based on the selected row. The dropdown list should show the user's month data, for example, if Josef's month value is 2, 'Feb' should be the first option di ...

Comparison between Static and Dynamic SVG

I have noticed a significant contrast in the rendering of static versus dynamic SVG. Take a look at this code snippet: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=devi ...

The function parseFloat in Javascript can be used to subtract two numbers, returning an integer value

Apologies for the inconvenience, but I could really use some assistance. I attempted to convert a string into a decimal and was successful, although I encountered an issue: number = document.getElementById("totalcost").innerHTML; //String that rep ...

Pass the specific index of an object located outside of a v-for loop in Vue 3

For educational purposes, I am working on building a basic shopping cart using Vue 3. So far, I have successfully set up the products object and implemented the addToCart() functionality. Everything is functioning smoothly within a v-for loop. However, t ...

having difficulty grasping the variable's scope within this code

Here we have a code snippet where the variable vid is initialized inside a function. The question arises on how this variable can be used outside the function, specifically in the context of vid.play(). How does the program know that vid was created usin ...