What is the correct way to assign a $scope variable after a successful ajax call?

Currently, I am working with Symfony and AngularJs 1.6.8 along with Symfony 3.4. Below is the configuration setup that I have:

base.html.twig

<html lang="en" data-ng-app="CeocApp" ng-controller="CeocController">
//css for the app
<link id="ng_load_plugins_before"/>
//more ccs for the app
<body>
....
<div class="row" ui-view></div>
....
<script src="{{ asset('assets/angular/angular/angular.min.js') }}" type="text/javascript"></script>
<script src="{{ asset('assets/angular/angular-sanitize/angular-sanitize.min.js') }}" type="text/javascript"></script>
<script src="{{ asset('assets/angular/angular-touch/angular-touch.min.js') }}" type="text/javascript"></script>
<script src="{{ asset('assets/angular/angular-ui-router/release/angular-ui-router.min.js') }}"
        type="text/javascript"></script>
<script src="{{ asset('assets/angular/oclazyload/dist/ocLazyLoad.min.js') }}" type="text/javascript"></script>
<script src="{{ asset('assets/angular/angular-ui-bootstrap/dist/ui-bootstrap-tpls.js') }}"
        type="text/javascript"></script>

<script src="{{ asset('assets/ceoc/angular_app/ceoc-angular-app.js') }}"></script>
</body>
</html>

ceoc-app.js

var CeocApp = angular.module('CeocApp', [
    'ui.router',
    "ui.bootstrap",
    "oc.lazyLoad",
    "ngSanitize"
]).config(['$interpolateProvider', function ($interpolateProvider) {
    $interpolateProvider.startSymbol('{[{').endSymbol('}]}');
}]);

CeocApp.config(['$stateProvider', '$urlRouterProvider', function ($stateProvider, $urlRouterProvider) {
    $urlRouterProvider.otherwise("/dashboard");

    $stateProvider
        .state('dashboard', {
            url: "/dashboard",
            templateUrl: "../templates/dashboard.html",
            controller: "DashboardController as dashboard",
            resolve: {
                deps: ['$ocLazyLoad', function ($ocLazyLoad) {
                    return $ocLazyLoad.load({
                        name: 'CeocApp',
                        insertBefore: '#ng_load_plugins_before', 
                        files: [
                            '../assets/ceoc/angular_app/controllers/dashboard-controller.js'
                        ]
                    });
                }]
            }
        })

}]);

Among other things, there are two problems encountered in the controller named `dashboard-controller.js`.

Problem 1:The usage of `$http.get(Rountin.generate('route_name'))` fails to work properly.

Upon running the application, everything functions correctly until reaching the mentioned `$http.get()` request.

angular.module('CeocApp').controller('DashboardController', ['$scope', '$rootScope', function ($scope, $rootScope, $http) {
    $rootScope.pageTitle = 'Dashboard';
    $scope.total = 2500;
    alert('this line will be reached');
    $http.get(Routing.generate('ceoc.dashboard')).then(function (data) {
        $scope.total = 10000 
    }, function (data) {
    });
    alert('this line will never be reached');
}]);

Problem 2: The inability to modify the `$scope` value using `$.get` method.

Although switching to `$.get()` solves the issue of making the AJAX request successfully, it does not allow the modification of `$scope.total` value.

angular.module('CeocApp').controller('DashboardController', ['$scope', '$rootScope', function ($scope, $rootScope, $http) {
    $rootScope.pageTitle = 'Dashboard';
    $scope.total = 2500;

    $.get(Routing.generate('ceoc.dashboard')).success(function (data) {
        alert('request successfull');
        $scope.total = 200; //this value won't be setted
    }).then(function () {
        $scope.total = 6000;
    });

$scope.total = '879';//this value will be setted
}]);

The provided server response

{"retrasadas":5,"total":10,"en_tiempo":5}

Thus, the main query regarding appropriately setting a `$scope.anyvar` value post a successful AJAX request remains. Does anyone recognize where the flaw lies?

I appreciate your assistance in advance.

Answer №1

Implementing Coec's handleAjax function along with its callback parameter:

Ceoc.handleAjax(Routing.generate('ceoc.dashboard'), "GET", function (data) {
  $scope.total = data.total;
  $scope.$apply();
});

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

What causes the HTML element's X position value to double when its X position is updated after the drag release event in Angular's CDK drag-drop feature?

I am facing a challenge with an HTML element that has dual roles: Automatically moving to the positive x-level whenever an Obsarbalve emits a new value. Moving manually to both positive and negative x-levels by dragging and dropping it. The manual drag a ...

Creating phony passwords effortlessly in JavaScript utilizing the informal library

I am trying to create a password that meets the following criteria: Minimum length: 7 Maximum length: 15 At least one uppercase letter At least one lowercase letter Special characters: ~ ! @ # $ % ^ * ( ) _ + ? I have been using the casual library for g ...

