ES6 Class Directive for Angular 1.4

I am currently exploring the possibility of incorporating a directive from version 1.4 and adapting it to resemble a 1.5 component. By utilizing bindToController and controllerAs, I aim to integrate the controller within my directive rather than using a separate one. While I have successfully achieved this by exporting as a function, I am interested in experimenting with exporting as a class to determine any potential advantages. However, I am encountering a bindToController error with the following code snippet:

export default class recordingMenuComponent {
    constructor(RecordingCtrl) {
        'ngInject';
        this.restrict = 'E',
        this.scope = {},
        this.templateUrl = '/partials/media/recording/recording-menu.html',
        this.controller = RecordingCtrl,
        this.controllerAs = 'record',
        this.bindToController = {
            video: '='
      }
    }

    RecordingCtrl($log, $scope, $state, $timeout, RecordingService) {
      'ngInject';
      const record = this;
      Object.assign(record, {
        recentCalls: record.recentCalls,
        startRecording() {
            let video = {
                accountId: $scope.accountId,
                title: record.sipUrl
            };

            RecordingService
                .recordVideoConference(video, record.sipUrl, record.sipPin, 0)
                .then(result => {
                    video.id = result.id;
                    $timeout(() => $state.go('portal.video', {videoId: video.id}), 500);
                }, error => $log.error('Error starting the recording conference: ', error));
        },
        getRecentCalls() {
            RecordingService
                .recentVideoConferenceCalls()
                .then(result => {
                    record.recentCalls = result;
                }, error => $log.error('There was an error in retrieving recent calls: ', error));
        }
    });
}

  static recordingFactory() {
    recordingMenuComponent.instance = new recordingMenuComponent();
    return recordingMenuComponent.instance;
  }
}

Followed by the import statement:

import angular from 'angular'
import recordingMenuComponent from './recordingMenuComponent'

angular.module('recordingModule', [])
    .directive(recordingMenuComponent.name, recordingMenuComponent.recordingFactory);

A portion of the module details has been omitted for brevity as it is unrelated to the transformation of this directive into a component. It is worth noting that I am aiming to avoid using .controller() prior to .directive().

Upon attempting to implement this code, the following error message surfaces:

angular.js:9490 Error: [$compile:noctrl] Cannot bind to controller without directive 'recordingMenuComponent's controller

I am uncertain if I am on the right track or if there might be a more appropriate approach to take. Thank you for any guidance offered.

Answer №1

Consider converting RecordingCtrl into a class structure

const app = require('../app');

class RecordingCtrl {

    static $inject = ['$log', 'RecordingService'];
    constructor($log, recordingService) {
        this.$log = $log;
        this.recordingService = recordingService;
    }


    startRecording() {
        // . . .
    }

    recentCalls() {
        // . . . 
    }
}

// for ng15 component
const recordingMenu = {
     restrict: 'E',
     scope = {},
     templateUrl = '/partials/media/recording/recording-menu.html',
     controller = RecordingCtrl,
     controllerAs = 'record',
     bindToController = {
         video: '='
     }
}

app.component('recordingMenu', recordingMenu);

// or ng1.4 directive
function recordingMenu() {
    return {
        restrict: 'E',
        scope = {},
        templateUrl = '/partials/media/recording/recording-menu.html',
        controller = RecordingCtrl,
        controllerAs = 'record',
        bindToController = {
           video: '='
        }
     }
}

app.directive('recordingMenu', recordingMenu);

It may not be ideal to have a controller implemented as a class method.

This approach could result in two separate classes unless you opt to convert the Directive Definition Object factory into a simple function or a static method of your controller.

Answer №2

Although unconventional, I managed to make it functional through experimentation. Here is the workaround I used:

.directive(menuRecordingComponent.name, () => new menuRecordingComponent())

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

The ng-repeat track by function is not functioning as expected, displaying slow performance and continuing to create $$hashKey

In my code, I have an ng-repeat setup like this: ng-repeat="article in main[main.mode].primary | orderBy: main[main.mode].primary.filter.order track by article.url" The main[main.mode].primary array contains the data and the .filter.order string is used ...

When scrolling, dynamically change the background color by adding a class

I am looking to achieve a scroll effect where the color of the menu buttons changes. Perhaps by adding a class when scrolling and hitting the element? Each menu button and corresponding div has a unique ID. Can anyone suggest what JavaScript code I should ...

How come my button is initiating automatically instead of manually?

Working on developing an API using Angular 2 with the Janus media server has brought up an issue regarding the start button. When running Janus, the button initiates automatically instead of manually. The following function was implemented for this purpos ...

How can you show a green check mark next to an input field in AngularJS after inputting valid data?

