What is the best approach for invoking two services using a single provider factory?

Welcome! I'm having a little trouble setting up a discussion platform where users can post and comment. I've created two REST services for this purpose, but it seems like the commenting functionality is not working as expected. Could anyone help me identify where the issue lies or suggest a better approach?

Quick note: I'm new to AngularJS and would really appreciate your assistance with this for my app. Thank you in advance!

controller.js

            'use strict';

            /* Controllers */
            angular.module('myApp.controllers', []).
                    controller('MyCtrl1', function($scope, Customers) {
                        $scope.allcustomers = Customers.query();
                    }).
                    controller('MyCtrl2', ['$scope', 'comments', '$location',
                        function($scope, comments, $location) {

                            /* callback for ng-click 'createUser': */
                            $scope.createComment = function() {
                                comments.create($scope.PComment)
                                $scope.allcomments.push($scope.PComment);
                                $scope.PComment = "";
                                $location.path('/view2');

                                $scope.allcomments = PComment.query();

                            };
                        }

                    ]).
                    controller('MyCtrl3', ['$scope', 'postmain', '$location',
                        function($scope, postmain, $location) {

                            /* callback for ng-click 'createUser': */
                            $scope.createPost = function() {
                                postmain.create($scope.PPostMain)
                                $scope.allposts.push($scope.PPostMain);
                                $scope.PPostMain = "";
                                $location.path('/view2');
                            }

                            $scope.allposts = postmain.query();
                        }]);

services.js

            'use strict';

            /* Services */
            angular.module('myApp.services', ['ngResource'], function($provide) {
                $provide.factory('postmain', function($resource) {
                    return $resource('http://localhost:8080/pingleMe/webresources/postmain', {}, {
                        query: {method: 'GET', isArray: true},
                        create: {method: 'POST'} 
                    });
                });

                $provide.factory('comments', function($resource) {
                    return $resource('http://localhost:8080/pingleMe/webresources/comments', {}, {
                        query: {
                            method: 'GET',
                            isArray: true
                        },
                        create: {method: 'POST'}
                    });
                });

            //
            //    $provide.factory('Comments', function($resource) {
            //        return $resource('http://localhost:8080/CustomerBack/webresources/comments', {}, {
            //            query: {
            //                method: 'GET',
            //                isArray: true
            //            },
            //            create: {method: 'POST'}
            //        });
            //    });
            });

app.js

            'use strict';


            // Declare app level module which depends on filters, and services
            angular.module('myApp', [
              'ngRoute',
              'myApp.filters',
              'myApp.services',
              'myApp.directives',
              'myApp.controllers'
            ]).
            config(['$routeProvider', function($routeProvider) {
              $routeProvider.when('/view1', {templateUrl: 'partials/partial1.html', controller: 'MyCtrl1'});
              $routeProvider.when('/view2', {templateUrl: 'partials/partial2.html', controller: 'MyCtrl2'});
              $routeProvider.when('/view2', {templateUrl: 'partials/partial2.html', controller: 'MyCtrl3'});

              $routeProvider.otherwise({redirectTo: '/view1'});
            }]);

partila2.html

            <div class="container">
                <h1>What's on your mind?</h1>

                <form novalidate="novalidate" class="form-horizontal">
                    <div class="control-group">
                        <div class="controls">                     
                            <textarea ng-model="PPostMain.postText" placeholder="whats in your mind" style='width:550px'></textarea>
                            <button ng-click='createPost()' class="btn btn-warning">Post</button>

                            <h4>Trending Posts</h4>

                            <p ng-repeat="post in allposts"> 
                                {{ post.postText}} <br>

                                <label ng-repeat="comnt in allcomments">{{comnt}}</label>
                                <textarea ng-model="PComment.commentText" placeholder="write comment" style='width:350px'></textarea>
                                <button ng-click='createComment()' class="btn btn-success">Comment</button>
                            </p>
                        </div>
                    </div>
                </form>
            </div>

index.html

            <!doctype html>
            <html lang="en" ng-app="myApp">
            <head>
              <meta charset="utf-8">
              <title>Pingle</title>
              <link rel="stylesheet" href="css/app.css"/>
              <link rel="stylesheet" href="app/lib/angular/i18n/twitter-bootstrap/css/bootstrap.css"/>
            </head>
            <body>
              <ul class="menu">
                <li><a href="#/view1">view1</a></li>
                <li><a href="#/view2">view2</a></li>
              </ul>

              <div ng-view></div>

              <!-- In production use:
              <script src="//ajax.googleapis.com/ajax/libs/angularjs/x.x.x/angular.min.js"></script>
              -->
              <script src="lib/angular/angular.js"></script>
              <script src="lib/angular/angular-resource.js"></script>
              <script src="lib/angular/angular-route.js"></script>
              <script src="js/app.js"></script>
              <script src="js/services.js"></script>
              <script src="js/controllers.js"></script>
              <script src="js/filters.js"></script>
              <script src="js/directives.js"></script>
              <script src="app/lib/angular/i18n/twitter-bootstrap/css/bootstrap.css"></script>

            </body>
            </html>

Answer №1

While I am still learning about angularjs, it seems logical to have a comment for each row.

Currently, there is only one Pcomment stored in the scope. Is the content of pcomment determined by the last row?

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

Retrieve the value within the $scope when making an HTTP get request, but ensure it is only called once the client code has

