AngularJS $scope variable is not defined during page load

Experiencing difficulties retrieving service data to include in the variable's scope. Below is my controller code:

'use strict';
var app = angular.module('ezcms2App.controllers', []);

app.controller('NoticiaCtrl', ['$scope', 'NoticiasFactory', '$http',
function ($scope, NoticiasFactory, $http) {            

//Testing paging on a local array - it works $scope.makeTodos = function () { $scope.todos = []; for (var i = 1; i <= 20; i++) { $scope.todos.push({text: 'todo ' + i, done: false}); } //The following does not work, $scope.todos ends up being undefined /$scope.todos = NoticiasFactory.query(function (entries) { for (var i in entries) { $scope.todos.push(entries[i); } });/ };

$scope.makeTodos();

$scope.totalItems = $scope.todos.length;

$scope.filteredTodos = []
        , $scope.currentPage = 1
        , $scope.numPerPage = 10
        , $scope.maxSize = 5;



$scope.numPages = function () {
    return Math.ceil($scope.todos.length / $scope.numPerPage);
};

$scope.$watch('currentPage + numPerPage', function () {
    var begin = (($scope.currentPage - 1) * $scope.numPerPage)
            , end = begin + $scope.numPerPage;

    $scope.filteredTodos = $scope.todos.slice(begin, end);
});

}]);

I also attempted using http get but as it is not asynchronous, it also returns undefined

'use strict';
var app = angular.module('ezcms2App.controllers', []);

app.controller('NoticiaCtrl', ['$scope', 'NoticiasFactory', '$http',
function ($scope, NoticiasFactory, $http) {            

    $scope.makeTodos = function () {
        $http.get('http://localhost:9292/localhost:80/apiadmin/index.php/api/noticia').success(function (resp) {
            $scope.todos = resp.data;
        });

    };

    $scope.makeTodos();

    $scope.totalItems = $scope.todos.length;

    $scope.filteredTodos = []
            , $scope.currentPage = 1
            , $scope.numPerPage = 10
            , $scope.maxSize = 5;



    $scope.numPages = function () {
        return Math.ceil($scope.todos.length / $scope.numPerPage);
    };

    $scope.$watch('currentPage + numPerPage', function () {
        var begin = (($scope.currentPage - 1) * $scope.numPerPage)
                , end = begin + $scope.numPerPage;

        $scope.filteredTodos = $scope.todos.slice(begin, end);
    });


}]);

Answer №1

Issue Resolved: AngularJS Noticias Controller

'use strict';
var app = angular.module('ezcms2App.controllers', []);

app.controller('NoticiaCtrl', ['$scope', 'NoticiasFactory', '$http',
    function ($scope, NoticiasFactory, $http) {
        //$scope.noticias = NoticiasFactory.query();

        $scope.noticias = [];
        NoticiasFactory.query(function (entries) {
            $scope.noticias = entries;

            $scope.totalItems = $scope.noticias.length;

            $scope.filteredNoticias = []
                    , $scope.currentPage = 1
                    , $scope.numPerPage = 10
                    , $scope.maxSize = 5;

            $scope.numPages = function () {
                return Math.ceil($scope.noticias.length / $scope.numPerPage);
            };

            $scope.$watch('currentPage + numPerPage', function () {
                var begin = (($scope.currentPage - 1) * $scope.numPerPage)
                        , end = begin + $scope.numPerPage;

                $scope.filteredNoticias = $scope.noticias.slice(begin, end);
            });
        });

    }]);

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

Creative Solution for Nested Forms

I am currently facing a challenge with nested forms in my PHP project. I need to include a form for AJAX image upload within another form so that I can pass the file path to the main form. The example code snippet is provided below; <form> <f ...

Securing pathways and pages using NextJs

I recently completed a project where I implemented route protection for a website using the if and else statements, assigning each page a function withAuth(). However, I have concerns about whether this is the most effective method for securing routes in n ...

Tips for automatically updating a start and end page input field

In my project, I am working with a list of start and end page numbers using angularJS forms. One specific feature I want to implement is the automatic updating of start page values based on the previous end page. For example, if a user enters '4' ...

Performing CRUD operations with mongoose and express

My express app is currently being developed with mongoose, and the goal is to integrate it with React for the front end. In my customer controller, I have outlined some CRUD operations, but there are aspects of this approach that I find unsatisfactory. W ...

