What is the process for retrieving isolated scope values from typescript directives within a typescript controller class?

As I work with a Typescript directive class and controller class, I am facing an issue. I need to set up a watch on an isolated scope variable within the Typescript controller class, but I seem to be unable to access these isolated scope variables. How can I properly achieve this?

Below is my directive class:

module MyNamespace.Directives {
  "use strict";
  export class MyDirective implements ng.IDirective {
    restrict = "E";
    replace = false;
    templateUrl = "/app/features/myDirective.html";
    scope = {
      showParameters: '=showParameters'
    };
    controller = MyController;

    link(scope: ng.IScope, element: ng.IAugmentedJQuery, attr: ng.IAttributes, controller: MyController): void {

    }

    static instance(): ng.IDirective {
        return new MyDirective();
    }
}
angular.module("myApp")
.directive("myDirective", MyDirective.instance)
.controller("MyController", ['myService', '$scope', (myService: MyNamespace.Services.IMyService, $scope: ng.IScope) => new MyController(myService, $scope)]);
}

And here is my controller class:

module MyNamespace.Controllers {
  export interface IMyController {

    loadItems(): void;
  }


  export class MyController implements IMyController {

    public items: any = [];
    public showParameters: boolean;
    static $inject = ['myService', '$scope'];

    constructor(
      private myService: Services.IMyService,
      private $scope: ng.IScope) {
      var vm = this;

      var a = this.showParameters;
      this.loadItems();

      this.$scope.$watch(() => this.showParameters, (oldValue: string, newValue: string) => {
        console.log("showParameters");
      });

      // Additional watches and methods go here...

    }

    public loadItems = (): void => {
      this.items = [
        { name: "Item 1", selected: false },
        { name: "Item 2", selected: true }
      ];
    }

    // Other methods for controller functionality...

  }

}

Answer №1

In order to implement a clean and organized code structure, we can define an interface for the isolated scope and then pass it into the controller:

// Define the custom scope interface
export interface IUwAuthorityScope extends ng.IScope
{
    showParameters: boolean;
}

// Define the controller interface
export interface IUwAuthorityController 
{
    loadFinancingType(): void;
}


