Issue with calling on-click function from a directive's template not being triggered

I am new to Angular and I'm experiencing an issue with my ng-click not working in certain contexts. Let me share my code and explain the problem more clearly.

HTML :

<div ng-app='myApp'>
   <section id="map-orders" ng-controller="ProductsController as products">
      <div class="product-box" ng-repeat="products in products.products | orderBy:'name'">
         <div class="product">
            <h3> {{products.name}} </h3>
            <span ng-click="remove($index)">Remove</span>
         </div>
      </div>
   </section>
</div>

JS :

var app = angular.module('myApp', [ ]);

app.controller('ProductsController', function(){
    this.products = products;   
    this.remove = function(index) {
        products.splice(index, 1);
    }
});

var products = [
    {
        name: "Carte 1", 
        generationDate: "03/03/2016",
    },
    {
        name: "Carte 2", 
        generationDate: "04/03/2016",
    }
];

The above code works fine. However, when I introduce a directive like this: HTML :

<div ng-app='myApp'>
   <section id="map-orders" ng-controller="ProductsController as products">
      <div class="product-box" ng-repeat="products in products.products | orderBy:'name'">
         <product></product>
      </div>
   </section>
</div>

And include this additional JavaScript for the directive:

app.directive('product', function() {
    var tpl = '<div class="product">' +
    '<h3 {{products.name}} </h3>' +
    '<span ng-click="remove($index)">Remove</span>'
    '</div>';
    return {
        restrict: 'E',
    template: tpl,
    };
});

Now, my remove() function does not work. I'm unsure why this is happening. Any help specifically related to my code would be greatly appreciated.

Thank you in advance.

Answer №1

When utilizing the controllerAs syntax, it is necessary to specify an alias for your function remove in the template.

Check out a live example on jsfiddle.

var myApp = angular.module('myApp', []);

myApp.controller('MyCtrl', function($scope) {
    this.products = [{
      name: "Alex",
    }, {
      name: "Sam"
    }];
    this.remove = function(index) {
      this.products.splice(index, 1);
    }
  })
  .directive("product", function() {
    var tpl = '<div class="product">' +
      '<h3> {{product.name}} </h3>' +
      '<span ng-click="my.remove($index)">Remove</span>'
    '</div>';
    return {
      restrict: 'E',
      template: tpl,
      link: function(scope) {
        console.log(scope);
      }
    };
  });
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp">
  <div ng-controller="MyCtrl as my">
    <div class="product-box" ng-repeat="product in my.products">
      <product></product>
    </div>
  </div>
</div>

P.S. There is an error in the template. The h3 tag should be closed properly.

Answer №2

When working with directives, it is important to ensure that you are utilizing the correct scope. In this case, your directive is using the same scope as your ProductsController. This means that the remove method in your ProductsController can be called by using products.remove($index), following the syntax of as controller when specifying the controller in your HTML.

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

What is the best way to showcase the outcome on the current page?

This is a sample HTML code for a registration form: <html> <head></head> <body> <form id="myform" action="formdata.php" method="post"> username:<input type="text" name="username" id="name"><br> password:&l ...

When trying to make a POST request, the browser displayed an error message stating "net::ERR_CONNECTION

Currently, my project involves coding with React.js on the client side and Express.js on the server side. I have encountered an issue when attempting to use the POST method to transmit data from the client to the server for storage in a JSON file. The erro ...

Ways to eliminate the occurrence of 'undefined' in Object.keys while using forEach loop

Hey there! I'm currently working with Node.js and running into an issue with using forEach on Object.keys. In the code snippet below, when I try to execute it, I encounter a problem where the first value in the output is undefined. For instance, let&a ...

Challenges encountered when attempting to retrieve browser information using the window.navigator object from website visitors

I've been attempting to retrieve information about the visitors' browser on my website. Unfortunately, the return I receive for each parameter is showing as 'undefined.' Below is the code I'm using (this is linked as an external J ...

What could be causing Next.js to throw an error upon completion of the MSAL OAuth process?

