ng-click not functioning correctly within templateUrl directive

Apologies if this appears to be a silly question, but I am new to Angular. I am facing an issue with an ng-click event that was functioning correctly until I moved the code into a directive. I suspect it has something to do with the scope, but I'm unable to resolve it.

Here is the html file I am referencing from templateUrl:

<div class="thumbnail">
    <p class="title">{{ flight.origin }}</p>
    <p class="title">{{ flight.destination }}</p>
    <p class="title">{{ flight.airline }}</p>
    <p class="date">{{ flight.deptime | date: 'medium' }}</p>
    <p class="date">{{ flight.arrtime | date: 'medium' }}</p>
    <p class="price">{{ flight.price | currency }}</p>
    <div class="pax">
        <p>Adults: {{ flight.paxadult }}</p>
        <p class="likes" ng-click="plusOneAdult($index)">+ </p>
        <p class="dislikes " ng-click="minusOneAdult($index)">-</p>
    </div>
</div>

Referenced in a js file:

app.directive('flightInfo', function () {
    return {
        restrict: 'E',
        scope: {
            flight: '='
                },
        templateUrl: 'js/directives/flightInfo.html'

    };
});

It is called from my main page using:

  <div ng-repeat="flight in flights | orderBy:'price'" class="col-xs-12 col-sm-6">
      <flight-info flight="flight"></flight-info>
  </div>

Answer №1

Make sure to include your 'plusOneAdult()' and 'minusOneAdult()' methods in your directive setup like so:

<div ng-repeat="trip in trips | orderBy:'price'" class="col-xs-12 col-sm-6">
      <trip-info decrease-adult-fn="minusOneAdult" increase-adult-fn="plusOneAdult" trip="trip"></trip-info>
  </div>

In your directive, be sure to receive these functions as shown below:

return {
        restrict: 'E',
        scope: {
            trip: '=',
            decreaseAdultFn:'=',
            increaseAdultFn:'='
                },
        templateUrl: 'js/directives/tripInfo.html'

    };

Answer №2

Kindly take note that the function you are attempting to access from templateUrl in the directive needs to be defined within the link section of the same directive.

Therefore, following your code, the link method should look something like this:

templateUrl: 'js/directives/flightInfo.html',
link: function(scope, ele, attr) {
    scope.plusOneAdult = function(id) {
        // your code
    };

    scope.minusOneAdult = function(id) {
        // your code
    }
}

Answer №3

It seems that your directive is not associated with any controllers, which means that your ng-click functionality within the directive will not be functional.

To resolve this issue, you should create a new controller and transfer your 'plusOneAdult' and 'minusOneAdult' functions to this newly created controller. Then, you can link this controller to your directive in the following manner:

app.directive('flightInfo', function () {
    return {
        restrict: 'E',
        scope: {
            flight: '='
        },
        templateUrl: 'js/directives/flightInfo.html'
        controller: 'js/directives/flightInfoController.js',
        controllerAs: 'Vm',
        bindToController: true
    };
});

You can now utilize the functions in your HTML like this: Vm.plusOneAdult() and Vm.minusOneAdult()

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

When using v-for to render an array list fetched from AsyncData, an error is thrown: The virtual DOM tree rendered on the client-side does not match the one

For my application, I am utilizing Nuxt.js. On one of the pages, I am using AsyncData to fetch an array of data objects from my API asynchronously. These data objects are then rendered in my template using v-for. Everything is functioning properly until I ...

Insert a JSX element into the body of a webpage using React JSX

Is there a way to dynamically add elements to the end of the body using vanilla JavaScript? const newRecipe = <div id = "container"> <div className="recipe App" id="four" onClick={this.toggleRecipeList.bind(this)}>{this.state.recipeName} < ...

AngularJS is throwing an error when trying to use a specific module

Hello everyone, I am a beginner with angular.js and I am encountering a problem that I need help with. I have tried to create a basic screen using a controller and a module in my example, but unfortunately, it is not working as expected. Below is the examp ...

Convert the jQuery functions click(), hide(), and fadeIn() into their equivalent native JavaScript functionalities

I'm determined to speed up my page by reducing requests. Does anyone have a solution for keeping the functionality of the code below without having to load the entire JQuery library? $("#div1").click(function () { $("#div2).hide(); $("#div3). ...

