Retrieve the Directive function from the Controller

Struggling with AngularJs and Typescript while developing an app. I'm encountering issues accessing a method in a directive from the controller class. Added 'control:=,' to the directive's scope but it's resulting in an error.

The controller code:

import {DaypartingSegmentsContainer} from "lib/js/publisher/deal/objects/dayparting/dayparting.segments.container";
@Component({
    bindings: {
        deal: "="
    },
    controllerAs: "$ctrl",
    module: DealApp,
    require: {
        DealForm: '^form',
    },
    selector: 'deal-edit-dayparting',
    template: require('./templates/deal.edit.dayparting.html'),
})
@Inject(
    "$scope",
    "$q"
)
export class DealEditDaypartingCtrl extends SxControllerBase {

    public daypartingSegmentsContainer : DaypartingSegmentsContainer;

    constructor(protected $scope : ng.IScope,
                private $q : angular.IQService) {
        super($scope);
    }

    public $onInit() : void {
        let self : DealEditDaypartingCtrl = this;
        this.daypartingSegmentsContainer.getCommonTimes();
    }
}

The directive class is:

import {Inject, Directive} from "lib/js/angularjs/decorators/sx-forward";
import DealApp from "lib/js/publisher/deal/lib.deal.app";
import DealEditDaypartingCtrl from "lib/js/publisher/deal/edit/deal.edit.dayparting";
import "lib/js/publisher/deal/objects/dayparting/dayparting.jquery.factory";
import {DaypartingDayName} from "lib/js/publisher/deal/objects/dayparting/dayparting.day.name";

import {
    minutesToString,
    stringToMinutes
} from "lib/js/publisher/deal/objects/dayparting/dayparting.time.functions";

@Directive({
    selector: 'dayparting-segments-container',
    require: '^dealEditDayparting',
    replace: true,
    module: DealApp,
    scope: {
        dayName: '<',
        control: '=',
    },
    template: require('./templates/dayparting.segments.container.html'),
    controllerAs: '$ctrl',
    link: function(scope : any, element : any, attrs : any, daypartingCtrl : DealEditDaypartingCtrl) : void {
        scope.daypartingCtrl = daypartingCtrl;
        // Delete button watch
        scope.$watch(
            () => {
                return daypartingCtrl.deleteSegment;
            },
            (shouldDelete : boolean) => {
                if (shouldDelete === true) {
                    scope.$ctrl.onDelete();
                }
            }
        );
        // Calendar leave watch
        scope.$watch(
            () => {
                return daypartingCtrl.calendarLeave;
            },
            (calendarLeave : boolean) => {
                if (calendarLeave === true) {
                    scope.$ctrl.onCalendarMouseLeave();
                }
            }
        );
    },
})

@Inject('$scope', 'JQueryFactory' )

export class DaypartingSegmentsContainer {
  
    constructor(private $scope : any,
                private JQueryFactory : any) {
        this.tooltipIsOpen = false;
        this.jquery = JQueryFactory.get();
    }

    public getCommonTimes() : void {
        console.log("i am in getCommon times!!!")
    }
}

export default DaypartingSegmentsContainer;

Encountering a console error -

Cannot read property 'getCommonTimes' of undefined

Answer №1

I finally figured out the solution staring me in the face all along. After adding the following code snippet, everything is now working smoothly:

        scope.$watch(
            () => {
                return daypartingCtrl.daypartingOninit;
            },
            (daypartingOninit : boolean) => {
                if (daypartingOninit === true) {
                    scope.$ctrl.getCommonTimes();
                }
            }
        );

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

Adjust the property to be optional or required depending on the condition using a generic type

