Using AngularJS to link a model referenced in the view (ng-bind) to a $resource obtained from an API

I'm currently facing a challenge in Angular where I need to establish a connection between a database object displayed in the html view and its corresponding instance through a json API.

While I have a functioning api and $resource, I am struggling to create a binding that allows updates made in the view to update the Angular model / $resource.

Specifically, my html view is prepopulated with data server-side and contains an ngBind attribute:

<div class="ng-scope" ng-app="Posts">
  <div class="ng-scope" ng_controller="PostsCtrl">
    <span contenteditable="true" ng-bind="post.1.text">post.1.text value</span>
  </div>
</div>

There are multiple instances of these on the page with unique ids. For demonstration purposes, let's consider this as a form text field without 'contenteditable' for now.

The format of the ng-bind attribute is flexible and can be adjusted as needed (e.g., post_1_text or split up entirely).

The structure of the resource factory, written in coffee script, is as follows:

app = angular.module 'Posts', ['ngResource']

app.factory 'Post', ($resource) ->
  $resource('/api/posts/:id', {id: '@id'})

app.controller "PostsCtrl", @PostsCtrl = ($scope, Post) ->
  $scope.posts = Post.query()

This successfully populates a collection of posts through the API.

My question is, how should the ng-bind attribute be structured to bind the controller and enable updates in the view to be reflected in the API?

(I understand that using ng_repeat: "post in posts" could simplify this, but for the sake of the example, assume I need to find an alternative solution.)

Thank you!

Edit: Here's a jsfiddle that illustrates the concept I'm trying to achieve:

http://jsfiddle.net/2QfVW/5/

...but I would like the id to bind to the object key 'id' instead of the index in the array.

Answer №1

Check out this modified version of your jsFiddle with three different variations for you to explore various methods.

I opted for the more straightforward syntax for binding. Using {{braces}} should make your code more readable.

Since your data is organized as an array, you'll need to reference it by the index within the array. In my revised version of your original code, I simply added the index, which may not be very helpful.

John goes by the name {{friends[0].name}} and has the id {{friends[0].id}}

In the following modification to your code, I introduced scope variables in the JavaScript file and assigned them the index values so that you can use those variable names in the view. This approach may not be the one you'll ultimately choose, but it provides you with some options.

Joy is known as {{friends[joy].name}} and has the id {{friends[joy].id}}

$scope.joy = 1;    // in the JavaScript

You will probably want to create a lookup function, which is the next enhancement you'll see. Here, I pass in the friend's ID that I want to find, loop through to find a match, and then return the entire friend object. In the view, I can then access any of the friend's properties. The '9' could also be replaced with a variable name.

Peter is represented by {{getFriend(9).name}} and has the ID {{getFriend(9).id}}

$scope.getFriend = function(fid) {

    angular.forEach($scope.friends, function(friend, key) {
        if (friend.id == fid) {
            found = friend;
        }
    });
    return found;
};

Does this explanation address your question? My initial response should clarify what's needed to update the model.

Answer №2

It seems like there may be some confusion in your question, so please provide more clarity if needed.

It appears that you may be missing an event to trigger your update. Can you explain how the user interface functions? Do users submit posts by clicking a button, or do you want automatic submission based on time intervals or changes? Clarifying the event or timer will help in implementing the model save in your controller. With Angular's two-way binding, you can easily reference $scope.post in your controller without needing ng-bind or ng-scope in your view.

I hope I have addressed your question correctly.

Sincerely, Darryl

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

By utilizing .focus() in iOS8, the virtual keyboard will be displayed and the page will automatically scroll upon touch

In the era before iOS8, when utilizing the Javascript .focus() method on an input element, it seemed as though nothing happened - the virtual keyboard did not make an appearance. However, with the latest iOS 8 update, executing the .focus() method initiall ...

Node.js: Module not found error

When I run the command below to install a module from the NPM registry: npm install dc All files are successfully installed, but upon running the script dc, it fails to resolve a dependency. $ node web-test.js module.js:340 throw err; ^ Error: ...

Troubleshooting Next.js 13: Issues with Error and Not Found Pages Rendering Incorrectly

I am currently working on a project with the latest version of Next.js, specifically Next.js 13, and I have organized my app directory structure accordingly. Within the app/sample directory, I have implemented custom error handling by creating pages named ...

What is the purpose of using $ symbols within NodeJS?

Lately, I've been attempting to grasp the ins and outs of using/installing NodeJS. Unfortunately, I'm feeling a bit lost due to tutorials like the one found here and their utilization of the mysterious $ symbol. Take for instance where it suggest ...

