Update the ng-model using an Angular service

I am currently working on an Angular application that includes a textarea:

<textarea id="log_text_area" readonly>{{logger}}</textarea>

In addition, there is a Logger service designed to update this textarea.

angular.module('app').factory('Logger', [function(){
    var logger = {};

    //
    // Log writing function
    //
    logger.log = function(log_area, arguments){
        // Get the current date
        var date = new Date();
        // Initialize log message
        var message = '';

        // Iterate through the object and build log message
        for (var i = 0; i < arguments.length; i++) {
            message += arguments[i] + " ";
        }

        console.log(log_area);

        // Check if log area is defined
        if (log_area != undefined){
            // Create log value
            var value = "[" + date + "}] " + message + "\n";
            value += log_area;
            log_area = value;
        }
    };

    // Return logger object
    return logger;
}]);

Now, I want to update my textarea from the controller:

function MyController($scope, Logger) {     
    $scope.logger = '';

    Logger.log($scope.logger, 'Logs Logs Logs');
}

However, the textarea does not update as expected. Can someone guide me on how to update the textarea using an Angular service?

Thank you.

Answer №1

Make sure your log function is set to return only the text, then assign this returned value to a $scope property in your controller.

$scope.logger = Logger.Log('log, log log');

Alternatively, you can add $scope.$apply(); after calling the log() method, but the first approach is preferred for cleanliness.

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

Unlock the lightbox and send the user to the parent page

Is there a way to simultaneously launch a lightbox popup and redirect the parent page? I have an AJAX script that retrieves HTML content as a response. My goal is to display this content in a lightbox popup while also directing the parent window to a des ...

Is it possible to call componentDidMount() multiple times in React?

I am in the process of converting an HTML API to ReactJS. The original HTML API is as follows: <script src="//dapi.kakao.com/v2/maps/sdk.js?appkey=3199e8f198aff9d5aff73000faae6608"></script> <script> var mapContainer = document.getE ...

Creating a C# view model with jQuery integration

I am facing an issue with binding a list property of a view model using jQuery. The view model in question is as follows: public class ToolsAddViewModel { public string Tools_Name { get; set; } public string Tools_Desc { get; set; } ...

Protractor successfully opens Firefox, however no URL is loaded. Chrome, on the other hand, functions perfectly

Every time I attempt to execute my protractor tests on Firefox, the browser opens but no URL is loaded. Eventually, an error message appears in the command prompt: Using FirefoxDriver directly... [launcher] Running 1 instances of WebDriver ERROR - Unabl ...

What steps can I take to prevent my JavaScript code from interfering with my pre-established CSS styles?

I'm currently designing a mini-email platform that serves as a prototype rather than a fully functional application. The HTML file contains placeholder emails that have been styled to appear presentable. I've implemented an input bar and used Jav ...

Sinon.stub functions as expected in karma and mocha when using Chrome, however it encounters issues when running in head

In my current project with AngularJS, I have implemented a feature where scrolling on an element triggers the scrollTop() function to determine if another method needs to be executed. I created a sinon.stub for this purpose: scrollTopStub = sinon.stub($. ...

Display a preview of the uploaded image

Is there a way to separate the image previews when selecting a picture using a JavaScript code for input file image preview? function readURL(input) { if (input.files && input.files[0]) { var reader = new FileReader() reader.onload = f ...

Challenges encountered during the execution of React tests: Enzyme, Jest, and React integration

Encountered an error while running tests: FAIL src/components/common/user/UserMenu/__tests__/UserMenu.test.js ● Runtime Error Error: Failed to get mock metadata: /redacted-directory/node_modules/core-js/library/modules/_global.js See: http://facebook ...

Error message displayed: MUI Textfield does not support input of decimal values

I have a textfield where users can enter the unit price const [unitPrice, setUnitPrice] = useState(0); <TextField label="Unit Price" variant="outlined" margin="normal" value={unitPrice.toString ...

Exploring the Dynamic Display of Nested JSON Objects in Angular 6

Struggling with a complex issue and feeling lost on how to approach it. I'm currently working with Angular 6. The challenge at hand involves handling JSON data in my project. While accessing simple data like "id" or "certificate" is easy, I'm en ...

Ensure your TypeScript class includes functionality to throw an error if the constructor parameter is passed as undefined

My class has multiple parameters, and a simplified version is displayed below: class data { ID: string; desp: string; constructor(con_ID:string,con_desp:string){ this.ID = con_ID; this.desp = con_desp; } } When I retrieve ...

The compatibility between Typescript methods and event handlers is lacking

Consider this basic TypeScript script class foo { v: number = 1; public bar() { console.log(this.v); } } var a = new foo(); var b = new foo(); document.getElementById('test').addEventListener("click", a.bar); document.getE ...

The React application is functioning properly; however, during compilation, it continually displays an error stating that the module cannot be found

Compilation Failed. Error: Module not found, unable to resolve the specified path. webpack compiled with 1 error I was hoping for a successful compilation, but unfortunately encountered an error. It's perplexing as the application is functioning co ...

What is the recommended approach for conducting backend validation?

As I develop a CRUD application using express.js and node.js, here is the backend API code that I have written: app.post("/signup", (req, res) => { const { name, email, password } = req.body; if (!name) { res.status(401).json("Please provide a n ...

What is the best way to handle responses in axios when dealing with APIs that stream data using Server-Sent Events (S

Environment: web browser, javascript. I am looking to utilize the post method to interact with a Server-Send Events (SSE) API such as: curl https://api.openai.com/v1/completions \ -H "Content-Type: application/json" \ -H ...

How can I arrange an array of strings with dates in C# or use ordering functionality in AngularJS?

I've got an array of dates in the following format: string[] arr=["08.02.2017","09.02.2017","30.01.2017","31.01.2017"] What is the most efficient method to sort this array in C# so that the order is descending? I want the data to be displayed within ...

An easy way to divide an array into a table

I've obtained these arrays from a JSON file "Works": [ {"TypeOfWork": "scaffolding", "Status": "done"}, {"TypeOfWork": "painting", "Status": "on-going"} ] My go ...

Enhance the Header component by incorporating a logout button that seamlessly navigates with the NextJS App

Currently, I am utilizing NextJS 14 with App router alongside Spring Boot on the backend. Within my application, I have both public and private routes set up. For the private routes, users are required to log in through a designated login page. Upon succes ...

The Google Geo Charts fail to load when initiated by Ajax requests

My goal is to use ajax to load an external HTML page that includes the following code: <script type='text/javascript' src='https://www.google.com/jsapi'></script> <script type='text/javascript'> function ...

Exploring the differences between React state and CSS :hover in the context of a dropdown menu that is accessible to both desktop users (via mouse) and

I have come across a dilemma regarding a dropdown menu that needs to cater to both Desktop/PC users (with mouse) and Mobile devices (with touch). After considering my options, here are the proposed solutions: OPTION 1 One approach is to implement it usi ...