What is the best way to trigger a button click event that performs various actions depending on the specific Controller currently present in the view?

INQUIRY

How can you trigger a button click that performs different actions depending on which Controller is present in the view?

SITUATION

I am working with two directives/controllers that use the same template view. The data is displaying correctly, but the ng-click="{{::vm.action}}" does not function when clicked. If I modify it to ng-click="{{::vm.action()}}", the view breaks.

CODE

main.html

<confirm-modal></confirm-modal>

<error-modal></error-modal>

modal.html:

<article>
    <h1>{{::title}}</h1>
    <p>{{::body}}</p>
    <button ng-click="{{::action}}">{{::button}}</button>
</article>

confirm-modal.directive.js (and controller)

angular
  .module('common.modal')
  .controller('ConfirmModalController', ConfirmModalController)
  .directive('confirmModal', confirmModal);

/* @ngInject */
function confirmModal() {

  var directive = {
    templateUrl: 'app/widgets/modals/modal.html',
    restrict: 'E',
    controller: ConfirmModalController,
    controllerAs: 'vm',
    bindToController: true
  };

  return directive;
}

function ConfirmModalController(modalService) {

  var vm = this;

  vm.title = 'Confirm Your Subscription';

  vm.body = '$8.99 per month will be billed to your account.';

  vm.button = 'Subscribe';

  vm.action = function () {
    console.log('confirm subscription');
    modalService.confirmSubscription();
  };

}

error-modal.directive.js (and controller)

angular
  .module('common.modal')
  .controller('ErrorModalController', ErrorModalController)
  .directive('errorModal', errorModal);

/* @ngInject */
function errorModal() {
  var directive = {
    templateUrl: 'app/widgets/modals/modal.html',
    restrict: 'E',
    controller: ErrorModalController,
    controllerAs: 'vm',
    bindToController: true
  };

  return directive;
}

function ErrorModalController(modalService) {

  var vm = this;

  vm.title = 'There was an error with your request';

  vm.body = 'Please contact administrator regarding this error';

  vm.button = 'Dismiss';

  vm.action = function () {
    console.log('error on subscription');
    modalService.closeAllModals();
  };
}

Answer №1

{{::vm.action}} is a reference to the method vm.action, whereas {{::vm.action()}} triggers that method when the template is displayed. Angular binds the result of the method (which is undefined here) to your ng-click. Simply remove the Angular expression delimiters in the click handler:

<article>
    <h1>{{::vm.title}}</h1>
    <p>{{::vm.body}}</p>
    <button ng-click="vm.action()">{{::vm.button}}</button>
</article>

Edit: Apologies. Forgot the ()

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

Are you looking to conduct comprehensive UI tests for a team-based web application?

Our web application is designed for collaborative use, so actions by one user in their browser affect another user's experience. A prime example of this functionality can be seen in our chat room feature. The technology stack we are currently using i ...

passing two $index values in a nested ng-repeat loop

Currently, I have implemented an ng-repeat within another ng-repeat to create a navigation menu. In each <li> element in the inner ng-repeat loop, I have set an ng-click event that triggers the relevant controller for that specific menu item, passing ...

AngularJS Validation does not verify the step limitation of an HTML number input field

Why isn't AngularJS validating the step="0.01" attribute in the second input? It seems to be working fine for the min and max attributes, but not for step. For instance: When entering 0.005, it still evaluates submitNewEntryForm.submitNewEntryAmount. ...

AngularJS Treeview with Vertical Line Styling using CSS

Struggling with styling, I am attempting to create a tree view in AngularJS. Currently, I am facing an issue aligning vertical and horizontal lines for the tree items. Check out my Codepen for reference. <html lang="en"> <head> <meta cha ...

Angular: Specifying initial value for a select input

I have created a Plunker with the code below. The issue I am facing is that the default value [Bank Account Number] is not being selected in the dropdown menu, even though the model is being updated correctly. Can anyone assist me with this? //index.htm ...

