Is it possible to integrate a backbone model with Angular?

Below is an example of a Backbone post model:

var Post = Backbone.AssociatedModel.extend({
    urlRoot: ApiService.resolveRESTUrl('posts'),
    defaults: {
        age : 0,
        fname : "",
        lname : "",
        manager : null
    },
    relations:[
        {
            type:Backbone.One,
            key:'User',
            relatedModel: function(){ return $injector.get('UserModel') },
            collectionType: function(){return $injector.get('UserModel').Collection; }
        },
        {
            type:Backbone.Many,
            key:'Last3Comments',
            relatedModel:function(){ return $injector.get('CommentModel')  },
            collectionType:function(){ return $injector.get('CommentModel').Collection },
        }
    ],
    getTimeAgo:function() {},
    getPicture:function(size){
        return this.get('picture_url') ?
            ApiService.getImageResizeUrl(this.get('picture_url'),'w'+size+'xh'+size) :
            null;
    },
});

While loading posts, if any library using Angular watcher in the post array (binded with "="), I encounter the following error:

Error: [$rootScope:infdig] 10 $digest() iterations reached. Aborting! Watchers fired in the last 5 iterations: []

Additionally,

RangeError: Maximum call stack size exceeded at Array.toString (native)

I am monitoring posts in this manner:

$scope.posts=[];
$scope.$watch('posts', function(model) {
    console.log($scope.posts, model);
},true);
$scope.loadPosts=function(){
    if($scope.loading || $scope.disabled) return;

    $scope.loading=true;

    ApiService.request("posts/home",{page:$scope.page,limit:10}).success(function(data){
        $scope.loading=false;
        $scope.page++;
        if(data.error){
            alert('Error');
        } else {
            if(data.data.posts.length==0)
                $scope.disabled=true;
            $.each(data.data.posts,function(i,e){
               var post=new PostModel(e);

                $scope.posts.push(post);
            });
        }
    }).error(function(){
        alert('Error');
        $scope.loading=false;
    });
};

Any thoughts on how to resolve these errors?

Answer №1

After hours of troubleshooting, I finally found the solution by leveraging angular's watchCollection instead of using just watch. WatchCollection is specifically designed to monitor changes in arrays.

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

Ways to prevent horizontal scrolling in an image

Currently, I am working on a scrolling animation page that is optimized for mobile devices. One issue I am encountering is when an element is larger than the screen size, such as when an image is wider than the mobile device. In this scenario, the user can ...

Incorrect data retrieval from JSON object with JQUERY

I am working on a function that extracts data from a database on the server-side and assigns it as the value of a textbox on the client-side. The function is functioning correctly on the server-side, but on the client-side, when I use console.log to view t ...

How to eliminate duplicate items in an array using various criteria

I have an array arr that needs to be cleaned up by removing duplicate objects with the same e_display_id and e_type as P. In this scenario, only objects with status==='N' should be considered. Here is the input array arr: let arr = [ { e_type ...

What is the best way to update an object with the value retrieved from an Angular $resource call?

How can I update an object with the API response after saving it using $resource in AngularJS? I have a scenario where I am iterating through an array of objects and need to save one particular object, let's call it 'value', to a ReST API. ...

Unable to dynamically display an HTML5 video using JavaScript

I'm facing an issue with displaying videos in a modal dynamically. Here's the scenario: +------------+---------+ | Name | View | +------------+---------+ | 1.mp4 | X | | 2.mp4 | X | +------------+---------+ The X ...

Is the iCheck feature designed to block all parent click events?

I've developed an "interaction tracker" system that collects anonymous data on clicked page elements. By implementing an event listener for clicks on the body, I can track interactions with any element on my site successfully. However, interestingly ...

Capture element in Javascript with screenshot functionality

I've been trying to save an image on my local website, but most of the code examples I find are for C# and Java, which I am struggling to convert to JavaScript. Many of the examples I come across use libraries like Point and IO that are not available ...

Are Node environment variables persistent?

First Example: package.json Scripts "scripts": { "start": "node app.js", "test": "NODE_ENV=test mocha --reporter spec" }, Command to Run Test: if (process.env.NODE_ENV === "test") { cons ...

What is the best way to retrieve the date and time using the Open Weather API for a specific city

Currently, I am in the process of developing a weather application using React and integrating the Open Weather API. Additionally, I have incorporated an external library for weather icons. The functionality allows users to input a city name and receive t ...

Altering various HTML components with every swipe of SwiperJS

I am new to working with JavaScript and I have integrated a Swiper JS element into my HTML page. Here is the current code I am using: <head> <link rel="stylesheet" href="https://unpkg.com/swiper/swiper-bundle.min.css&quo ...

Why does findOneandReplace continue to throw an error stating: "Error: Atomic operators are not allowed in the replacement document"?

I am currently working on a Pokemon Team Builder application with a React front end and an Express back end using MongoDB for the database. After reviewing my TeamSchema, it seems that there are no atomic operators included. Take a look at my TeamSchema b ...

What could be causing this JavaScript code to run sluggishly in Internet Explorer despite its simple task of modifying a select list?

I am currently developing a multi-select list feature where users can select items and then rearrange them within the list by clicking either an "Up" or "Down" button. Below is a basic example I have created: <html> <head> <tit ...

From AngularJS to Spring Framework Controller

I'm relatively new to working with angularjs. Currently, I have a checkbox in one of my views <input id="{{fields[3].name}}" type="checkbox" value="{{fields[3].name}}" ng-checked="selection.indexOf(fields[3].name) > -1" ng-click="toggleSelecti ...

Issue with the page base and Jquery Ui tabs URL

Having an issue with jqueryui tabs. Here's the code I'm using: // jQuery Tabs $( "#tabs" ).tabs(); // Open correct tab based on URL hash var hash = window.location.hash; var index = $("#tabs a").index($('#link-'+hash.replace('#& ...

Nunjucks not loading the script when moving from one page to another

Currently, I am in the process of developing a website utilizing nunjucks and express. This website serves as a blog platform with content sourced from prismic. My goal is to load a script file for an active campaign form whenever a user navigates from a b ...

Exploring Next JS: Effectively altering SVG attributes and incorporating new elements

I have integrated SVGR to load an SVG as a component in my latest Next.js 13 application: import CvSvg from './../../public/image.svg' export default function Home() { return ( <div className="flex flex-col min-h-screen" ...

cancel the ongoing ajax request during a specific event

There seems to be an issue with the behavior of clicking on the .personalized class. When clicked, it does not display both #loading_personalized and #divPersonalized elements simultaneously. This results in the execution of an AJAX call even when the pr ...

Using a carousel component in Bootstrap

Just starting out with this, trying to customize Bootstrap to change slides automatically. I followed the documentation at https://getbootstrap.com/docs/4.3/components/carousel/ but for some reason, the slides aren't changing on an interval, even thou ...

Sign in with Google / External authentication service

Currently working on an AngularJS application that includes Google login functionality. To implement this feature, I found a useful guide at the following link: . Additionally, there is a script that is called when the page loads: <script type="text/j ...

The Angular component is failing to display the template

After following a tutorial on UI-Router () I have implemented the following states in my Angular application: angular .module('appRoutes', ["ui.router"]) .config(['$stateProvider', '$urlRouterProvider', function($sta ...