Exploring Angular Scope within a Typescript-based javascript function

My current setup involves Typescript with Angular combined with Breezejs.

class CounterController {
    count: number = 0;
    static $inject = ['$scope'];


    constructor($scope) {
        $scope.vm = this;
    }

    setCount14(): void {  
        this.count = 14; // works
    }

    getQuestions(): void {
        var manager = new breeze.EntityManager('/breeze/dbentities');
        var query = breeze.EntityQuery.from("Corporations").where("Name", "startsWith", "Zen");
        manager.executeQuery(query)
            .then(querySucceeded);

        function querySucceeded(data) {
            this.count= 1; // works not!
        }
    }
}

Is there a way to correctly access the count property in the querySucceeded function?

Edit: Is it possible to pass a typescript function to executeQuery(query).then ?

Solution: Pass Typescript function as a Javascript function

Then calling the scope.$apply() actually applies the bindings.

Answer №1

Try using (data) => { this.count = 1; } instead to ensure that "this" has the correct scope. Alternatively, you can also do:

var me = this;
function querySucceeded(data) {
  me.count= 1; // This will work!
} 

For example:

getQuestions(): void {
    var manager = new breeze.EntityManager('/breeze/dbentities');
    var query = breeze.EntityQuery.from("Corporations").where("Name", "startsWith", "Zen");
    manager.executeQuery(query)
        .then((data) => { this.count= 1; });
}

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

What factors contribute to the variations in results reported by Eslint on different machines?

We initially utilized tslint in our project but recently made the switch to eslint. When I execute the command "eslint \"packages/**/*.{ts,tsx}\"" on my personal Windows machine, it detects 1 error and 409 warnings. Surprising ...

Issue with webpack dev server not correctly generating output files to be included in index.html

Struggling to configure webpack and react with typescript without the complexity of CRA. The dev server isn't outputting files to index.html for viewing in the browser. I want to maintain a clean and simple structure, avoiding the multiple js scripts ...

RetrieveByUserIdentifier as a callback method (express)

Can you help me refactor the code below to use a callback function instead? I want to ensure that the Req and Res logic is handled separately. Userservice.js function getByUserId(req, res, next) { let userIDD = req.body.userID; User.findOne({ use ...

Provide a value for a secondary select option parameter

I need to retrieve the university ID for use in another select option, which will display my college list under a specific university from a MySQL database. However, I am struggling to find the right approach. I want to pass fetch.university_id as a parame ...

Refreshing an AJAX call automatically in Knockout JS

Greetings everyone! I'm currently working on setting up a simple setInterval function to automatically refresh my data every minute. The line that is giving me trouble is: setInterval(incidentViewModel.fetchdata,60000); I also attempted this: windo ...

How to access Bootstrap's modal initial data-* upon closing

When displaying a bootstrap modal, a convenient method to retrieve associated data is by using the following code snippet: $('#myModal').on('show.bs.modal', function (e) { var id = $(e.relatedTarget).data('id'); alert( ...

Can you identify the specific error type that occurs in the onError function of react-query's MutationCache when using Typescript

Can someone help me with identifying the type of error in react-query MutationCache onError function when using Typescript? I also need guidance on how to override the type so that I can access and use the fullMessage from the data. const queryClient = new ...

inject the HTML content into the <div> container

Snippet: https://jsfiddle.net/x9ghz1ko/ (Includes notes.) In my HTML file, there are two distinct sections: <section class="desktop_only"> and <section class="mobile_only">. The challenge lies in positioning a JavaScript sc ...

There seems to be an issue with the angular login feature using ui-router, as it is not able

Implementing a custom login module for my website as shown below: angular.module('caknow', [ 'ui.router', 'ngStorage', 'authentication', 'login' ]) .config(['$stateProvider', '$url ...

Unable to download essential dependencies using NPM

After cloning a repository for a MEAN stack application, the first step was to run npm install. The installation process resulted in: added 1580 packages from 1887 contributors and audited 15249 packages in 281.586s found 18 vulnerabilities (5 low, 12 mod ...

Updating an array within a service across different controllers in AngularJS

My goal is to create an array within a service that can be updated from different controllers. The purpose of this setup is to ensure that the array is accessible across all controllers. I need the ability to add new items to the array as well as delete ex ...

Ways to guide user after logging out

My Angular front end includes the following code in app.js to handle user logout: .when('/logout', { templateUrl: 'mysite/views/logout.html', resolve: { authenticated: ['djangoAuth', function(djangoAuth){ return ...

Discovering and tallying a particular term within a text via JavaScript - a guide

In my current project, I have extracted an XML response and converted it into readable text. Here is a snippet of the converted XML: let XMLText = '<?xml version="1.0" encoding="utf-8"?> <BlockList> <CommittedB ...

Encasing the app component with a context and encountering the issue: TypeError - (destructured parameter) does not have a defined value

My goal is to wrap all components under the app in a context to provide specific functionalities (as evidenced by my UserContext component). import React, { useState, createContext, useContext } from 'react' const Context = createContext(); exp ...

What is the best way to ensure synchronous function execution in Angular?

Consider the following scenario: ServiceA is accessed by two components with inputs. ComponentA contains a textArea while ComponentB has a toggle button. Whenever these components are changed, ServiceA.save() is triggered, which subsequently makes an HTTP ...

Implementing pagination for images offers a user-friendly browsing experience

My friend and I are in the process of creating a website that displays images from two directories in chronological order. The image name serves as a timestamp, and we generate a JSON object using PHP with the code below: <?php $files = array(); $dir ...

Incorporate MUX Player (Video) into Angular versions 14 or 15

Mux offers a video API service with its own player: MUX Player I am interested in integrating this npm package specifically into a component in Angular 14/15. The JavaScript should only be loaded when this particular component is rendered. Integration Th ...

Tips for disregarding single quotation marks in the validator.js function for checking alphanumeric characters

I am currently working on validating a string using express validator, specifically utilizing the isAlphanumeric function. However, I would like to include space, dash, and single quote as acceptable characters in the validation process. Below is the code ...

The react-select onChange event fails to render when passed with certain props

I recently started using the select-react library, which can be found at So far, I have successfully mapped options to individual items from my itemList. The dropdown registers the selected option, but my ultimate goal is for the bar chart to render the c ...

Show a dynamic highchart graph displaying linear data retrieved from the database

I am attempting to present data retrieved from a database in a linear highchart format. Here is the JSON response from my database: [{"protocol":"tcp","date":"01/02/20","time":"00:10:20","total":281}, {"protocol":"udp","date":"01/02/20","time":"00:10:30", ...