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

Creating a dynamic start page for Progressive Web Apps (PWA) involves determining the

Recently, I developed a project called "Progressive Web App" using JavaScript and Visual Studio 2017. One key element of the project is the file "package.appxmanifest", which defines the StartPage. I am curious to know if there is a way to dynamically se ...

Master the art of using Insertion Sort in javascript with the help of Khan Academy

Seems like I am almost there with solving this problem, but my code isn't running as expected. Can someone offer some feedback and point out where I went wrong? var insert = function(array, rightIndex, value) { for(var j = rightIndex; j & ...

the onreadystatechange function is not being triggered

When trying to call the show_Message function, I expected an alert box to appear. However, the onreadystatechange is not working as expected. All other alert boxes are functioning properly. Below is my JavaScript function: function send_Message(){ var ...

Querying Firebase by the value of a child node

Here is how my structure looks like: 2017511 UcQefEaHJG6fteGsbsiaWjQ60d9Q62 value1: 50 value2: 1200 value3: "blabla" AcQefEaHJG6fteGsbsiaWjQ60d9Q62 value1: 55 value2: 2200 value3: "balabla" BcQefEaHJG6fteGsbsiaWjQ6 ...

Display modal within a React list

I need to display a list of items with an edit button for each item, which should trigger a modal showing the details of that specific item. Initially, I had a single modal component in the parent element and passing the visible values to the parent state ...

Displaying FontIcon in a NativeScript alert box

Would it be possible to display a fonticon on a Nativescript dialog? Similar to this example? dialogs.alert({ title: // set icon as text message: "Check-in Successful" }).then(()=> { console.log("Dialog closed!"); }); Is it feasible to ...

Do you find this unattractive? What are some ways to improve this unsightly JavaScript statement?

This code seems messy, how can I better structure this switch statement? function renderDataTypeIcon(dataType: string) { let iconName; switch (dataType) { case "STRING": //TODO - ENUM iconName = "text"; break; ...

``Promise rejection triggered when a boolean value is passed to $q.when`

In the code snippet below, $q.when is used to resolve a promise with either true or false. It is known that $q.when will always resolve and never be rejected. When passing a boolean value to this segment, it is observed that the error callback function is ...

What is the best way to create a selection input using buttons and save the chosen option in the state?

Check out this snippet showcasing 3 buttons const [role, setRole] = React.useState('') const [active, setActive] = React.useState(false) <Grid container spacing={1}> <Grid item xs={4}> <Button variant='plain&apos ...

The capability to scroll within a stationary container

Whenever you click a button, a div slides out from the left by 100%. This div contains the menu for my website. The problem I'm encountering is that on smaller browser sizes, some of the links are hidden because they get covered up. The #slidingMenu ...

Does the CSV stream parser (PapaParse) cause rendering delays?

Currently, I am utilizing papa parse to fetch csv streams from my backend in order to visualize data. However, I have observed that while it is successfully invoking the callback for the data chunks, it is also causing rendering issues. I am attempting to ...

Interacting with an element within a jQuery dialog box created through a function click

I'm encountering an unusual issue with jQuery and Javascript across all browsers (IE, FF, Chrome). On my (asp.net) webpage, I have the following structure: A header with numerous dynamically generated buttons at PreRender A hidden div containing but ...

Using feature flags in Vue for enhanced functionality

I am interested in incorporating a "feature toggling mechanism" into my Vue application. Although I have set up a basic system, I want to explore the methods outlined in a article by Pete Hodgson. The concept of "Inversion of Decision" seems particularly i ...

How come the light position is not updating?

I am currently using the three.js library to create an animated cylinder: let renderer, camera, scene, light, cylinder; initialize(); animate(); function initialize() { renderer = new THREE.WebGLRenderer({ alpha: true, antialias: true }); renderer ...

React Big Calendar encountered an error: The element type provided is not valid, as it is expected to be a string for built-in

Error One: The element type is invalid: it was expecting a string (for built-in components) or a class/function (for composite components), but received undefined. This could be due to not exporting your component correctly from the file where it's d ...

What causes Vue to only update once when there are two closely timed mutations to reactive data?

Can you take a look at this simple example? export default { data() { return { name: "Amy", age: 18, }; }, computed: { combinedDataForWatching() { return { name: this.name, age: this.age, ...

Tips for dynamically styling a Styled Component with all the CSS housed in an external file

My goal is to dynamically render a Styled Component. In the past, it was simple because all styling was contained within the component itself. However, I now strive to maintain a separation of concerns by storing the CSS in an external file. While this app ...

What is the best way to designate a selected list item in AngularJS?

I need to update the underlying model when a list item is clicked. The goal is to set the controller's $scope.current to match the index of the clicked list item. Because the list items are not standard form inputs, I am unable to use ng-model for thi ...

The div remains unchanged when the button is clicked

My webpage is filled with several large div elements. There's a button on the page that, when clicked, should switch to the next div. Despite my efforts, the code I've written doesn't seem to be working as expected. :( This is the HTML st ...

What is the method for retrieving the name of an object's property within an Angular template

I am trying to display the name of a nested object's property using Angular interpolation <ng-container ngFor="let item of saleDetailsAggegater.productMap | keyvalue"> <tr *ngFor="let qtyMap of item.value | keyvalue"&g ...