"Exploring the world of jest.doMock: A guide to mocking

Here is the code snippet I am testing: ... import data from '../data/mock.json'; // function is async export const something = async () => { try { ... if (!data) { throw 'error is here!'; } ...

Experience the convenience of uploading files with a simple drag and drop using

Is there a way to enable drag and drop file upload functionality using AJAX in Internet Explorer? It seems that IE does not currently support this feature, so I am looking for any possible solutions. ...

mastering the chrome api within your redux-saga workflow

Currently, I'm working on creating a 'get_current_url' function using redux-saga in my project involving a Chrome extension built with React.js. In order to obtain the current URI, I need to utilize the chrome.tabs.query API. Below is the sn ...

The server encountered a "Cannot GET /socket.io" error while trying

I am experiencing an issue with my app that uses express/socket.io. The app is running smoothly without any errors, but when I make an http-request, I receive the following error message: GET http://xxxxxxx.com:3035/socket.io/1/?t=1449090610579 400 (Bad R ...

Issues with rendering in-line styles in ReactJS after a state update

I'm currently working on implementing a basic state change for a button in React. 'use strict'; class ReactButton extends React.Component { constructor(props) { super(props); this.state = {hovering: false}; } onClick() { ...

Struggling with setting up a search bar for infinite scrolling content

After dedicating a significant amount of time to solving the puzzle of integrating infinite scroll with a search bar in Angular, I encountered an issue. I am currently using Angular 9 and ngx-infinite-scroll for achieving infinity scrolling functionality. ...

A guide to retrieving information from PHP using jQuery AJAX

I am a beginner in the realm of ajax, but my enthusiasm to learn is unwavering. I recently established a form using Formidable Pro that submits data via ajax. Within the submit button, I have incorporated an onclick function: <div class="frm_submit"> ...

Obtain date and currency formatting preferences

How can I retrieve the user's preferences for date and currency formats using JavaScript? ...

Setting compilerOptions.isCustomElement for VueJS 3 in a Laravel project: A step-by-step guide

I am currently working on integrating VueJS 3 into a Laravel project and utilizing a JS file to implement a markdown toolbar. The JS file contains functions that generate buttons for applying various markdown options. Everything is functioning properly, bu ...

Incorporate a directive dynamically within a separate directive

Introducing the table-div directive, which is responsible for rendering both the header and body of a table. Each row within tbody has the option to incorporate additional functionality through a custom directive that can display data linked to its parent ...

Utilizing Angular 9 with Jest for unit testing: simulating a promise, checking for method invocation afterwards

I'm in need of assistance as I am unsure how to mock a promise and verify that a method is called within the then() block. When I click on the save button of my form, my code appears as follows: // File: myComponent.ts save() { const myObject = n ...

The synergy of Redux with scheduled tasks

In order to demonstrate the scenario, I have implemented a use-case using a </video> tag that triggers an action every ~250ms as the playhead moves. Despite not being well-versed in Flux/Redux, I am encountering some challenges: Is this method cons ...

React Higher Order Components (HOCs) are functioning correctly with certain components but not

I have encountered an issue where using a Higher Order Component (HOC) to bind an action to various types of elements, including SVG cells, results in unintended behavior. When I bind the onClick event handler normally, everything works fine, but when I ap ...

Tips on displaying updated data in angular.js with a delay after updating the data object

I am setting up an array of objects in angular.js by retrieving them from the http service. <ul class="order-list" ng-repeat="catalog in catalogs"> <li style="width:34%;" ng-show="{{catalog.ordered}}" ><span class="fa fa-m ...

Counting the elements on a page using Selenium and Node.js: A step-by-step guide

I've been experimenting with Selenium in Javascript using NodeJS and I'm trying to tally up some elements based on CSS selectors. So far, I've attempted a few methods: client.findElements(By.css(".some-class")).size(); However, I encounte ...

Issue: The system is unable to locate the module labeled './lib/binding/napi-v3/argon2.node'

After attempting to install bcrypt or argon2 with the command npm install --ignore-scripts --omit=dev, an error occurred: app-1 | node:internal/modules/cjs/loader:998 app-1 | throw err; app-1 | ^ app-1 | app-1 | Error: Cannot find modul ...

Issue with $scope.gridOptions.api.setRowData function not being effective

I am currently working with ag-grid and facing an issue where I am unable to display data from a JSON file on the UI using the $scope.gridOptions.api.setRowData method. Currently, only the headers are being displayed but not the data itself. Below is the ...

Enhance your WordPress site by implementing infinite scroll with AJAX to seamlessly load more posts

Currently, I have implemented a feature that loads more posts through AJAX when the user clicks on a 'load more' button. The code I utilized is based on a tutorial found at this link. My goal now is to enhance this functionality so that instead ...