Executing an Angular controller function with ng-click using ES6

Exploring the use of ES6 with Angular 1.6, leveraging Browserify and Babelify in Gulp has led me to an issue where I am unable to call a controller's methods on the DOM using ng-click when creating the controller with ES6 class.

controller:

    export default class FocusbtnsController {
    constructor($scope) {}

    testMethod() {
        alert('test method works!!');
    }
}

main module:

import angular from 'angular';
import FocusbtnsController from './focusbtns.controller';

export default angular.module('shapesite', [])
    .controller('FocusbtnsController', FocusbtnsController);

HTML:

<div class="center-btns ng-scope" ng-controller="FocusbtnsController">
    <div class="focus-btn-container" style="left:50%;top:5%" ng-click="testMethod()">
        <div class="diamond">
            <div class="diamond-btn"></div>
        </div>
    </div>
</div>

Removing the export default from the angular.module did not yield any results. Adding the method testMethod to the $scope argument like $scope.testMethod = testMethod; does work, but it seems inefficient.

Is there something I am overlooking that would allow me to call the controller method while utilizing ES6 syntax without having to assign it to the $scope?

Answer №1

Expanding on my previous response, here is a straightforward example of an Angular 1.5+ component.

samplecomponent.component.html

<button ng-click="$ctrl.someAction()">Press Me</button>

samplecomponent.component.js

import template from './samplecomponent.component.html';

class SampleComponentController {
  constructor($service) {
    'ngInclude';

    this.$service = service;
  }

  someAction() {
   console.log('Greetings planet Earth');
  }
}

const sampleComponent = {
  template,
  controller: SampleComponentController,
  bindings: {},
};
export default sampleComponent;

samplecomponent.module.js

import sampleComponent from './mycomponent.component';

angular.module('MyModule')
  .component('sampleComponent', sampleComponent);

To implement it, you can use

<sample-component></sample-component>
.

Another approach would be similar to the solution provided by Nicholas Tower, however, in my personal view, components are more suitable for Angular 1.5+.

Answer №2

When utilizing classes as controllers (or ES5 objects with prototypical inheritance for that matter), it is essential to implement controller-as syntax. This informs Angular to utilize variables present on the controller itself, rather than on $scope. Your template will need to be updated like so:

<div class="center-btns ng-scope" ng-controller="FocusbtnsController as $ctrl">
    <div class="focus-btn-container" style="left:50%;top:5%" ng-click="$ctrl.testMethod()">
        <div class="diamond">
            <div class="diamond-btn"></div>
        </div>
    </div>
</div>

I highly suggest taking it a step further by leveraging AngularJS's Components instead of ng-controller. Refer to Baruch's response for an example using components.

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

Using AngularJS to nest ng-repeat within ng-model

I'm in the process of learning AngularJs and I've encountered a problem that I need help with. Here is an example demo link Whenever I click on the first select drop down, the one below it also changes. I understand this is because of the same ...

The "disabled" attribute is no longer recommended, please utilize "disable" instead

Lately, after upgrading AngularJS, I have been receiving a warning whenever I open a ui.bootstrap modal. The warning in Chrome-beta 44 says: angular.js:11655 Use of "disabled" attribute has been deprecated, please use "disable" I'm curious if this i ...

Ajax continues to operate even if an error is detected

Hello fellow programmers! I'm currently facing an issue with form submission and validation using jQuery with 2 ajax events. The problem lies in the fact that even if the first ajax event (timeconflict.php) returns an error, the second ajax event (res ...

What is the approach to initiating a jquery function once HTML content is dynamically added through an AJAX call?

<div id="timeline"> <ul class="grow" id="grown"><li>One</li><li>Two</li><li>Three</li><li>Four</li><li>Five</li><li>Six</li><li>Seven</li><li>Eight< ...

Communication lost with Oracle database in NodeJS - receiving error ORA-03135