I encountered an error while building a website using next.js. The site is set up for production, and after the authentication process with MSAL for Azure AD integration, I am facing the below error during the OAuth loop. As a beginner in next.js coming fr ...

Dynamically add a plugin to jQuery during execution

After installing jQuery and a jQuery-Plugin via npm, I am facing the challenge of using it within an ES6 module. The issue arises from the fact that the plugin documentation only provides instructions for a global installation through the script tag, which ...

When the mongod process is active, the Gulp watch task encounters an EBUSY error

I have devoted countless hours to trying to solve this issue on my own, scouring the internet for similar problems, but to no avail. I have come to the realization that my best course of action is to seek assistance by posting a question here. In my backe ...

Can a Javascript file be concealed from view?

Imagine a scenario where the localhost root file is served an HTML file using the following code: app.get('/', (req, res) => res.sendfile('index.html')) Is it possible to include JavaScript files in the HTML document that are not a ...

Exploring solutions for handling asynchronous issues with vue3-google-map

While working with a Vue library for managing Maps called vue3-google-map, I encountered an issue when trying to define certain polylines that would not allow me to select the center of the marked area: Here is my map template: <template> <Goo ...

Encountered an issue when attempting to send data using this.http.post in Angular from the client's perspective

Attempting to transfer data to a MySQL database using Angular on the client-side and Express JS on the server-side. The post function on the server side works when tested with Postman. Here is the code snippet: app.use(bodyParser.json()); app.use(bodyPa ...

Using Javascript to invoke a PHP function and retrieve the response

This particular post showcases a sample code for fetching a server file list as an illustration. Below is the code that was utilized: <html lang="en-US"> <head> <meta charset="UTF-8"> <title>Guidance on creating form using jQ ...

Can a sophisticated text editor be utilized without a content management system?

Many website builders utilize rich text editors as plugins to enhance content creation, such as in CMS platforms like Joomla and WordPress. However, can these same editors be easily integrated into a custom website built from scratch using just HTML, PHP ...

When using this.$refs in Vue, be mindful that the object may be undefined

After switching to TypeScript, I encountered errors in some of my code related to: Object is possibly 'undefined' The version of TypeScript being used is 3.2.1 Below is the problematic code snippet: this.$refs[`stud-copy-${index}`][0].innerHTM ...

Integrating Amazon external images in NextJS

There is a specific issue with loading images from a URL stored on Amazon S3 within the domain configured in next.config.js. Strangely, when using external URLs like Unsplash, the images load fine. The problematic URL is: idinheiro-admin-images.s3.sa-east ...

Ways to transfer information from a directive to a controller

In my application, I have created a custom directive that utilizes D3.js. The goal is to trigger an API call to fetch more data when a user clicks on a node within the D3 visualization. This involves accessing the data linked to the clicked node and sendin ...

Launch a new pop-up window that will disappear once the user clicks outside of the window

In my Java web application, I'm attempting to create a pop-up window that appears over the parent window when a user clicks on a link. The pop-up window will display values fetched from a database using Hibernate, and the user can select a value. Once ...

What is the best way to send a Rails AJAX form upon clicking?

I'm looking to implement AJAX form submission in Rails using a button. Here's my current code: Controller: def list @events = ExternalEvent.all if !params[:city_id].nil? @events = @events.where(city_id: params[:city_id]) end respond ...

Learn how to calculate and showcase time discrepancies in minutes using Angular2

I am currently working on an Angular app that displays orders using the *ngFor directive. Each order has a datetime field indicating the date it was created. My goal is to implement a timer that shows how long a customer has been waiting for their order ...

Reorganize the JSON data to match the specified format

{ "EUR": { "Description": "", "Bid": "1.1222", "Region": "", "Bid1": "1.1283", "CurrencyCode": "EUR", "FeedSource": "1", "Ask": "1.1226", "ProviderName": "TEST 1", "Low": "1.1195", ...

Declare `document.body` as the designated container element for the material-ui Tooltip

The issue: I need to show a tooltip pointing to an element (referenceEl) from the left. The referenceEl is located within a container that has a limited width of 60px and has the css properties overflow: hidden applied. Due to the tooltip being appended af ...