Is there a way to call and update an Angular controller's $scope from external sources?

function in controller:

$scope.updateData = function () {
            Words.fetch('update', $scope.randNum)
                .error(function (data) {
                    console.log('update error: ' + data.message);
                })
                .success(function (data) {
                    $scope.board = data.settings.board;
                    $scope.tray = data.tray;
                    $scope.scores = data.pointsPerLetter;
                    $scope.totalScore = data.score.total;
                    console.log('update: ' + $scope.tray);
                })
        }

and the service function:

angular.module('wordService', [])
    .factory('Words', function ($http) {
        var id;
        return {
            fetch: function (call, num) {
                id = num;
                return $http.get('http://xxxxx');
            },
            sendUpdate: function (call, data) {
                console.log('send update: ' + data)
                return $http.post('http://xxxxx' + call, data);
            }
        }
    });

Instead of using

ngAccess = angular.element(document.getElementById('ws')).scope();
to call ngAccess.updateData() or $scope.updateData

How can I incorporate this functionality within a service for easy access when needed, while still being able to update the scope from the controller? The current method is not compatible with browserify and does not have access to the scope yet.

Scenario: I want to click a button that triggers a function to update the scope. Note: The button is displayed on a canvas element. (shouldn't affect functionality as event listeners are still present).

Thank you in advance for your help!

Answer №1

Transfer the data object to the service and assign a reference to a controller scope variable...

Your factory could be structured as follows:

.factory('Words', function ($http) {
    var id;
    var results = {};

    var get = function (call, num) {
        id = num;
        return $http.get('http://xxxxx').then(function(response){
            results.board = response.data.settings.board;
            results.tray = response.data.tray;
            results.scores = response.data.pointsPerLetter;
            results.totalScore = response.data.score.total;
        };
    };

    var send = function (call, data) {
        console.log('send: ' + data)
        return $http.post('http://xxxxx' + call, data);
    };

    return {
        get: get,
        send: send,
        results: results
    }
});

Meanwhile, your controller might appear like this:

.controller(function($scope, Words){
    $scope.words = Words.results;
    $scope.init = function () {
        Words.get('init', $scope.randNum).then(function(){
            console.log($scope.words); // should log the desired data
        }, function(response){ console.log(response)});
    };
    
    $scope.init(); 
})

Note that I have refactored your factory slightly to implement the revealing module pattern for better organization and ease of use. This structure allows you to make internal calls to your functions as well as external ones.

Now, you can add a button anywhere in the application without direct prototypical inheritance from the controller's scope. For instance, this directive would trigger a call and update the results accordingly, reflecting changes in the controller scope variable:

.directive('update', function(Words){
    return function(scope) {
        scope.update = function(){
            Words.get('update', 'somevalue')
        }
    }
})

This directive can be placed in the view like so:

<button update ng-click="update()">Update</button>

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

Issue with Bootstrap side navbar not collapsing when clicked on a link

Currently, I'm working on creating a website for a friend. While I used to have some experience with coding in the past, it has been a while and I am a bit rusty. This time around, I decided to use bootstrap for the project. However, I'm struggli ...

Implementing Angular2 with conditional loading

One of the requirements for my project is to redirect users to the login page before loading the Angular2 application, without actually loading it. The project is built using angular2-quicksart. After minifying the Angular2 js file: <script> va ...

NextJS-PWA detected that the start_url was responsive, but it was not through a service worker

Recently, I incorporated next-pwa (npm link) into my workflow to streamline the service-worker setup process for building a PWA in NextJS. While most things have been smooth sailing, there's one persistent error (shown below) that continues to pop up ...

Strange symbols were stored in the database after saving the textarea value

After submitting a form, text entered into a text area is being saved to my database. However, in one instance, certain characters such as • are appearing in the field. For example: • Text When retrieving the data from the database using Jav ...

Storing information within a Express application using Postgres

Recently, I've been delving into the world of Express and experimenting with a program that allows users to create events and invite others. While I know about using join tables to retrieve data, I'm curious if there's a way to organize the ...

Please reset the form fields after the most recent edit

I've created a form that includes multiple select elements. When an option is selected, it activates the next select element and updates it with values using Ajax and PHP. However, I'm facing an issue where changing a previous option only resets ...

Unlocking the Secrets: Expert Methods to Obtain Assets through HttpClient in Angular

After researching similar inquiries, such as the response provided in this thread, it seems that downloading or reading files from the assets directory can be accomplished easily by utilizing the get method of the HttpClient. For instance, if I have a Down ...

Guide on waiting for AWS assumeRole before proceeding with defining the module

I'm currently working on a module that needs to export functions and variables, but before it can do that, it must switch user roles. Here is the code snippet I've come up with. What I need is for the anonymous async function to execute first, an ...

Looking for a way to assign the object value to ng-model within a select tag from an array of objects? Also, curious about how to easily implement filters on ng-options?

Here is the HTML code for creating a question template: <body ng-controller="myCtrl"> {{loadDataSubject('${subjectList}')}} {{loadDataTopic('${topicList}')}} <h1 class = "bg-success" style="color: red;text-align: ...

Issue with jQuery fadeTo() not working after appendTo() function completes

I am facing a problem with the code below that is meant to create a carousel effect for my website. The main issue I am encountering is that the original fadeTo() function does not actually fade the elements, but rather waits for the fade time to finish an ...

Express.js session management -- Ensuring sessions are created exclusively for authenticated users

I've implemented the express-session Node module to handle secure session cookies. // To ensure certain requests require an active session, this code sets up a secure session cookie app.use(expressSession({ secret: "wouldn'tyouliketoknow", ...

Bootstrap datetimepicker is not showing the calendar for selecting a date, making it impossible to choose a specific date

I am facing an issue with integrating the bootstrap datetimepicker with Datatables to filter the data based on selected dates. The problem is that only an input bar is displayed on the page, and there is no calendar or calendar symbol visible. I suspect it ...

How to show ngFor value from Angular in a separate tag

I have a list of companies that I want to display in the following format: <div class="col-md-4"> <select ngModel="selectedCompany" style="width:400px;"> <option *ngFor="let x of mycompanylist&q ...

Navigating with buttons in the Material UI Drawer

I have implemented a Material UI drawer with some modifications. The original code used buttons, but now I want to navigate to a new page when a button is clicked. For example, clicking on the 'INBOX' button should take me to a page '/new&ap ...

AngularJS doesn't cooperate well with square brackets in form field names

While using AngularJS for validation within a Symfony2 form, I encountered an issue with the naming of the form field generated by Symfony2 as "license[domain]". The validation process functions correctly; however, AngularJS struggles to handle the braces ...

Verify changes in the Cross Domain RSS feed by utilizing Ajax technology

I have a website where I am trying to automatically reload an RSS news feed from every 60 seconds if it has been updated. I attempted to use Ajax for this purpose, but I seem to be facing some issues: <script type="text/javascript" src="../js/jquery.a ...

Determine if a cell is editable within the `renderEditCell` function by using MUI

I am working with a MUI data grid that contains different cell types. I am currently seeking a way to implement user permission-based editing for cells in the grid. However, I only want the permission testing to occur when a user attempts to edit a cell, r ...

Error: Unable to apply filter on this.state.pokemon due to invalid function

My goal is to fetch data from the PokeAPI and iterate through the array of information that is returned. I begin by setting my state to an empty array, then proceed to make the API call and retrieve data from the response, adding it to my pokemon state. ...

A guide to selecting the dropdown item labeled as (Select All) using Python and Selenium

edit: Trying to submit parameters for a database-generated report on this page. Successfully modified the start date in the first field using send_keys(), but unable to click on "(Select All)" for fields 3 and onwards, except one. In order to access the h ...

Utilizing v-if and splice on users to select items from v-model

After following a tutorial, I have the code snippet below that I would like to enhance: <div style="margin-top: 10px;"> v-for="task in taskItems" :key="task.id" <q-icon :name="task.icon"/> <div ...