NextRouter does not have a property called "refresh"

Here is the provided code snippet: "use client"; import { useRouter } from "next/router"; import { useState } from "react"; export default function CreatePrompt() { const [title, setTitle] = useState(""); const ...

Verifying if a number is present in a textbox when inserting text (without using setTimeout)

I have an input field similar to the one shown below: <input type ="number" id="numberTxt" placeholder="Number Only"/> To ensure that the value entered is a number, I am using the following function with the keypress event: <script> ...

getting properties of an object using AngularJS factory

I'm facing a major roadblock with this issue. Everything is functioning well enough at the moment, but I'm struggling to retrieve the data from the factory in a non-JSON format. You can take a look at my partially functional plunker for more deta ...

How can AngularJS handle uploading multipart form data along with a file?

Although I am new to angular.js, I have a solid understanding of the fundamentals. My goal is to upload both a file and some form data as multipart form data. I've learned that this is not a built-in feature of angular, but third-party libraries can ...

Issue: The hydration process has failed due to a discrepancy between the initial UI and the server-rendered content when utilizing the Link element

Exploring Next.js, I stumbled upon the <Link/> component for page navigation. However, as I utilize the react-bootstrap library for my navbar, it offers a similar functionality with Nav.Link. Should I stick to using just Link or switch to Nav.Link? ...

Using v-bind to dynamically set styles in Vue.js

While utilizing v-bind:style to apply dynamic values, I encountered an issue where v-bind:style did not seem to work. However, in the console, I verified that v-bind:style was receiving the correct value (:style='{ color : red (or any other value) }&a ...

What is the best way to display the Edit and Delete buttons in a single column?

Currently, I am encountering a small issue. I am trying to display Edit and Delete Buttons in the same column but unfortunately, I am unable to achieve that. Let me provide you with my code. var dataTable; $(document).ready(function () { dataTa ...

My Discord bot seems to be malfunctioning and failing to send out

I am new to discord.js and I'm having trouble getting my bot to respond with a message when I send one on the server. The bot shows as online in Discord and "Logged in!" appears in the console when I run it, so client.on("ready") seems to be working f ...

In order to have a Node.js program run synchronously following a for loop

I am struggling with ensuring that the last console statement is executed only after all iterations of the for loop are completed. Currently, this console statement executes immediately once control enters the else statement. Any ideas on how to resolve ...

What is the best way to transfer an integer from my main application to a separate JavaScript file?

Currently, I am developing a complex code using React Bootstrap and focusing on creating a Dropdown list that fetches data from the backend database. <Dropdown> <Dropdown.Toggle variant="success" id="dropdown-basic"></D ...

Change the width of the webpage inside the iframe

I am working with an iframe that has a fixed width and height of 400px. I want to load a web page in the iframe, but I need to adjust the width of the source to fit my iframe perfectly. The height is not an issue as I can add a scrollbar if needed. Here ...

Is there a way for me to determine the quality of a video and learn how to adjust it?

(function(){ var url = "http://dash.edgesuite.net/envivio/Envivio-dash2/manifest.mpd"; var player = dashjs.MediaPlayer().create(); player.initialize(document.querySelector("#videoPlayer"), url, })(); var bitrates = player.getBitrateInfoListFor("vid ...

Dealing with an empty request.FILES using FileUploadParser in Django Rest Framework and Angular file upload technique

Uploading files in an angular view can sometimes be tricky, especially when using templates. The code snippet below shows how to upload multiple and single files using Angular File Upload library. Multiple <input type="file" name="file" nv-file-select= ...

What is the best way to manage a significant volume of "business" data or objects within my JavaScript project?

I specialize in working with AngularJs and have a factory that provides services related to buildings. I am managing a large number of buildings (around 50-60) with multiple properties and sub-properties associated with each one (approximately 15-20, some ...

Utilizing JSON data as a variable for handling in a Handlebars view within a Node.js/Express application

I am currently seeking a solution to display a view that includes a variable with data fetched from an API. My technology stack involves express, handlebars, and request. Here is the code for the web server's router: const express = require('ex ...

I am puzzled as to why the Angulajs filter is not producing the desired results

I have created an AngularJS filter that relies on four user inputs. The Category and Author inputs come from dropdown lists, while one input is taken from a text field and the other from a radio button selection. I have implemented a button to clear all us ...