Adjusting the position of a stationary element when the page is unresponsive and scrolling

Managing a large web page with extensive JavaScript functionality can be challenging, especially when dealing with fixed position elements that update based on user scroll behavior. A common issue that arises is the noticeable jumping of these elements whe ...

Setting breakpoints in Node-Inspector can be quite challenging

After successfully setting up a web application, I decided it was time to learn how to properly debug it without relying on console.log. To start, I ran Node-Inspector via node-debug server.js (the main script file) and attempted to set up a breakpoint wit ...

Incorrectly modifying the _locals property while rendering a MySQL result in Express/Node.js leads to the error: "Cannot assign to read only property '_

I am currently using Handlebars to display data retrieved from a MySQL query. The route is set up as shown below: var query = "SELECT col1, col2, col3 FROM table WHERE section >= " + start + " AND section <= " + end + " ORDER BY col1 ASC"; connecti ...

Using AngularJS, you can display repeated elements in a single textarea by utilizing

--> I want to be able to input data into a textarea using just one textarea element. --> The reason for this is so that when the data in MySQL is updated, I can type new data in the textarea while still keeping the existing data. I have tried using ...

Is there a way to identify when a fresh google instant page appears?

I am currently developing a browser extension that requires making a call when a new Google instant page is loaded and then modifying the results, similar to SEOQuake. One problem I encountered is that if a user pastes a link directly into the URL field a ...

Retrieve the earliest and latest dates from a JSON file to utilize with FlatPicker

I have a file in an unknown format, possibly JSON, with dates listed. I am attempting to extract the minimum and maximum dates from this data in MM/DD/YYYY format for use as variables in Flatpicker's minDate and maxDate options. The current AJAX call ...

Turning a Two Dimensional Object or Associate Array into a Three Dimensional Object using Javascript

Is there a method to transform the following: var stateDat = { ME: ['Maine',1328361], etc. }; Into this structure dynamically within a function? var stateDatHistory = { 1:[ ME: ['Maine',1328361], etc. ], 2:[ ME: ['Maine& ...

I am looking to obtain assistance through denomongo for guidance

The deno-mongo guide page on GitHub is no longer functional. You can find the page here: 'https://github.com/manyuanrong/deno_mongo' I am struggling to understand how to use the plugin and get it up and running. Following the example in the "Re ...

For an unknown reason, I am facing difficulties in using the Storage feature from @angular/fire in ANGULAR 16

Recently I started exploring Angular/Fire and decided to test out some of its features by creating a basic app. Firestore and authentication were working smoothly, but when I attempted to include Storage, an error message popped up: ERROR FirebaseError: ...

Guide to displaying all files from firebase storage on a screen

I'm struggling to display all the files from my firebase storage. I've tried pushing them into an array, but I can only get one file name. Any ideas on how to push all the files into the fileName array? function Home() { const [fileURL, setFile ...

Is the file corrupt using node.js?

Looking for ways to determine if a file is corrupted using node.js? I have attempted various File System methods, such as fs.readFile, fs.open, and fs.access, but all of them are showing an OK status. However, I am confident that my file is corrupted base ...

How to retrieve data from the resolve function in an Angular 2 component

How can I access the resolved data in an Angular 2 migrated component? I have an Angular JS app.config set up with routing that loads the necessary Angular 2 migrated component. .state('users.list', { url: '/users/list', templ ...

Using Typescript/JSX to assign a class instance by reference

Looking to access an object's property by reference? See the code snippet below; class Point{ x:number; y:number; constructor(x,y) { this.x=x; this.y=y; } } const a = { first: new Point(8,9), second: new Point(10,12) }; let someBoo ...

Ensure that the heading cells in the table header (thead) are properly

Struggling with aligning the thead with the td in the tbody? I attempted adjusting the thead using display: table-header-group;, but discovered that padding doesn't work on 'table-header-group'. This led me to try adding padding-left to my t ...

Unable to forward to another page using NodeJS (Express)

After spending a considerable amount of time trying to find a solution, I finally managed to create a simple button click redirection using NodeJS and Express. However, when clicking on the "Next page" button in my index.html file, I encountered an error s ...

Pause the event listener temporarily and reattach it after specific actions have been completed

I am currently working on a React app that includes a scrollable div. Here is an example: <main id="main" onScroll={this.handleScroll}> My question is, how can I temporarily remove the onScroll event listener from the main element and then reattach ...