How can I incorporate a factory object into an Angular JS view?

As someone new to angular js, I am embarking on the task of creating a simple grid with pagination. Within my project, there is a factory object called Entities with a specific structure:

 //app module
 angular.module('project',['ngRoute','controllers', 'services'])
     .config(['$routeProvider', function($routeProvider){
         $routeProvider
             .when('/',{
                 controller:'ListCtrl',
                 templateUrl:'list.html'
             })
             .when('/edit/:id',{
                 controller:'EditCtrl',
                 templateUrl:'form.html'
             })
             .otherwise({
                 redirectTo:'/'
             })
     }]);

//controller
 angular.module('controllers',[])
     .controller('ListCtrl',['$scope','Entities',function($scope ,Entities){
         Entities.get(function(data){
             $scope.entityCaption='Projects';
             $scope.entities=data;

         });          
       }])

// services module
 angular.module('services', [])
     .value('dataConfigs',
            {
                fetchUrl:'../fetch.php',
                saveUrl:'../save.php',
                entityName:'projects'
            }
       )
     .factory('Entities', ['$http','$filter','dataConfigs', function($http,$filter,dataConfigs){
         return{
             pageNo:1,
             rows:2,
             sortBy:'id',
             sortOrder:'desc',
             get: function(callback){
                 $http({
                     url: dataConfigs.fetchUrl + '?method=grid&table='+dataConfigs.entityName+'&page='+this.pageNo+'&rows='+this.rows+'&sidx='+this.sortBy+'&sord='+this.sortOrder+'&format=assoc',
                     method: "POST"
                  }).success(function (data) {
                      callback(data);
                  });
             },
             getById:function(id,callback){
                 $http({
                     url: dataConfigs.fetchUrl + '?method=grid&table='+dataConfigs.entityName+'&where_id='+id+'&page=1&rows=1&sidx=id&sord=asc&format=assoc',
                     method: "POST"
                 }).success(function (data) {
                         if(data.records==1)
                             callback(data.rows[0]);
                         else
                             callback({});
                 });
             },
             prevPage:function(){
                this.pageNo--;
             },
             setPage:function(){
                //set pageNo to N
             },
             nextPage:function(){
                 this.pageNo++;
             }
         };
     }]);

I am seeking guidance on how to utilize the Entities factory object within the ListCtrl's list.html view, for example:

list.html

<div class="pagination pull-right">
        <ul>
            <li ng-class="{disabled: Entities.pageNo == 0}">
                <a href ng-click="Entities.prevPage();prePage()">« Prev</a>
            </li>
            <li ng-repeat="n in range(entities.total)" ng-class="{active: n == Entities.pageNo}" ng-click="Entities.setPage()">
                <a href ng-bind="n + 1">1</a>
            </li>
            <li ng-class="{disabled: Entities.pageNo == entities.total - 1}">
                <a href ng-click="Entities.nextPage()">Next »</a>
            </li>
        </ul>
    </div>

I'm unsure about the feasibility of this approach. Please provide insights on how to address this issue. My goal is to connect the pagination with the Entities object while ensuring that all pagination and sorting operations are performed server-side, allowing the object to retain page numbers and sort orders when switching between Edit and List views.

The server-side script provides information such as the number of records, pages, and rows for the current page, for instance:

{"page":"1","total":4,"records":"8","rows":[..]}

Another key aspect is to observe the values of pageNo, sortOrder, and sortBy attributes within the Entities object.

Answer №1

If you are attempting to access your factory from the HTML view, please be aware that this is not possible in AngularJS.

In order to access entities, you must bind them to the $scope in your controller. This will allow you to access the entities in your views through the $scope.

The $scope serves as a connection between the controller and the view in AngularJS. This approach is similar to MVVM in technologies like Silverlight or WPF in .NET.

To gain a deeper understanding of how AngularJS operates, we recommend reviewing this section of the documentation: http://docs.angularjs.org/guide/concepts

We hope this explanation proves helpful!

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

Tips on assigning a class to an HTML element that is dynamically inserted

Currently, I am utilizing the jQuery Mask Plugin v1.5.3 along with jquery-1.9.1.js In my code, there is a button as shown below: <input type="button" class="btn btn-success" id="add_employee" value="add employee" /> This button triggers the addit ...

Ways to initialize Nested Arrays in Angular applications

I have been experimenting with some code on Codepen. I am trying to load JSON data from a service and then use ng-repeat to display the arrays. The issue I'm facing is that while the first array loads successfully, the nested array "data.cities" is n ...

Can items be conveniently stored in an MVC Controller?