I am diving into the world of AngularJS and Angular Material with my web application. As a beginner in AngularJS and Angular Material, I need some help. My current task is to display a green checkmark next to an input field only when valid data is entere ...

I must first log a variable using console.log, then execute a function on the same line, followed by logging the variable again

Essentially, I have a variable called c1 that is assigned a random hexadecimal value. After printing this to the console, I want to print another hex value without creating a new variable (because I'm feeling lazy). Instead, I intend to achieve this t ...

Is Aurelia-Fetch reliant on whatwg-fetch as a dependency in its codebase?

I am currently in the process of updating my Aurelia project from a beta version to the March version. One of the issues I encountered is: Cannot locate name 'Request'. Searching online led me to this problem on GitHub: https://github.com/au ...

Exploring the benefits of leveraging Express with SSL security features

I recently acquired a Comodo SSL certificate for setting up an SSL server with express. The certificates I have include: AddTrustExternalCARoot.crt COMODORSAAddTrustCA.crt COMODORSADomainValidationSecureServerCA.crt mysite.com.key mysite.com.csr mysite_co ...

Pull information from API and populate a dropdown menu in an Angular material select input

I am facing an issue with displaying data from an API in a mat select input field. I have tried to iterate over the data using a for loop but it is not working as expected. Can someone help me figure out how to properly populate the mat select input with d ...

Accessing a secured Azure AD CORS WebAPI with an AngularJS Single Page Application

After successfully implementing the SinglePageApp-DotNet example, I encountered a challenge when trying to make the single page application call a CORS enable web api. Both applications are secured by AAD and deployed to Azure websites, but I couldn't ...

Secure HyperText Transfer Protocol prevents JavaScript from executing

My website's HTTPS version is having trouble loading JavaScript. All scripts are hosted on the same server. I've attempted: <script type="text/javascript" src="https://server.tld/js/jquery.js"> <script type="text/javascript" src="//ser ...

The terminal does not recognize the nodemon command

My goal is to automate server reloads using nodemon. I have successfully installed it locally and set the start command as nodemon app.js with this code: "scripts": { "start": "nodemon app.js" } Initially, everything was running smoothly. However, ...

I'm noticing that the value in my array keeps changing, but I'm struggling to pinpoint where the change is coming from

Recently, I've come across an issue where a property within my array collection is changing unexpectedly. Here's a snippet of the code from my controller: $http({ method: 'GET', headers: globalData.httpHeader, params: { orderke ...

Is there a way for me to configure my website so that when a link is clicked, my PDF file will automatically open in Adobe

I've been facing an issue where I need my users to access a specific PDF file from a link on my website. Currently, the PDF opens in a separate tab next to my site, but ideally, I would like it to be forced to open in Adobe Reader directly. Is this ac ...

HTML animation effect on subpage with a URL modification [LATEST UPDATE]

Can you smoothly load a new subpage in the background, update the URL, and fade it in while an animation is playing on the previous page? Check out this example (jsFiddle) to see a simple animation: $(document).ready(function() { 'use strict&apo ...

Loading screen while all files and audio are being loaded

My JavaScript code is responsible for displaying and playing audio on my website. Unfortunately, the load time of the page is quite slow. To address this issue, I decided to follow a tutorial on installing a preloader, which can be found at . Although I ...

Experience seamless language translation with AngularJS

I'm just starting out with Angular JS and I'm curious to hear your thoughts on which translation library is the easiest to implement or most commonly used for translating websites with Angular JS. Appreciate any insights you can provide! ...

Reverse changes made to a massive object and then redo them

My current project requires the implementation of undo-redo functionality for a product. At the moment, I am managing a substantial Object retrieved from a MongoDB collection The structure is as follows: { cart:{ products:[ { name: " ...

When scrolling, numerous requests are sent to ajax - how can I consolidate them into a single request for lazy loading?

I encountered a problem where multiple Ajax requests are being sent when I try to call an Ajax function after scrolling. How can I resolve this issue? $(window).scroll(function(){ var element = $('.MainChatList'); var scrolled = false; ...

AngularJS: Utilizing Multiple HTTP Requests with the $http Service

Here is the code snippet I am working with: var updateScreen = function() { $http.get("http://localhost:5000").then(function(response){ $scope.numSerie = response.data.refDetail.Num_Serie; $http.get("data/tempsgammes ...

Tips for setting a Bootstrap 3 dropdown menu to automatically open when located within a collapsed navbar

Is there a way to have my dropdown menu automatically open when the collapsed navbar is opened? Take a look at this example I created in a fiddle to see what I'm working with so far. Right now, when you click on the navbar in its collapsed state, two ...