If someone rapidly clicks on an AngularJS app, the page fails to load

Just a heads up - I am pretty new to Angular. Most of the code is from a tutorial on Lynda that I'm experimenting with. I've noticed an issue when I try to implement a type of "pagination" feature to display various elements from a data.json file ...

"Integrating multiple partials with templateUrl in AngularJS: A step-by-step

Is there a way to merge partial views using the templateUrl attribute in an AngularJS directive? Imagine having a directive like this: .directive('combinePartials', function () { var mainPartial = "mainpartial.html", var template2 = "pa ...

The AngularJS $http.post method resulted in a 404 error

I am currently experimenting with posting data to the server using $http.post in Angular. The backend of my project is built with Laravel. As a beginner in Angular, I haven't implemented anything complex yet. However, when attempting to post to /api, ...

The function of removing the ng-submitted class in AngularJS after form submission seems to be malfunctioning when using setPristine and setUnt

When a form is submitted in Angular, the class ng-submitted is automatically added by default. In my attempts to reset the form state by using $setPrestine and $setUntouched, I encountered some errors that prevented it from working properly. Examples of t ...

Issue with accessing Scope value in AngularJS directive Scope

FIDDLE I've recently developed a directive that looks like this: return { restrict: 'EAC', scope: { statesActive: '=' }, link: function (scope, element, attrs) { var ...

In AngularJS, the process of replacing text using a filter can be achieved by following

Currently in the process of learning Angular, but I've hit a roadblock and can't seem to find a solution. I have a website that provides USPS shipping options, and I need to replace the default text with my own. The vendor's option shows &ap ...

New possibilities arise following ng-switch implementation

I am facing an issue with a switch that alters the value of a variable known as p. <div ng-switch on="p"> <div ng-switch-when="true"> /*...displaying nodes and option to add node*/ </div> <div ng-swi ...

The Angular modal service is failing to show up on the screen

I am having trouble implementing the angular modal service in my web application. When I click on the button, the modal does not appear. Can someone help me figure out what I am doing wrong? Builder View <div ng-controller="BuilderController as vm"> ...

The skin colors are failing to load on JWPlayer7

I've encountered a strange issue with jwplayer. I'm setting it up from an Angular JS Controller and loading it using a simple preview button that loads the jwplayer with the specified configuration. It should be straightforward. jwplayer(id).s ...

AngularJS Error: Attempting to Access Undefined Object - Jasmine Testing

Encountering an error while running Jasmine tests when trying to mock/spy on an API call in the tests. Below is the code snippet responsible for calling the API: UploadedReleasesController.$inject = ['$log', '$scope', '$filter&apo ...

Using Angular JS to retrieve specific information from a JSON file

I am in the process of developing an AngularJS app that showcases notes. The notes are stored in a note.json file, and the main page of the app only displays a few fields for each note. I want to implement a feature where clicking on a specific note opens ...

Guide on accessing a local image while setting the background image using JavaScript

I am trying to set a background image from a local source on my computer. Below are two lines of code, one that works and one that does not: (the local one fails) _html.style.backgroundImage = 'url("urlsourceblahblahblah")'; _html.style.backgro ...

What is the best approach to send data to the parent when closing $mdDialog?

When I open a Dialog Window, it has its own controller. Is there a way for me to modify data in the differentController that belongs to the Dialog Window and then send the modified data back to the parent controller when the dialog is being removed? fun ...

Checking for offline status in a Cordova app using Angular

I have implemented the following code to determine whether my Cordova application is online or offline. var networkState = navigator.connection.type; var states = {}; states[Connection.UNKNOWN] = 'Unknown'; states[Connection.ETHERNET] = ' ...

Tips for assigning a value in a dropdown menu with AngularJS

Can someone help me with setting the same value in multiple drop-down lists using angular.js? Below is an explanation of my code. <table class="table table-bordered table-striped table-hover" id="dataTable"> <tr> <td width="100" align ...