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

Creating an image from the contents of a div is necessary in order to visually

I am looking to develop a software that can: receive text input from the user and place it in a specific div allow users to adjust font, color, and size based on their preferences enable image uploads as background save all customizations and send them v ...

Incorporate CSS file into the head section or directly within the HTML section without the need for JavaScript

I'm facing an issue with adding a CSS file to my webpage using JavaScript code at the bottom of the page. When users disable JavaScript, the file cannot be added. Is there a way to include the CSS file in the page without relying on JavaScript? $(doc ...

When the caret triangle is upside down, it indicates that a drop-down menu is available even when the

I am facing an issue with a dropdown list where the triangle indicator is incorrectly displayed: https://i.stack.imgur.com/L4NBW.png Both images show that the arrows are in reverse direction, and I am struggling to identify the cause of this problem. He ...

Could you please ensure that the animation activates upon hovering over the "a" element?

Utilizing bootstrap, I have created the following code. I am looking to add functionality that triggers an animation upon mouseover of an img or a element, and stops the animation upon mouseleave. .progress-bar { animation: pr 2s infinite; } @keyfr ...

What is the best choice between .dot template and Angular for this situation?

Looking for some guidance on where to invest my time, rather than ready-to-use code. Curious about integrating Angular (1.4.3) features into an express (4) application that currently uses .doT templates. Is it possible to work with both .doT templates an ...

Unable to locate FFmpeg on the root server for Discord JS v13

After setting up my DiscordJS Bot on a new rootserver, I transferred all the files and launched the bot. Everything seemed to be working fine until I tried to run a command that involved the bot joining a voice channel and playing audio. At this point, an ...

The AJAX load event listener triggers prior to receiving a response from the server

When working on a script to upload images via AJAX, the process is as follows: a user selects an image using a form file input field. The form contains an onsubmit function that prevents the page from reloading after submission. Within this function, data ...

Utilizing Nested JSON for Stacked Highcharts Implementation

I've been researching extensively about nested json for Highcharts stacked percentage column, but I haven't been able to get the desired output. Below is the code that I have tried, but unfortunately it's not producing the expected result. ...

Having trouble importing the named export `{module}` from a non-ECMAScript module with TipTap and Nuxt?

I'm using TipTap with Nuxt and running into some issues that I can't seem to resolve. Despite following suggestions from the repository's issues, I keep encountering these specific errors: ERROR in /Volumes/Projects/nuxt/candy-hub-lerna/no ...

The organization of an AngularJS application and its $scope functionality

I'm having trouble getting everything connected properly. I have all the necessary pieces, but I can't seem to access the injected resources. When I try to reference them, they are all coming up as undefined. var app = angular.module('app&a ...

The AJAX request is producing duplicated and unforeseen results

My Ajax Call: <script type="text/javascript"> var dataString ={ "EmployeeNum" : 50}; var queryObject=""; var queryObjectLen=""; console.log("loading"); google.load('visualization', '1.0', {'packages':['corechart&ap ...

Switch out an item within a list of objects with a different item

I have a variable called this.rows that contains a collection of items. There is a real-time item being received from the server, which matches one of the items in the this.rows object collection. How can I replace an item with new values? Below is an ex ...

"Vue3 offers the ability to return a multi-layer object through the Provide-Inject

While implementing provide-inject in my personal project, I encountered an issue where the value returned by inject() was a RefImpl Object. This meant that I had to access the actual value using inject().value.value instead of just inject().value. Here is ...

Ways to access states from a Vuex store within a Vuetify list in VueJs

Here is a snippet from my Vue file: import store from '@/store' export default{ name: 'myList', data: () => ({ show: true, listContent: [{ name: '1', icon: 'pers ...

Enter information into the designated text field once you have selected the button

In my PHP/HTML form for user login, I have a password field where users can enter their password or click a button to generate a random one. Although I found some JavaScript code online for this feature, I'm having trouble getting it to work with my ...

Button halts the playback of numerous audio tracks simultaneously

I'm in the process of creating a Launchpad, where each row consists of 8 buttons/audio tracks and a stop button. My goal is for each stop button to halt all audio playing on that specific row when pressed—for instance, pressing Stop Button 1 would c ...

Is there a way to asynchronously load multiple textures in three.js using a callback function?

Bringing in a single texture with a callback is a simple task, for instance: var loader = new THREE.TextureLoader(); var texture1 = loader.load("https://i.imgur.com/UiTMJzv.png", process); //executed only once texture1 is loaded function process(){ } B ...

Can a string variable be passed as a file in a command line argument?

Running a command line child process to convert a local file to another format is something I need help with. Here's how it works: >myFileConversion localfile.txt convertedfile.bin This command will convert localfile.txt to the required format an ...

Discover the steps to retrieve a fresh array in PHP after utilizing sortable.js

Hi there! I am currently utilizing the sortable javascript feature found on Although the script is working perfectly fine for me, being a non-expert in javascript poses a challenge when it comes to generating the necessary code to retrieve an array in php ...

What is the best way to create dynamic .env files that can easily adapt to different environments instead of

Having multiple .env files (one for Vue and one for Laravel) with 'localhost' hard coded in them is causing accessibility issues from other computers on my network. It would be beneficial to have this set up dynamically, except for production. F ...