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

Issues encountered with AngularJS directive binding inner content not functioning as expected

I am currently developing a feature toggle directive, which requires a check to be performed in order to display content if the check is successful. I want the directive to replace itself with its content without creating a new child scope (so I'm try ...

Discovered an issue with AngularJS involving ng-show and ng-if?

Upon my investigation, I have identified multiple issues with angularjs: <div ng-show="['[]']">this should be displayed but it is not working as expected</div> <div ng-show="[]">this should be displayed but it is not working as ...

Angularjs and Angular (5) routing combo

I'm currently exploring the possibility of running angular alongside our existing angularjs application. Instead of immediately diving into the tedious process of transitioning to ngUpgrade, I wanted to attempt running them independently first. My ide ...

Guide: Implementing service utilization within a controller using Express and Typescript

This specific piece of TypeScript code is causing me some trouble. I'm attempting to utilize a service to retrieve data from a database, but unfortunately, I keep encountering the following error message: Cannot read property 'populationService&a ...

Is there a way to identify the items that have been removed and added in an array by comparing an old array to a new array

Consider the following scenario: oldArray = [ { id: 1, position: 'DEV OM'}, { id: 2, position: 'Senior Developer'}, ] newArray = [ { id: 2, position: 'Senior Developer'}, { id: 3, position: 'Junior Devel ...

The act of exporting an enum from a user-defined TypeScript path leads to the error message "Module not

I have set up a custom path as explained in this particular discussion. "baseUrl": ".", "paths": { "@library/*": [ "./src/myFolder/*" ], } Within this module, I am exporting an Enum. export enum EN ...

The error message "Property not found on type 'Product | Customer' in React Typescript" is indicating that the specified property does not exist on the

I am currently working on a React app using TypeScript where I need to manage data for Customers and Products. To enhance this functionality, I plan to create a form component that can be used for updating either a Customer or a Product. The idea is to pr ...

Using styled-components and typescript to override props

Currently, I am faced with the challenge of using a component that necessitates a specific property to be set. My goal is to style this component with the required property already defined, without having to manually specify it again during rendering. Howe ...

Use AngularJS to narrow down search results based on the current month of the year

I need to create a screen that displays accounts payable and allows users to filter each account by month. The default display should show the current month, with options to navigate to previous and next months. I'm working on this project using Symfo ...

Implementing express-openid-connect in a TypeScript project

Trying to incorporate the express-openid-connect library for authentication backend setup with a "simple configuration," an issue arises when attempting to access the oidc object from express.Request: app.get("/", (req: express.Request, res: express.Respon ...

The 'BaseResponse<IavailableParameters[]>' type does not contain the properties 'length', 'pop', etc, which are expected to be present in the 'IavailableParameters[]' type

After making a get call to my API and receiving a list of objects, I save that data to a property in my DataService for use across components. Here is the code snippet from my component that calls the service: getAvailableParameters() { this.verifi ...

What is the process for extracting Excel .xlsx information from a POST request body in an Express API?

I've created an Angular frontend application that sends an excel (.xlsx) file as form data in the request body to my Express endpoint. Take a look at the function from my Angular service file below: uploadOrder(workOrder: File) { const formData: For ...

Leveraging TypeScript with Angular components

Situation: On my website, I have a section called the "main page" where all available books are displayed. The "main page" is represented by the blue box in the image provided and serves as a key component on my site. Additionally, there is a separate co ...

The ng-view DIV in Angular JS 1.x mysteriously vanishes

Currently, I am working on a project that involves angularJS and ASP.NET in Visual Studio 2013. However, I have encountered a frustrating issue where my DIV node for ng-view is being replaced with an ng-view comment without any errors appearing while testi ...

Using Javascript to open a PDF in a new tab directly from a byte array

I am currently using AngularJS along with an HTTP resource to make a request to an external API. The response I am getting back is in the form of a byte array. My goal is to convert this byte array into a PDF and open it in a new window. So far, I have not ...

Node.js routing at the secondary level modifies the main directory path

In my current web project, I am incorporating both Angular JS and Node JS simultaneously. To handle routing in Angular JS, I have implemented the following code: app.config(function($routeProvider,$locationProvider) { $routeProvider .when("/expert/:exper ...

Tips on creating a unit test for validating errors with checkboxes in your code base

In a certain scenario, I need to display an error message when a user clicks on the Next button without agreeing to the terms. To achieve this, I am looking to write a unit test case using Jest and React Testing Library. How can I go about doing this? im ...

Creating applications with Angular2 and TypeScript is possible even without utilizing NPM for development

I've seen all the guides recommend installing npm, but I'm determined to find an alternative method. I found Angular2 files available here, however, none of them are in TypeScript code. What is the best course of action? Do I need Angular2.ts, ...

A guide on determining the return type of an overloaded function in TypeScript

Scenario Here is a ts file where I am attempting to include the type annotation GetTokenResponse to the function getToken. import { ConfigService } from '@nestjs/config'; import { google, GoogleApis } from 'googleapis'; import { AppCon ...

Implementing child components rendering in a React application using TypeScript

Just a little background information: I am attempting to build a carousel with pagination using ReactJS. Here is the code snippet I currently have: interface HTMLCarouselT { children: Array<JSX.Element> size: number; } const HTMLCarousel = ({ch ...