I am currently working on a NodeJS application that utilizes the oracledb library to establish a connection with an Oracle Database. The code snippet below is used for attempting the database connection: this.oracledb.fetchAsBuffer = [this.oracledb ...

Is there a way to reduce the excessive bottom margin on Twitter embeds?

Is there a way to adjust the Twitter embed code for tweets so they don't have a large margin at the bottom? Here is an example of the standard Twitter embed code: <blockquote class="twitter-tweet"><p>@<a href="https://twitter.com/gami ...

Glitchy/Crazy CSS3 Animations

Currently, I am developing a website at . One of the features I have implemented is CSS3 transitions for route changes, but this feature only works in Chrome. Here's how the animation works: I apply the .preanimate class to rotate the phasing out di ...

My .php file seems to be having trouble loading any of the external css or javascript files

Being new to PHP, I recently created a .php website and connected it to a local test server using MAMP. However, I encountered an issue where the CSS and JavaScript from external files weren't working, even though the PHP functionality (such as sendin ...

Are Opera and IE9 blocking cross-origin Ajax requests?

I have been utilizing the following page - - to initiate a cross-origin Ajax request towards this specific resource: The functionality appears to be functioning as expected in Chrome, Safari, and Firefox, but encounters an issue in IE9 and Opera. Below ...

Add to MongoDB only if the entry does not already exist; otherwise, move on

Can I perform a conditional insert in MongoDB? //Pseudo code Bulk Insert Item : If Key exists Skip, don't throw error If key does not exist Add item If I do single inserts, it might return an error or insert into the collection. But is thi ...

Shifting elements within Phoria.js

I'm currently working on a game where a ball bounces and falls into a randomly placed bin. I'm wondering if there's a way for the ball to jump and land based on the dynamic coordinates of the bin. If I have knowledge of the direction and dis ...

Unexpected behavior observed with Async Await

I'm currently working on a feature for my node server that involves using cheerio to extract information from a website. However, I'm facing some unexpected behavior with my functions. Here is the controller code: class ScraperController { s ...

generate a series of nested divs within one another

I am looking to create a custom nested loop that will generate div elements based on the content of my h1 and h2/h3 tags. I understand this may have been covered in other inquiries, so any guidance would be appreciated :) Here is the initial HTML: <h1& ...

Uh-oh! It seems like there is a deployment error in NextJS on Vercel. The issue is that Nested

Suddenly, my middleware ceased to function properly during deployment. The error message states: > Build error occurred NestedMiddlewareError: Nested Middleware is not allowed, found: pages/_middleware Please relocate your code to a single file at /midd ...

What is the process for including a JavaScript file in an HTML document?

Greetings to all and thank you for taking the time! I have a straightforward query for you.. I have designed an html page featuring only a basemap (open street map). Moreover, I possess a javascript file which utilizes your coordinates to calculate a perce ...

Material-UI Autocomplete can only save and display one specific property of an object at a time

Can someone help me with implementing Autocomplete from Material-UI? I want to store only a specific property value and not the entire object. For example, let's say I want to store the property Value, but it could be any other property as well. con ...

Are there benefits to using AngularJS for a basic AJAX site?

After creating a basic website, I have decided to enhance it with a JavaScript overlay for various functionalities such as: Implementing ajax in the search box and pagination for seamless loading of results without refreshing the page Integrating the HTM ...

Attempting to generate tables from JSON containing numerous "table" sections

Hello there. My goal is to generate tables from the JSON data I've received. While creating a table works fine with a single block of JSON, I face challenges when dealing with multiple blocks for multiple tables. Below you'll find an example of J ...

Detecting changes in input elements when setting values in AngularJS

Access Code: http://jsfiddle.net/mb98y/309/ HTML <div ng-app="myDirective" ng-controller="x"> <input id="angular" type="text" ng-model="data.test" my-directive> </div> <button onclick="document.querySelector('#angular&a ...

Steps for extracting URL parameters from AWS API Gateway and passing them to a lambda function

After successfully setting up my API gateway and connecting it to my lambda function, I specified the URL as {id} with the intention of passing this parameter into the lambda. Despite numerous attempts using both the default template and a custom one for ...