On the controller page Expense.js: $scope.getPagedDataAsync = function (pageSize, page) { $scope.largeLoad = todoService.initialize(); todoService.getDataAsync(); $scope.setPagingData($scope.largeLoad, page, pageSize) ...

Why is the AngularJS $http get callback not triggering when receiving status code 401?

Whenever I visit a products page, I trigger a specific service: app.factory('ProductService',['$http','$location',function($http,$location){ var factory = {}; factory.getAll = function(){ $http.get('/prod ...

I'm curious if anyone has experimented with implementing TypeScript enums within AngularJS HTML pages

During my Typescript project, I defined an enum like this: enum Action { None = 0, Registering = 1, Authenticating = 2 }; In the controller, I declared a property named action as follows: class AuthService implements IAuthService { action: number; ...

Injecting services differently in specific scenarios in AngularJS

I have a unique angular service called $superService that I utilize across many of my directives and controllers. However, there is one specific directive where I want to implement the following behavior: If another directive utilizes $superService in its ...

Trigger a function following a collection update in Angular Meteor

I am in the process of developing a multiplayer game, and I would like a specific function to be triggered once the first player updates an "isStarted" field in the collection. Within my controller code: angular.module('mcitygame').directive(&a ...

Executing a file upload using ng-click="upload('files')" within Selenium Webdriver

Is it possible to automate a file upload when the HTML code does not include an < input type='file' > instead, uses a link <a ng-click="upload('files')"> File Upload </a> Clicking this link opens a file selector f ...

Ways to determine if an expectation has not been met in Jasmine/Protractor

I am testing a page where server-side RSA keypair generation occurs after the page has completely loaded. This process takes between 5 to 20 seconds with my current setup, during which time the user must wait until the browser receives the keypair. Althou ...

Incompatible parameter type for the Angular keyvalue pipe: the argument does not match the assigned parameter type

I need to display the keys and values of a map in my HTML file by iterating over it. To achieve this, I utilized Angular's *ngfor with the keyvalue pipe. However, I encountered an error when using ngFor: The argument type Map<string, BarcodeInfo ...

What is the proper way to send a HTTP status code 409 (conflict) and a JSON response from a spring REST API when a duplicate email is detected while a user is registering

I have attempted a few solutions so far, including: Using the Response object, but I prefer to avoid utilizing the servlet API of JSP. Trying a solution that returns an HTML response with a status code, however, I need it to be JSON instead. Here is a ...

Storing paperclip attachments in a database using AngularJS within a Rails 4 application

I have a query regarding saving a photo into a database using AngularJS in Rails4. I have implemented the attachment setup using the paperclip gem. class User < ActiveRecord::Base devise :database_authenticatable, :registerable, :recoverable ...

Is there a way to alter a class using ng-class only when the form is deemed valid?

I am trying to implement a feature where an input field shows as required, but once the user enters text, it indicates that the input is valid by changing the border color from red to green. I am facing an issue with this line of code always returning fal ...

Utilizing Selenium in Python to Scrape AngularJS in Chrome's Headless Mode

Seeking advice on how to scrape information from a webpage built with angularjs. Encountering an issue where the target element is not received when crawling the page in "--headless" mode, but works fine without it. Curious about the differences between t ...

Refresh two angular-datatables

I'm facing a challenge when it comes to updating two datatables simultaneously on the same page. Here's how my HTML is structured: <table id="datatable1" ng-if="Ctrl.dtOptions1" datatable="" dt-options="Ctrl.dtOptions1" dt-column-defs="Ctrl. ...

Learn the best way to populate Google Map popup windows with multiple values and include a button to pass unique ID values

I'm facing an issue with my code. When I click on a marker, it should display "Madivala, 12.914494, 77.560381,car,as12" along with a button to pass ID values. Can someone help me figure out how to move forward? http://jsfiddle.net/cLADs/123/ <ht ...

Cross Domain Requests in Internet Explorer: Preflight not being sent

I have come across several similar discussions but none of the solutions provided have worked for me so far. Issue: In our current setup, we have three servers hosting our http-apis - two for testing and one for production. Lately, we have been deployin ...

Updating the value of a $scope variable located within an included template in AngularJS

My setup is quite simple as outlined below. The issue I'm facing is that out of the two variables I define within the $http success callback, only one is reflected in the UI. In this scenario, I am attempting to display progress when the controller l ...

Is there a way to prevent the Angular Material input counter from shifting from inside the input to outside when it loses focus?

After upgrading to the latest Angular Material Design version (1.0.0-rc4) from 0.11.4, I have encountered some issues with my forms. The problem arises when dealing with two inputs. Initially, the max-length counter is displayed inside the input before ei ...

Utilize JSON parsing with AngularJS

My current code processes json-formatted text within the javascript code, but I would like to read it from a json file instead. How can I modify my code to achieve this? Specifically, how can I assign the parsed data to the variable $scope.Items? app.co ...

Tips for setting limitations on a date picker's minimum and maximum values on an iPhone using JavaScript

I have encountered an issue with my JavaScript function that sets min and max values for the input type date. While it works perfectly on Android devices, I am facing a problem on iPhone where I am unable to restrict the calendar with the specified min and ...

Creating unit tests for a state that includes PreparedQueryOptions within Jasmine framework

Currently, I am in the process of writing a Jasmine test case for the state within Angular JS. The resolve section of my state looks something along these lines: resolve: { myResult: function () { var dfd = $q.defer(); ...