Notify AngularJS of changes to the model

My angular application structure is pretty straightforward. Here is a snippet of the HTML:

<body ng-app>
    <div class="content" ng-controller="LeaderboardCtrl">
        <div class="row" ng-repeat="fb_ranking in fb_rankings">
            <div class="rank cell">{{fb_ranking.rank}}</div>
            <div class="name cell">{{fb_ranking.name}}</div>
            <div class="score cell">{{fb_ranking.score}}</div>
        </div>
    </div>
</body>

And here is the accompanying JavaScript:

function change_data(){
    some_data[0].rank = 99;
    var sc = angular.element(document.getElementById('overlay')).scope;
    sc.$apply(function(){
        sc.fb_rankings = some_data;
    });
}

var some_data = [
    {rank: 1, name: 'Boink a doodledo', score: 3000},
    {rank: 2, name: 'Someone else', score: 300},
    {rank: 3, name: 'Donkey', score: 30},
    {rank: 4, name: 'Booger landon', score: 20},
];
    
function LeaderboardCtrl($scope){
    $scope.fb_rankings = some_data;
}

Initially, everything functions as expected upon loading. However, my aim is to update the model some_data programmatically, rather than in response to an event like a click. This is due to the fact that the data update is a result of intricate Flash and DOM interactions, ruling out the use of event-based directives like ng-click.