Looking for assistance with removing hardcoding in HTML and jQuery?

Currently working on a biography page for my company's website that features a grid layout of the employees' profile pictures. Each picture should be clickable, causing the screen to fade to gray and display an overlay with the respective person& ...

Spin an object around the global axis using the tween.js library

I'm trying to achieve a gradual rotation of a cube on the world axis using tween. Initially, I was able to rotate the cube around the world axis without tweening with the following code: rotateAroundWorldAxis(cube[1], new THREE.Vector3(0,1,0),degreeT ...

Is there a specific jest matcher available for comparing Array<Objects>?

I'm currently testing the equality of two arrays of objects and have found that the toEqual matcher in Jest only works for arrays of strings. Is there another matcher available in Jest that can handle this condition? Please refrain from marking this a ...

A guide to dynamically display input fields according to the selected mat-radio button in Angular Material

I am currently utilizing angular material version 9.2.4 Within my project, I am implementing the angular material mat radio button with an input field. Each payment method will have its own corresponding input field. When the 'Cash' option is se ...

ReactJS tables that can be filtered and sorted

Within my component's state, there exists an array named 'contributors'. Each element within this array is an object containing various properties. My goal is to present this data in a table format, with the added functionality of sorting an ...

Struggling to get the jQuery resize event to function properly

Ensuring that my charts remain responsive on different devices has been quite a challenge. Despite implementing a resize event handler in my function to dynamically adjust the charts, I encountered an issue where the page would go blank upon resizing the b ...

Tips for making a sidebar sticky when scrolling

In order to keep the right-side bar fixed, I have implemented this javaScript function: <script type="text/javascript> $(document).ready(function () { var top = $('#rightsidebar-wrapper').offset().top - parseFloat($('#rightsideb ...

Tips for managing this JavaScript JSON array

Here is an example of a JSON array: var data = { name: 'Mike', level: 1, children: [ { name: 'Susan', level: 2, }, { name: 'Jake', level: 2 }, { name: 'Roy', level: 2 }, ...

javascript box is hidden to prevent displaying of values

I need the negative character to disappear when the user clicks the minus (-) button. The count should stop at 0. Currently, it is displaying characters like -1, -2, -3. I only want to show 0 or numbers greater than 0. <script type="text/javascript" ...

Learning more about the functionality of ui-router, particularly how the ui-sref directive can be used to navigate to

Here is an example of the HTML code: <li class="list-group-item" ui-sref="contacts.detail({id:4})"> <span class="badge" ui-sref="contacts.selected">14</span> Cras justo odio </li> When contacts.selected is clicked, it w ...

Combining and visualizing multiple datetime series in Highcharts

Is there a way to overlay two datetime x-axes that have different date ranges but the same number of data points? I want point index x from series 1 to line up with point index x from series 2. I attempted to do this by using two x-axes, one of which is h ...

Create PDF and Excel files using Javascript on the client side

Are there any client-side Javascript frameworks that are comparable to Jasper Report in Java? I need to be able to generate both PDF and Excel files on the client side (browser) without relying on server-side processing. While I've come across Ja ...

The formValidation, previously known as BootstrapValidator, is causing issues with my form submission via Ajax, despite my efforts to update the code to work with

I recently upgraded the old BootstrapValidator to the new 0.6.0 release known as formValidation. Despite reading the documentation multiple times, I have been unsuccessful in finding the issue and need some assistance. Below are the CSS styles and scripts ...

Wordpress causing Jquery to malfunction; PHP function not executing

Looking to incorporate a script into my WordPress function.php file. Here's what I have so far: <?php function add_google_jquery() { if ( !is_admin() ) { wp_deregister_script('jquery'); wp_register_script('jquery', ...

Tips for concealing select options after choosing with select picker?

Our establishment features three distinct rooms, each offering three identical options that users can choose from. https://i.sstatic.net/Jx4Me.png To illustrate, if a user named John selects option one in the first room, that same option will be hidden w ...

Utilizing AngularJS and Node.js to update MongoDB

Looking for a solution to update my MongoDB using Node.js and AngularJS within the front-end of my application. The code I currently have is causing an error stating `TypeError: Cannot read property 'put' of undefined. Here is my AngularJS contr ...