Class-based AngularJS directive using ES6 syntax

After using classes to define a directive, I encountered an issue. The html code is displaying correctly and the constructor and controller functions are being called as expected. However, there is a specific class method that I intended to call from the HTML using ng-click but it seems like it's not working.

It's worth mentioning that I am currently working on version 1.3x and cannot upgrade at the moment.

Link to Plunker

Directive:

class StoreHours{

  constructor(){
    console.log("Inside constructor");
    this.restrict = 'E';
    this.templateUrl = 'storeHours.html';
    this.bindToController = true;
    this.controllerAs = 'vm';
    this.scope = {
      hours: '=',
      index: '=',
      addNewHour: '&'
    };
  }

  controller(){
    console.log("Inside controller function");
  }

  // The class method I want to call with ng-click
  addNew(newHour){
    var vm = this;

    console.log("addNew()");

    vm.addNewHour({ hour: newHour, index: vm.index });

    vm.newHour = "";
  }

  // Not necessary but included for reference
  link(scope, element, attrs){

  }
}

app.directive('storeHours', () => new StoreHours);

HTML:

<div style="background-color: gray;">
  <h1>I'm the store hours component!</h1>

  <li ng-repeat="hrs in vm.hours">
    {{hrs}}
  </li>

  <input type="text" ng-model="vm.newHour" />
  <button ng-click="vm.addNew(vm.newHour)">Add New</button>
</div>

Answer №1

addNew() function is associated with the class scope, but if you want to link it to the controller() scope (which is different)

Simply include the function within the controller and everything should work correctly.

  controller(){
    console.log("within controller");
    var vm = this;  
    vm.addNew = function(newHour){
      console.log("addNew()");
      vm.addNewHour({ hour: newHour, index: vm.index });
      vm.newHour = "";
    }
  }

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

Send a Dictionary<String, List<String>> object to JavaScript

I am looking to send a Dictionary> from the server to the client using JavaScript. Although I came across this post, I am still unsure about the steps to follow. To clarify my objective, the dictionary comprises the 'name' key of all workshee ...

Exiting AngularJS Page

Utilizing AngularJS for my frontend, I have a routes.js file where I can set up a resolve to initialize variables required for controllers before navigating to a page. However, I'm looking for the reverse scenario - when leaving a page, I want to tri ...

The particles-js effect only partially fills the page

I've encountered some issues with particles-js. Firstly, it fails to cover the entire page. Additionally, I seem to be unable to interact with the particles for reasons unknown. Here is the HTML code snippet: <script type="text/javascript" src="j ...

The style in {filename} was not applied as it has a MIME type of 'text/html', which is not a compatible stylesheet MIME type

Currently, I am working with an index.ejs file in conjunction with Express for a local host web server. However, I seem to be encountering 4 errors of 2 different types. You can view the errors here. Below is a snippet of my code: <html> <head> ...

Retrieve the name of the object within the nested structure

One challenge I'm facing is with the object named '$scope.filter'. It has a nested structure like this: I am trying to figure out how to retrieve the name of the nested object (key in this case) using a directive. Ideally, I would like to a ...

"The transparency of the three-js canvas texture is compromised when using the WebGL renderer, unlike the Canvasrenderer which maintains

I am attempting to display a CircleGeometry over a cube from the camera view. The cube has a solid color, while the circle contains just an arc on a canvas with no background color. When using CanvasRenderer, the transparency of the canvas is retained an ...

How to Retrieve AngularJs Controller properties using the ng-if directive on the root element

Is there a way to access the angular controller property from the same tag where ng-controller is defined and hide the tag using ng-if if the property languages has less than one element? This is what my code currently looks like, but it's not workin ...

Embarking on your journey with the Withings API

How can I connect to my website with the Withings API? I want to send weight values to the Withings API and receive body measurement values. Where can I find the code for the Withings API? $config['withings_settings']['widgets'] = &apo ...

What is the best way to transfer a value to v-model using emit?

I'm having trouble passing the selected value from a select field to v-model. Currently, the code only seems to work with a v-text-field. <script> export default { name: 'FormSelect', props: { model ...

Using AJAX to pass the ID name when clicking in PHP

Currently, I am in the process of implementing an Ajax-driven filtered search system that consists of three distinct tabs. These tabs allow users to search by names, category, and location. I have successfully enabled searching when a user types a name int ...

Google Maps: Customize infoWindow Layout

I'm having trouble figuring out how to change the default frame of an infoWindow in Google Maps. Here's my code where I create a marker and add a listener that opens an info window: var markerPosition = new google.maps.LatLng(lat, lng); ...

Unable to locate and interact with a specific element within a dropdown menu while utilizing Protractor

I am currently facing an issue with selecting a checkbox from a dropdown in jq widgets. The code seems to work fine when the element is visible on the screen, but fails otherwise. I have tried various methods such as executeScript and scrollIntoView to bri ...

Easily log in and create an account on a single webpage with the help of PHP and

I'm currently engrossed in a web project. The initial version of the project had separate login.php and register.php files. The login functionality called a .js file for ajax validation, and the same process occurred with the registration. In the re ...

What is the most efficient way to loop through these parameters in order to refine an array?

Hello, I need some help with my code. It currently filters an input array to remove any values that match specific arguments. However, I am struggling to iterate through all the arguments effectively. Here is the code that is currently working: function d ...

Improved method for detecting click events

I am facing an issue with two calendars controlled by user input. Currently, if a user clicks to open one calendar and then clicks anywhere outside of it, both calendars close simultaneously because they are detecting each other as the target. I am looking ...

What is preventing me from parsing JSON in JavaScript?

This JSON data consists of a single object: results[0] = { 'MAX(id)': 1 } The following code snippet is not functioning as intended: var text = results[0]; var obj = JSON.parse(text); console.log(obj.MAX(id)); ...

The MVC framework coupled with a robust Javascript/JQuery validation library is a winning

Currently, I am involved in a project that utilizes MVC 2.0 along with Kendo UI. Our team has made the decision to utilize AJAX validation instead of MVC Model level validation. This means that validation occurs during most "onchange" events on HTML contro ...

Steps for closing a modal window when a layer is unchecked on the control panel

One of the features on my website is a modal window that pops up whenever a user selects a layer from a menu. The user can close this modal window by using the "X" icon or clicking on the map itself. However, there is an issue where if the user unchecks th ...

Can parameters be passed using object and serialization in jQuery?

$.post('/ur.l' , jQuery('selectors').serialize() + '&textareaname=" + escape( $("#textarea").val() ) , function(data) { ... } } ); $.post(&a ...

Performance problem with React-Native for-looping through a large array size

I'm currently facing a performance issue with the search function in my react-native app. The search involves scanning through an array of 15,000 elements for specific keywords. Surprisingly, the search performs well and quickly on Android devices, bu ...