Using TypeScript to access the value of the parent scope within a directive controller

I am facing an issue with my directive.

export class SigninFormDirective implements angular.IDirective {

        // setting up the directive
        restrict: string =  'AE';
        templateUrl: string = "/public/app/signin/views/directiveTemplates/signinForm.html";
        scope: Object = { formData: "=" };
        controller: Function = SigninDirectiveCtrl;
        controllerAs: string = "form";
        bindToController: boolean = true;

        constructor($http: angular.IHttpService, $q: angular.IQService) {                        

        }        

        static SignupFormFactory(): angular.IDirectiveFactory {

            const directive = ($http: angular.IHttpService, $q: angular.IQService) => {
                return new SigninFormDirective($http, $q);
            };
            directive.$inject = ['$http', '$q'];
            return directive;            
        }


    }  

I need to access the formData variable in the directive controller. This variable is passed from the parent controller.

 // defining the main controller`
    export class SigninCtrl implements interfaces.ISigninCtrl {

        formData: Object[];
        // assigning an IID for MainController
        static IID = "SigninCtrl";

        // defining the controller
        constructor(public $state : angular.ui.IState) {
            this.init();            
        }

        private init = () => {
            this.formData = [];
        }



    }

In the directive's controller, I have a method where I'm trying to access the formData:

 public submitForm($event: angular.IAngularEvent, email: string, password: string) {            
        var userService = this.userService;
        var utilityService = this.utilityService;            

        // form submission
        this.formWasSubmitted();

        if(typeof password === undefined) {
            return;
        } else {                               

            var deferred = this.$q.defer();
            userService.signin(email, password)
            .then(dataObject => {                    
                if(dataObject.data.status.short === "NOTACTIVATED") {                        
                    this.formData.push(dataObject);                        
                    deferred.resolve(dataObject);
                }                                               
            }, error => {
              deferred.reject(error);  
            })                
        }

    }

I am utilizing controllerAs - how can I access formData within the directive controller? I have set up the two-way binding, but I am unsure how to access it in the controller using controllerAs. Do I need to use $scope? Or is there another way to achieve this? Currently, I am encountering this error:

https://i.sstatic.net/hUtYh.png

Any assistance would be greatly appreciated. Thank you!

Answer №1

Apologies for the confusion earlier. I managed to figure it out eventually.

To access the formData variable that is passed to the directive from its parent controller, or any other variable passed to your TypeScript Directive controller, you simply need to use this.

For example:

this.formData

Make sure to declare and reference your variables within your class as per usual.

class MyDirectiveCtrl {
    myVar: type;
}

If you opt for using $scope, you can access the variable like this:

$scope.(controllerAlias).myVar

However, it's much simpler to just utilize this.

The issue I encountered stemmed from a forgotten console.log statement. Once I removed that, this.formData.push worked perfectly.

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

Adjusting the size of SVG elements using AngularJS

As someone just starting out with AngularJS, I'm currently working on a project involving SVG elements that have fixed width and height. Unfortunately, this is causing issues when it comes to creating a responsive graph application. Can anyone provide ...

Error: The post request was blocked due to cross-origin restrictions

