Using controllerAs in an AngularJS directive allows for multiple instances to be created, each with the

In my form, I have directives that contain identical input fields, selects, and check boxes. To handle this, I created a directive with an isolate scope and controllerAs syntax using bindToController=true. The controller has a method triggered by an ngChange on the checkBox. However, I encountered an issue where the controller alias I assigned, 'ctrlVm', is overwritten by the second instance of the directive. This results in the runTest() function firing for both directives, instead of independently.

A simplified version of the problematic directive and controller looks like:


function myDirective() {
  var directive = {
    restrict: 'AE',
      priority: 100,
      require: 'ngModel',
      scope: {
        boundObject: '=boundObj',
        myArray: '='
      },
      templateUrl: 'myTemplate.html',
      controller: controller,
      controllerAs: 'ctrlVm',
      bindToController: true
    };
    return directive;

    function controller() {
      ctrlVm = this;
      ctrlVm.runTest = runTest;

      function runTest() {
        ctrlVm.myArray.push(ctrlVm.boundObject.first);
      }
    }
}

To see the full demo showcasing this issue, visit:

http://plnkr.co/edit/TdZgadsmVQiZhkQQYly1?p=preview

Essentially, I expect clicking each box to result in either "one" or "two" being added to the array. However, due to the controller alias being overwritten, both instances behave the same way adding "two" regardless of the clicked box.

I have searched extensively but found limited solutions suggesting different aliases for controllers or dynamically setting the controllerAs name based on directives. Unfortunately, these approaches would require separate views as my current view utilizes controllerAs aliases. Is there a way to reuse the controller and maintain the expected functionality for each directive separately?

Answer №1

The variable ctrlVm is not declared in your directive's controller.

Make the following change:

  function controller() {
    var ctrlVm = this;
    ctrlVm.runTest = runTest;

    function runTest() {
      ctrlVm.myArray.push(ctrlVm.boundObject.first);
    }
  }

Here is the updated code: http://plnkr.co/edit/Cdz47jgtpU6GYQ12vWhL?p=preview

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

Catch the return of the transition event

My website is built on asp net core, with all pages displayed as partialviews to create a spa model without relying on angular or other frameworks. By switching partialviews, I can easily modify the page's url using window.history.pushState ("objec ...

Modifying selections within a select box generated dynamically using JQuery

Looking for help on how to delegate to a static DOM element in my current situation. I need to create a dynamic select box .userDrop when .addNew is clicked, and then have the user select an option from #secDrop, triggering a change event that calls the da ...

What is the best way to populate a div with multiple other div elements?

My current project involves creating a sketchpad using jQuery for an Odin Project assignment. However, I have encountered an issue with filling the canvas (wrapper div) with pixels (pixel divs). The canvas does not populate correctly. Here is the link to m ...

What is the best way to prevent the use of "******" at the beginning of every line in Javascript/Node Bund

Update: I am currently working on a Node.js test project (utilizing WebPack). In the development builds (app.js), at the start of each line, there is /******/ https://i.sstatic.net/jZ5h6.png Since this seems to be common behavior, I am wondering if th ...

The values obtained from the previous parameter object of the React setState hook can vary and are not always

In my code, I am using a useEffect hook to update the state with setState. However, I'm encountering some unusual and inconsistent behavior with the previous parameter: useEffect(() => { setCurrentPicturesObject((existing) => { ...

Running numerous MEAN stack applications on a single VPS is a cost-effective and efficient

Currently, I am delving into the world of MEAN stack development and have successfully deployed an application to an AWS EC2 instance running Ubuntu. While everything is functioning properly, I'm curious about whether it's feasible to host multip ...

Utilizing Express REST API with Postgres through the HTTP method

I am currently working on implementing REST APIs with Express and Postgres. I have a scenario where I need to delete all instances from a table based on the user_id foreign key, and then insert new instances with the same user_id. I'm unsure which HTT ...

Several iFrames embedded on the website automatically adjust to the same pre-set height

Apologies if this question has already been addressed, but I am struggling to properly articulate it. Here's the issue: I have a client's holiday accommodation website that uses three embedded iFrames for a Calendar, Booking Enquiry, and floorpla ...

Maximizing PUT Methods in HTTP RESTful Services

I've been playing around with my routes file and I'm looking to switch up the method being called (delete instead of update). Code Snippets: # User management API GET /users @controllers.Users.findUsers POST /user ...

To prevent the default alignment in case the text exceeds the input length, stop the automatic alignment

I have a query regarding an input field with a maximum length of 4 characters. The appearance is such that these 4 characters seem to be delineated by borders which are actually 3 lines displayed above the input field. When I enter the fourth character, a ...

Tips for filling a Rails dropdown list using a JSON array

My Ant show page showcases detailed information about different types of ants. There are two drop downs on the page - one for environment: [indoor, outdoor], and another for diet: [sugar, fat, protein]. When a parameter is selected from each dropdown, it ...

Apply a border to the input field when the user enters or leaves the field, only if the value is

I am managing a few input fields and storing their information in an object. My goal is to click on an input field to focus on it, and if the field is empty or has a length greater than or equal to 0, I want it to display a red border. If I type somethin ...

How to Set Up a Simple Gulp Uglify Configuration

My objective is to compress all .js files within my project and save a minified version in the same directory. Assuming this is the structure of my project directory: project/ gulpfile.js basic.js Project/ Project.js Toolbelt. ...

animation of leaping to a specific element

I am currently working on a sidebar with links that have a hover effect to add a bullet. However, I want the bullet to smoothly follow the cursor's movement along the y-axis within the sidebar instead of jumping between the links. How can I achieve th ...

Unexpected Issue with JavaScript Ajax (Using jQuery.post): The Promise State Turns to "Rejected"

Recently, I've been encountering some issues while trying to debug my jQuery.post() call. The responses I'm getting are quite puzzling and I'm at a loss on how to proceed next. If anyone has any suggestions or insights, I would greatly appre ...

Using Vanilla Javascript to implement a dark mode toggle button

I've been struggling with getting a button to properly switch a website to dark mode. I already have a night mode that works based on the user's location and time, so I know the issue lies within my JavaScript... Initially, I tried adding ' ...

In my attempts to retrieve specific statistics from the PokeAPI using Axios and Node.js, I encountered an error

Having an issue while trying to utilize the Pokemon API. Whenever attempting to access the attack, HP and speed stats, all Pokemons show up as undefined! Can someone please point out what might be wrong with my API call? const axios = require('axios&a ...

What is the best way to send a parameter to the callback function of a jQuery ajax request?

I am facing an issue where I need to pass additional variables to a jQuery ajax callback function. Consider the following scenario: while (K--) { $.get ( "BaseURL" + K, function (zData, K) {ProcessData (zData, K); } ); } func ...

Top method for showcasing animated images (HTML/CSS/JS)

For my website, I want to create an engaging animation showing a coin being flipped multiple times in the air before landing on a specific side. After the animation finishes, I would like it to transform into a static image of the final result. I've ...

Learn the process of retrieving JSON objects through AJAX using jQuery

When making a jQuery call to an API website, I receive the results in JSON format: { "results":[ { "user":{ "gender":"female", "name":{ "title":"mrs", "first":"linda", "last":"diaz" }, ...