Forgive me if this question seems trivial, but I am curious about the functionality and best practices involved. If the HomeController has a list as a field and one user adds to it, will that user see the updated list or will it remain empty? Furthermore, ...

execute a series of asynchronous functions one after another

async function cancelUserSubscriptionHandler() { const unsubscribe = await fetch("/api/stripe-sessions/cancel-subscription", { method: "PATCH", body: JSON.stringify(), headers: { "Content-Type": "appli ...

Tips for effectively handling checkboxes created by ezMark:

Incorporating the ezMark library into my website with PHP, Smarty, and jQuery has been a challenging yet exciting task. On a particular webpage, I am faced with the need to disable certain checkboxes based on specific conditions. Moreover, there is a paren ...

Incorporate child routes within a React component

I've been attempting to include <route> in a component within a routers component, but it doesn't seem to be working. Can anyone provide some assistance? My login page currently has a form and I'd like to switch that out with routes. ...

Arrange images in a fluid manner around other images

Check out the website I'm currently working on: metroweb.tk I'm in the process of designing a website that mimics the Windows 8 metro UI. However, I've encountered an issue with larger app icons such as notes and clocks sticking out. Is the ...

"Attempting to dynamically include Components for SSR bundle in React can result in the error message 'Functions are invalid as a React child'. Be cautious of this

When working with my express route, I encountered an issue trying to pass a component for use in a render function that handles Server-Side Rendering (SSR). Express Route: import SettingsConnected from '../../../client/components/settings/settings-c ...

Problem with Angular-UI Bootstrap Tooltip

It seems like due to the current structure of the page, the tooltip functionality is not functioning properly. index.html <div class="main-navigation"> <div rt-tool-menus-"menus" selected="selectedMenus" tooltip="{{appController.displayName}} ...

Navigating with Plone and AngularJS路径

Hello, I'm currently diving into AngularJS and experimenting with building an AngularJS based Plone addon. One challenge I'm facing relates to routing. Let's say I have a Plone URL, like http://localhost/blah/my_page When a user clicks on ...

What steps can I take to address the issue of missing @angular/Core modules?

I am encountering an issue with running my Angular 2 project. Here's what I have tried: - Attempted to run the project using npm install and npm start, but it did not work - Cloned a quickstart from Github and replaced it with my src folder, only to ...

Creating string enums in NextJS with TypeScript

I am working on my nextjs application and I have a component with a prop that is a string. I decided to create an enum, so I attempted the following: enum Label { dermatology = 'Dermatologi', psychology = 'Psykologi', rheumatology = ...

The pushPage functionality in Onsen UI seems to be malfunctioning

I am currently utilizing onsen UI's ons splitter along with a side menu. Interestingly, I am encountering an issue where the nav.pushpage function does not seem to work within the googleloginfunction. Please take a look at the code provided below. H ...

Extract user's location using JavaScript and transfer it to PHP

My goal is to utilize JavaScript to retrieve the latitude and longitude, then compare it with the previous location, similar to how Facebook authenticates logins from different devices. To accomplish this, I have implemented 2 hidden fields which will capt ...

Instructions for utilizing lodash or JavaScript to apply a filter to an object

Received this object from the Server: var data = { test1: { documents: [] }, test2: { documents: [{ vId: 'sdfas23', TypeId: '81', isDeleted: false }], answer: true }, test3: { documents: ...

How to successfully implement an AJAX GET request in Express.js

Currently, I am utilizing node.js and Express.js on the backend and attempting to initiate a server call from the client using AJAX. In my implementation, the following POST request is functioning properly with AJAX: node.js/Express.js: app.post('/ ...

Can an FAQ accordion collapse the selected element when another element is clicked?

I recently started working on a FAQ accordion project from frontendmentor. The functionality works perfectly when clicking on a question to reveal the answer and clicking again to hide it. However, I am facing an issue where if I click on one question and ...

Control the line height in DataTables

Is there a way to adjust the line height for a tr using either DataTables settings or CSS? I've attempted different methods, but nothing seems to change the line-height. https://i.sstatic.net/GwFaD.png Table CSS ...

Extend the start day by one day for the checkout option on the Pikaday datepicker

Is there a way to automatically add 1 day to the checkout date when selecting a check-in date? For example, if today is November 8, 2017 and I select November 10 as the check-in date, can the checkout date automatically adjust to November 11? This is the ...

Tips on how to optimize form input mapping without losing focus on updates

I am facing an issue with a form that dynamically renders as a list of inputs. The code snippet looks like this: arrState.map((obj,index)=>{ return( <input type="text" value={obj} onChange{(e) => stateHandler(e,index)}<inpu ...