const controlConfig = >T extends 'input' | 'button'(config: Config<T>): Config<T> => config; interface Config<TYPE extends 'input' | 'button'> { type: TYPE; label: string; ...

Exploring the functionality of Karma with Angular NgRX effects combined with a timer

Below is a sample NgRX effect implementation: loadData$: Observable<any> = createEffect((): Observable<Action> => { return this.actions$.pipe( ofType(loadDataStarted), switchMap(() => { retu ...

Difficulty in updating the value of HTML Range element using Angular6 function

My goal is to retrieve the changing values from a series of HTML range sliders. This is how they are set up: <li *ngFor="let rgbVal of rgbVals; let i=index"> {{i}}: {{rgbVal}} <br> <div class="color-box" [style.back ...

Is there a way I can run certain code asynchronously before my service methods are invoked?

Having difficulty executing tasks before initializing my service and using its methods. The scenario is as follows: I am developing an application that communicates with 2 different backend systems via REST (to ensure future compatibility for client upgra ...

Confirming the validity of a certain attribute by referencing other attribute keys

I am looking to enhance the type-checking for the following object: interface Config { fields: Record<string, unknown>; table: { id: string }[]; } const config: Config = { fields: { id: {} }, table: [ { id: ' ...

What is the best way to establish personalized CSS styles specific to each subdomain?

I am in the process of establishing a multi-tenant application with a single instance and single database setup. The backend infrastructure is built using Ruby on Rails, while the frontend is handled by a separate AngularJS app integrated with a Rails fram ...

initiating angular and node individually but with integration between them

For testing purposes in production, I needed to separate my angular 1.x frontend client and node backend server code. Both the client and server use API functions provided by node, but they are running on different servers on my local machine. My node serv ...

How can I send a variable to a service using AngularJS?

I am currently working on developing an app for movie tracking, and I am fairly new to Angular. I am facing a challenge in passing a variable to this service. Instead of hardcoding the URL, I want it to be a variable. What is the best approach to achieve ...

Toggle the Editable Feature in AngularJS JSON Editor

Currently, I'm utilizing a library called ng-jsoneditor that is available on GitHub. I am attempting to switch the state of an element from being editable to being read-only. To indicate that an element should be read-only, I need to specify the onE ...

Storing information in an array based on a specific flag

Currently, I am developing an Angular application where I am dealing with a specific array that contains a flag named "checked". Based on the value of this flag, I need to perform certain manipulations. Here is a snippet of my sample data: const data = [{ ...

TypeScript does not automatically determine the type of a passed generic parameter

I am currently working on defining flexible types for my api responses, but I am struggling to find the right approach for type conversion using TypeScript 4.5.4. My goal is to parse the response and determine the type that will be used later in the code. ...

Is it possible to share data from one controller in a JS file to another JS file? (using AngularJS)

I need to create a table in JavaScript. In one of my JS files, I have a controller with JSON data containing properties like width, height, color, etc. In another JS file, I am building the actual table structure. Here is an example of my AngularJS file: ...

Is combining a string and a React element within the same array considered acceptable in the world of React?

Consider a scenario where you need to display data in the form of string[][]. Here is the code snippet: export interface IProps { correctAnswers: string[][]; } public render(): JSX.Element { return ( <div> {this.props.c ...

The <a> tag does not lead to a different webpage and cannot be clicked on

I have developed a web component that includes a method to generate a copyright string: '<p>Copyright © 2020 John Doe<a href="https://www.example.com">. Terms of Use</a></p>' After creating the string, I conver ...

Angular is facing difficulties in loading JSON data from Rails

Within my Rails backend, I have a method designed to retrieve data from the database and convert it into JSON: def index @airports = Airport.select('id,city,country') render status:200, json: { airports: @airports } end In addition, ...

Testing a Controller in Ionic Framework using Karma Unit Testing

I've hit a roadblock trying to understand why my Karma and Jasmine tests are failing for an Ionic Controller. I'm fairly new to Ionic, karma unit testing, and angularjs, so I'm struggling to identify the issue here. Can anyone help pinpoint ...

Utilizing various APIs with distinct Authentication headers concurrently within an Angular JS application

Hey there, I'm new to AngularJs and could really use some advice or help from you guys! I'm working on an app that allows users to login and check their current location in a building using the Cisco CMX server. This server calculates the user&a ...

Possessing a versatile legend element

I'm struggling to find any information on this topic, so I've come here for some insights. Is there a way to create a graph where certain series items are grouped under an 'Other' category and can be expanded upon clicking? For instanc ...

What is the best way to monitor updates made to a function that utilizes firestore's onSnapShot method?

I am currently working with the following function: public GetExercisePosts(user: User): ExercisePost[] { const exercisePosts = new Array<ExercisePost>(); firebase.firestore().collection('exercise-posts').where('created-by&apo ...

Setting setSelected to true in multiple ag-grids seems to only work for the final grid

Currently, I am using a for loop to iterate over an array and dynamically creating ag-grid based on its content. With the data available, I am preselecting certain rows in the ag-grid. For the gridReady method: onGridReady(event) { this.resultsArray ...