export class UwAuthorityController implements IUwAuthorityController 
{
    // Here, we explicitly specify that the injected '$scope' parameter will adhere to our custom type - IUwAuthorityScope
    constructor(
        private userService: Services.IUserService,
        private $scope: IUwAuthorityScope) 
    {
        ... 
        // We can now monitor changes in the $scope based on our defined properties
        this.$scope.$watch("showParameters", showParms => {
            // Accessing specific $scope variables with full typing support
            if(this.$scope.showParameters === true) ...
        });
    }
 ...

Answer №2

After taking your suggestion into consideration, I continued to encounter the following error: Error: [$injector:unpr] Unknown provider: IUwAuthorityScopeProvider <- $scope

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

Expanding class structures - variety of types

Suppose I have an abstract class named Conditions, which is then extended by classes like BoolCondtions, TextConditions, and more. In addition, I am using an interface structured as follows: export interface ConditionModel {type: string; class: Conditions ...

"iOS users have reported that notifications from Firebase have mysteriously ceased to

Yesterday evening, I was experimenting with Push Notifications from Firebase on my iOS application and everything was functioning correctly. I successfully sent a notification from a Cloud Function to a specific FCM token. However, this morning, notificat ...

Utilize specific class designations to establish characteristics within a particular type

Imagine I have various event classes: class UserLoggedIn { ... } class UserLoggedOut { ... } Then there exists a class dedicated to handling these events: class UserEventsManager extends AnotherClass { onUserLoggedIn(event) { ... } onUserLoggedOut ...

Execute JavaScript code once all the AngularJS template directives are fully loaded

On my HTML page, I am utilizing AngularJS template directives. Here is an example of how it looks: <div class="row"> <div class="col-sm-12"> <div logo></div> <div login-card></div> ...

Change the timestamp 2017-09-12 00:00:00 to just 2017-09-12 with the help of Angularjs

When pulling data from the database, the date is showing up as 2017-09-12 00:00:00. How can I format it to only display as 2017-09-12? ...

Using TypeScript to replace a current data type

Looking for a solution to implement a wrapper above the $http service in an AngularJS project. The goal is to have request promises with an abort() method. Attempting to achieve this by creating the following function: function request(params:ng.IRequest ...

Exploring LocalStorage Monitoring in Vue.js 2

How can I stay informed about any changes in Banana.vue? I have tried using addEventListener, @watch but it doesn't seem to be working... The index.vue file is importing both Apple.vue and Banana.vue In Apple.vue: localStorage.setItem('fruit ...

I require assistance in comprehending async/await in order to ensure that the code will pause and wait for my http.get function to

I've been reading various articles and forums, both here and on Google, about using awaits and asyncs in my code. However, no matter where I place them, the code after my http.get call always executes first. The alert messages from the calling program ...

Converting Getters into JSON

I am working with a sequelize model named User that has a getter field: public get isExternalUser(): boolean { return this.externalLogins.length > 0; } After fetching the User from the database, I noticed in the debugger that the isExternalUser prop ...

Angular implementation of a reactive form including a child component

Upon inspection, I noticed that my father form component is displaying the values of nickName and name, but not the value of age. It seems that {{myFormFather.status}} does not recognize the component child. It's almost as if my child component is inv ...

Angular $resource request results in a 401 error during a PUT request if CSRF is not defined, while a GET request with CSRF defined results in a 404 error

Currently facing a challenge with updating a list. I am working with Rails and AngularJS. On the JavaScript side, I integrated jQueryUI for sortable feature along with Angular $resource to interact with and manipulate a text block in a specific order. Fo ...

What is the most effective way to move specific data from one page to another in Angular/Typescript?

Welcome to my Main Page! https://i.stack.imgur.com/m9ASF.png This is where I want to start my journey. https://i.stack.imgur.com/E8pAW.png My goal is to click the Last 1 Day button to redirect to another page with the date filter and ItemId values already ...

The Node.js express seems to be unable to fetch the css and js files

Sharing my main.ts file in which I am facing issues with linking my css and js files. view image import express from 'express'; import {Request,Response} from 'express'; import expressSession from 'express-session'; import pat ...

Typescript incompatibility causing errors with Vue components

I am encountering an issue while using typescript 2.8.3, ts-loader 3.5.0 (as I'm using webpack 2), and vue 2.5.16. The problem arises when attempting to define components in a Single File Component (SFC) like the code snippet below: <script lang=" ...

VSCode prioritizes importing files while disregarding any symbolic links in order to delve deeper into nested node

I'm encountering a problem with VSCode and TypeScript related to auto imports. Our application includes a service known as Manager, which relies on certain functions imported from a private npm package called Helpers. Both Manager and Helpers make us ...

Determine data type based on key of object within a Zod array

Trying to extract the type from a key within an array of objects using Zod presents some challenges, especially when the array is nested within another object. To illustrate the issue: const obj = z.object({ nestedArray: z.array(z.object({ valueIWant: z ...

I wish for the value of one input field to always mirror the value of another input field

There is a checkbox available for selecting the billing address to be the same as the mailing address. If the checkbox is checked, both values will remain the same, even if one of them is changed. Currently, I have successfully achieved copying the mailing ...

Updating from Angular version 12.0.4 to 12.1.0 results in a runtime error. As a temporary solution, we are reverting back to version 12.0

There is a related issue discussed here: Angular: TypeError: Cannot read property 'firstCreatePass' of null However, the problem in that case pertains to different Angular versions and the solution provided did not resolve my issue. The recurring ...

Using computed properties with Nuxt's `head` property can result in error messages being displayed

While utilizing Nuxt.js, I am using head() { } method to configure SEO metadata. However, when accessing computed properties within this method, Vetur displays the following message: Property 'domain' does not exist on type 'CombinedVueInst ...

Challenges arise when the $_POST method fails to return a defined index

Although there are similar questions, none have fully addressed my issue. The challenge is to send values via POST to the DB to check if a user exists. Despite using isset and a ternary operator to handle errors, I still encounter persistent PHP errors. I ...