The element event does not trigger an update on the view

I am trying to display the caret position of my editor on a specific place on the website. I have created a directive and service to share variables between the controller and directive. Inside the directive, I have enabled events like "keyup", "mouseup", etc. These events trigger, the service gets updated with correct values, and the Angular controller sees that the value has changed but the view does not refresh.

I suspect that these events are not informing Angular to refresh the view. How can I accomplish this properly? Here is my code.

It's also worth noting that the directive called "EditorEvents" is placed in a different location. Both only have a common root (are not nested).

class EditorEvents {
    public link: (scope: IExpressionEditor, element: ng.IAugmentedJQuery, attrs: ng.IAttributes) => void;

    private service: DebugValuesService;

    constructor(text: string, service: DebugValuesService) {
        this.service = service;
        EditorEvents.prototype.link = (scope: IExpressionEditor, element: ng.IAugmentedJQuery, attrs: ng.IAttributes) => {
            element.val(text);
            element.on("input propertychange", (event: JQueryEventObject) => {
                console.log('INFO: expression changed, new value: ', element.val());
                this.setServiceValues(scope, element);
            });
            element.on("keyup", (event: JQueryEventObject) => {
                if (event.which >= 37 && event.which <= 40) {
                    console.log('INFO: caret changed, new value: ', EditorEvents.GetCaretPosition(<HTMLInputElement>element[0]));
                    this.setServiceValues(scope, element);
                }
            });
            element.on("mouseup", (evet: JQueryEventObject) => {
                console.log('INFO: caret changed, new value: ', EditorEvents.GetCaretPosition(<HTMLInputElement>element[0]));
                this.setServiceValues(scope, element);
            });
        };
    }

    private setServiceValues(scope: IExpressionEditor, element: ng.IAugmentedJQuery) {
        var cursor = EditorEvents.GetCaretPosition(<HTMLInputElement>element[0]);
        var text = element.val();
        this.service.SetCursorPosition(cursor);
        this.service.SetScriptLength(text.length);
        this.service.Text = text;
    }

    private static GetCaretPosition(element: HTMLInputElement): number {
        ...
    }

    public static Factory(text: string) {
        var directive = (service: DebugValuesService) => {
            return new EditorEvents(text, service);
        };

        directive['$inject'] = [];

        return directive;
    }
}

and associated with this controller service

class DebugModeController extends BaseController<IDebugObject> {
    constructor($scope: IDebugObject, service: DebugValuesService, $interval) {
        super($scope, "DebugModeController");

        $scope.IsDebugMode = () => Configuration.IsDebugMode;
        $scope.Service = service;
    }
}

The values should be visible here:

<div ng-controller="DebugModeController" class="debug-controller" ng-show="{{ IsDebugMode() }}">
    <input disabled="disabled" type="hidden" ng-model="Service.ScriptLength" />
    <input disabled="disabled" type="hidden" ng-model="Service.CursorPosition" />
    <table>
        <thead>
            <tr>
                <td>Name</td>
                <td>Value</td>
            </tr>
        </thead>
        <tbody>
            <tr>
                <td>Script length</td>
                <td>{{ Service.ScriptLength }}</td>
            </tr>
            <tr>
                <td>Cursor position</td>
                <td>{{ Service.CursorPosition }}</td>
            </tr>
        </tbody>
    </table>
</div>

Answer №1

It seems like this event is not triggering Angular to update the view. What is the correct way to achieve this? Below is an excerpt of my code:

To ensure Angular 1.x performs dirty checking, you should manually trigger a digest cycle like this:

element.on("mouseup", (event: JQueryEventObject) => {
  console.log('INFO: caret changed, new value: ', EditorEvents.GetCaretPosition(<HTMLInputElement>element[0]));

Modify it to include:

element.on("mouseup", (event: JQueryEventObject) => {
  console.log('INFO: caret changed, new value: ', EditorEvents.GetCaretPosition(<HTMLInputElement>element[0]));
  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

Exploring the TypeScript handbook: Utilizing rootDirs for Virtual Directories

Exploring the concept of Virtual Directories with rootDirs in the handbook, we find an interesting example demonstrating how modules can be imported from different source folders by combining multiple rootDirs. // File Structure src └── views ...

Filtering out specific properties in an array using Angular

I am facing an issue with my Angular filter when inputting text for a specific list. initialViewModel.users = [ {user: 'Nithin',phone: 'Azus', price: 13000}, {user: 'Saritha',phone: 'MotoG1',price: 12000}, {user: ...

Learn how to implement a search filter in Angular by utilizing the "| filter" directive in your controller with a specific text query

Can you help with this code challenge? jsfiddle.net/TTY4L/3/ I am attempting to create a filtering list, where if I enter a value like 'avi', the list should display as: Avi Ravi, I understand the logic to achieve this: {{['Avi',&a ...

Using a pseudo-element after to center CSS content

Although there are numerous posts discussing this topic, my situation is unique. In my case, I have a collection of colors represented by circles. When I click on a circle, I add content in the form of a check mark by including a class selector with an af ...

Implement a click event listener in React.js

How can I implement a callback function for button clicks in my TypeScript code? This is the code snippet: export enum PAYMENT_METHOD { online, offline, } interface Props { paymentMethod: PAYMENT_METHOD; togglePaymentMethod: (paymentMethod: PAYM ...

What could be causing the delay in loading http requests in Angular?

When attempting to update the array value, I am encountering an issue where it works inside the httpClient method but not outside of it. How can this be resolved in Angular 14? Here is a snippet from app.component.ts: ngOnInit(): void { this.httpC ...

The feature of Nuxt 3's tsconfig path seems to be malfunctioning when accessed from the

Take a look at my file structure below -shared --foo.ts -web-ui (nuxt project) --pages --index.vue --index.ts --tsconfig.json This is the tsconfig for my nuxt setup. { // https://v3.nuxtjs.org/concepts/typescript "exte ...

Transforming the data type of a variable

Recently, I decided to switch my file name from index.js to index.ts. Here's an example of the issue I'm facing: let response = "none" let condition = true if(condition){ response = {id: 123 , data: []} } console.log(response) Howev ...

What is the best way to generate a JSON output that contains the entire

The use of {foo|json} is effective for displaying only part of the $scope. Is there a way to pass the entire scope to the json filter? ...

Eliminate any blank spaces in the SELECT Angular application for IE-CSS

One issue I encountered is removing the default selected "SELECT" option from a select drop down on my webpage. Currently, I am using to remove it successfully in Chrome and Firefox browsers, but unfortunately IE does not respond to this method. I ha ...

When using ng-init, the select will not automatically set to a default value

I'm facing an issue with setting the default value for a drop-down using ng-options. Even though I am able to get the default value in the response, it is not getting set in the drop-down. In JavaScript: $scope.personalDetails = [ { ...

A guide on arranging the JSON array within an AngularJS controller

Can someone assist me with sorting the JSON list provided below in the controller and then displaying it in the view? The orderBy filter only sorts one level, but I need it to sort recursively for all children. Input: R2 -->S4 ------>T5 ------> ...

using node js to make an angular http get request

When working with MongoDB, I am able to query data and then send it as JSON to a specific URL. In the process of querying data from MongoDB router.get('fillSurvey/:ID', function (req, res) { Survey.findOne({_id:req.params.ID}, function ( ...

Can webpack effectively operate in both the frontend and backend environments?

According to the information provided on their website, packaging is defined as: webpack serves as a module bundler with its main purpose being to bundle JavaScript files for usage in a browser. Additionally, it has the ability to transform, bundle, or ...

Comparison Between JavaScript Cookie and AngularJS $cookiesIn this comparison,

Can you explain the difference between a cookie created using JavaScript and one created using angularjs $cookies? For example, when I create a cookie using JavaScript like this: document.cookie = "username=smith";, the cookie values are retained even whe ...

I am a beginner in the world of Typescript/Angular, and I have encountered a compiling error TS2339. It seems that even when the condition *ngIf="x.length > 0;" should be false, the

I'm currently enrolled in a Typescript/Angular course where I am learning about the implementation of "*ngIf". During one of the lessons, the instructor provided an example using an empty array to demonstrate how it fails the condition and results in ...

Saving the data received from an API in a dedicated service

I am working on storing an API response in a service so that it can be accessed across multiple views. Below is the function I have in my service. It works perfectly when called by my controller, but I want to run this API call only once and then store th ...

Text Separation Within a Singular JSON Object

Currently, I am offering my assistance as a volunteer to develop a fast AngularJS App for a non-profit organization. Although I have successfully set up Angular, the main issue I am encountering has to do with parsing JSON data. The JSON object that I am ...

Issue with AngularJS controller method not functioning properly when assigned to a Div

I am facing an issue with a login form and its controller. The login function is not triggering upon submitting the form for some reason. Here is the code snippet for the form within the larger view file: <div class="login-wrap" ng-controller="LoginCt ...

Display customizable template according to variable

The answer provided for the issue regarding dynamic template generation based on value instead of variable in this thread was really helpful. However, I'm facing challenges in getting it to work. Here's a simplified example: export class A { } ...