This is my unique script /** * Created by caneraydin on 16.03.2016. */ /** * Created by caneraydin on 16.03.2016. */ /** * Created by caneraydin on 16.03.2016. */ /** * Created by caneraydin on 16.03.2016. */ var app=angular.module('todoApp ...

a common pattern used to substitute website links

I am trying to modify my code that creates HTML links from plain text. While it currently works well, I want to exclude any links that contain .png or .jpg extensions. Does anyone have suggestions on how to adjust the regular expression? var urlPattern ...

Implementing a loading spinner in Angular UI Grid

Can anyone please help me figure out how to display a basic loader while data is being loaded? I am currently using ng-grid-1.3.2 and have searched on Google for examples, but haven't found any yet. Any help would be greatly appreciated. Thanks! ...

Typescript controller inheritance leading to Error: $injector:unpr Unknown Provider due to minification

LATEST UPDATE: 2019/07/16 The issue I am facing is actually a result of misusing $inject. Instead of declaring it as private $inject in api-service.ts, it should have been public static $inject = [...]. During the minification process, explicit injection ...

Tips for creating an onClick event for a React Component that is passed as a prop to another component

I am currently in the process of creating a custom trigger component that can be passed down to another component. My goal is to implement a click event on this trigger component from the receiving component. If you'd like to see a live example, chec ...

MongoDB: Issue updating the 'role' field of a document

Recently, I've run into an issue where I am unable to update the 'role' of a specific document. The document in question is a 'user' object within the MEANjs User schema, and it has a pre-defined property for roles. Here is the sec ...

Uncovering the enum object value by passing a key in typescript/javascript

How can I retrieve the value of an enum object by passing the key in typescript? The switch case method works, but what if the enum object is too long? Is there a better way to achieve this? export enum AllGroup = { 'GROUP_AUS': 'A' &a ...

Sequelize error: An unknown column is encountered in the field list while including a model without specifying the `attributes` field

Utilizing Sequelize for executing MySQL queries in my codebase, I have meticulously defined Models and connected them with their associations. Creating a music playlist structure with: Artists who can have multiple songs. Playlists that contain multiple ...

Tips for unchecking a checkbox when another checkbox is checked in Angular

My table displays a list of deleted items. Users have the option to either recover the item or delete it permanently. I am seeking assistance in ensuring that only one checkbox is checked in a table row, and unchecking other checkboxes if the user tries t ...

Is there a way to deactivate the parent ng-click function?

My HTML code contains a structure with the ng-click attribute: <div ng-click="parent()"> <div ng-click="d"></div> </div> Is there a way to disable the outer ng-click="parent()" function when I click on ng-click="d"? ...

What is the process for creating a column layout using md-card?

Despite following the official demo, the content still appears in a row. I tried using layout="column" but it didn't work. You can check out the demo here. ...

Hit the punchDB endpoint and retrieve all documents, then return the resulting value

As a newcomer to JavaScript and pouchDB, I am encountering difficulties in fetching data from pouchDB This problem is common when trying to retrieve and process data db.allDocs({include_docs: true}).then(function (result) { console.log(result.rows); ...

Adding a simulated $state object to an angular unit test

I'm facing some challenges with Angular unit testing as I am not very proficient in it. Specifically, I am struggling to set up a simple unit test. Here is my Class: class CampaignController { constructor($state) { this.$state = $state; ...

Make sure to wait for the store to finish updating the data before accessing it. Utilize RxJS and Angular

Greetings! I am currently working with Angular and RxJS, and I'm trying to find a solution to wait for the store's data to be updated after an action is dispatched in order to perform some operations using that data. Below you can see a snippet o ...

Clicking on a hyperlink should navigate to a new tab without the need to refresh the current page

<a href="##webinar" onclick="location.reload();">goTOWebinarTab</a> The code above is used to navigate to a specific tab within the same page (angular tabs). It currently works well, but requires the page to be reloaded. Is there a way to achi ...

The findIndex() method will consistently return a value of -1 when used on an array

I am struggling to find a solution for the following problem. Instead of returning 1, the index is always -1 in this case. Can anyone assist me with this? let allRules = [{ruleName: "a"}, {ruleName: "b"}, {ruleName: "c"}] let name = "b" let index = allR ...

Ensuring validation for a single checked checkbox in AngularJS

I'm currently experiencing a challenge with checkboxes in my Angular project. Due to the requirements of the backend, each checkbox must have a unique name, but at least one of them needs to be checked before the form can be submitted. To address thi ...

Integrating a non-nullable static type into memoized components leads to a lint error - refer to the example provided for

Example 1: When defining a non-nullable someStaticProperty, a lint error will be thrown: import { NamedExoticComponent, memo } from "react"; type WithComponentId = { componentId: string }; type ScreenComponentStaticMembers = { someStaticProperty: str ...

Using Angular Bootstrap DualListbox to manage NgModel within an NgRepeat loop

In my current setup, I am utilizing the Angular Bootstrap DualListbox within an NgRepeat loop. However, I am encountering difficulties in getting the NgModel to function correctly as intended. To better illustrate my situation, I will provide a simplified ...