To achieve this, I have the change_data function which makes a property modification and then attempts to access the angular scope and use the $apply function. Unfortunately, when I execute change_data(), it fails with the following error message: TypeError: Object function (a,d){v... and so on.

I'm perplexed by what might be causing this issue and what the error signifies. I have created a jsfiddle with the code mentioned above: http://jsfiddle.net/w2Ahr/1/

Any insights or guidance would be greatly appreciated.

Answer №1

function update_data(){
    some_data[0].rank = 99;
    var scope = angular.element("#overlay").scope();
    scope.$apply(function(){
        scope.fb_rankings = some_data;
    });

It's important to note that directly changing the scope outside of Angular is not recommended practice. This should only be done for demonstration purposes, and any scope modifications should ideally be handled within your controller

Answer №2

When directly calling scope.$apply, it can lead to potential complications. To ensure a smoother operation, it is advisable to utilize a wrapper:

// Implement this method to prevent '$apply already in progress' errors
$scope.updateScope = function (fn) {
    var phase = this.$root.$$phase;
    if (phase === '$apply' || phase === '$digest') {
        if (fn && (typeof(fn) === 'function')) {
            fn();
        }
    } else {
        this.$apply(fn);
    }
};

Subsequently, execute:

sc.updateScope(function(){
    sc.fb_rankings = updated_data;
});

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

Exploring Angular JS: Discovering the mechanism behind the redirection from /index.html to /index#!/phones. Learn more in the description

Discover in this tutorial Upon navigating to /index.html, a redirect occurs to /index.html#!/phones and displays the phone list on the browser. I am curious about the configuration that directs /index.html to /index.html#!/phones. ...

Leveraging and utilizing TypeScript npm packages

My goal is to create shared code in TypeScript, package it as an npm package, and easily install it. I attempted to create an external library like this: export class Lib { constructor(){ } getData(){ console.log('getting data from l ...

Using React's useEffect to implement a mousedown event listener

I created a modal that automatically closes when the user clicks outside of it. method one - involves passing isModalOpened to update the state only if the modal is currently open. const [isModalOpened, toggleModal] = useState(false); const ref = useRef(n ...

What is the method for determining profit as a percentage?

I need some help with a basic question. I have two variables, 'a' and 'b'. Variable A represents the money I receive from a customer, while variable B represents the money I will pay to a carrier. For example, if I receive $1000 from a ...

Invoking a Jquery function through a GridView link

After attempting various methods for hours, I am throwing in the towel. It's possible that someone here might spot what I'm missing. I have a GridView containing a Delete button. Upon clicking on the ClientClick event, a javascript function is in ...

How can you make sure that mouse events pass through the KineticJS stage?

Is it possible to have a PanoJS3 component covering the entire screen with a KineticJS stage on top, but still allow touch events to pass through the KineticJS stage to what lies beneath? I want shapes on the stage or layer to receive the touch events, wh ...

Struggling with integrating API response formatting in React and updating state with the data

This is the content found in the file 'Search.js' import React, { Component } from 'react'; import * as BooksAPI from './BooksAPI' class Search extends Component{ constructor(props){ super(props); this.state={ ...

Enhanced approach to building with React and Express

Quick Summary: How can I set up a project using React on the front-end and Express on the back-end with just one package.json and node_modules folder? When starting a project that combines a React front-end and an Express back-end, my desired structure is ...

When an image is clicked, I am attempting to access data from a Sharepoint list

In my Sharepoint list, there are three columns: Image, Title, and Description. I am using ajax to retrieve the items from the list. The images can be successfully retrieved, but my goal is to display the title and description of the clicked image when an ...

Using Ajax to populate two dropdown menus by utilizing the selected value from a third dropdown menu

I have an HTML page that includes 3 drop-down boxes. Whenever I make a selection in one of the boxes, the chosen value is sent to the server, and the server should return the values for the other 2 drop-down boxes. How can I dynamically populate the other ...

Angular file upload component with customizable file size limits

I'm currently developing an upload file feature that will transmit the file via nodejs. However, I am encountering an issue related to file size. Whenever the file exceeds a few kilobytes, I encounter the following error: Error: request entity too la ...

Unraveling the mysteries of the Bootstrap carousel script

Hi everyone, I'm a newcomer to the world of JS and jQuery. Recently, while examining the code in carousel.js, I stumbled upon this particular line: this.cycle(true) The cycle function is structured like this: Carousel.prototype.cycle = function ...

Exploring the World of 3D Rotation with Three.js

I currently have 2 mesh objects - the Anchor and the Rod. The Anchor rotates around the z-axis, as shown in the image. The Rod is designed to only move backward and forwards. You can view the image here: . However, I am struggling to determine the matrix ...

Ways of retrieving Sveltekit session data in an endpoint

Is there a way to access a session in an endpoint using SvelteKit? I attempted the following with no success: import { get } from 'svelte/store'; import { getStores} from "$app/stores"; function getUser() { // <- execute this du ...

retrieving request headers using XMLHttpRequest

Is there a way for me to access my requestHeaders within the onload function? Any guidance on how to achieve this would be greatly appreciated. Many thanks! ...

What could be the reason behind the validation failure of this Javascript code?

After implementing your recommendation, this is my current status: <script> function tick() { const React.element = ( '<div><marquee behavior="scroll" bgcolor="lightyellow" loop="-1" width="100%"> <i> <font color ...

What is the best way to set an array as the value for an HTML form input?

I am attempting to set the value of an array to an input element in HTML. When I run the following code in my browser console, it works: let between0400am0800am = [1669352400000, 1669438800000]; document.getElementById("time400am800amEveryDay"). ...

What is the best method for resizing individual SVG elements using jQuery or JavaScript?

A unique effect on my webpage involves an SVG comprised of scattered squares that enlarge when the user scrolls past a specific point. However, there is a problem with the scaling process which results in a horizontal scroll bar appearing. This occurs beca ...

The specified file ngx-extended-pdf-viewer/assets/pdf.js cannot be found

I have integrated the ngx-extended-pdf-viewer package in my Angular application using npm to enable the display of PDF content. According to the setup instructions, I have added the following configuration in my angular.json file: "assets": [ ...

Error message: CORS policy prevents third-party scripts from running in Next.js

I am encountering an issue with implementing a script handling tool in my Next.js project. I followed the documentation on nextjs.org and utilized the worker (experimental) parameter to enhance the page's performance. However, I am facing a CORS polic ...