Tips for transferring information from a controller to a directive using the $emit method

I am facing an issue passing values from the controller to the directive

Within my controller, I have two arrays defined as:

$scope.displayPeople.push(data.userName);
$scope.displayOrg.push(data.orgname);

I need to pass these arrays from the controller to the directive

This is my directive:

<div>
    <div class="multitext-wrap blue-border">
        <ul inputfocus>
            <li class="tag" ng-repeat="list in displayItems track by $index" ng-class="{selected: $index==selectedIndex}" >
                <span class="tag-label">{{list}}</span><span class="tag-cross pointer" ng-click="Delete($index,selecteditemslist[$index],list,searchid)">x</span>
            </li>
            <li class="">
                <input type="text" ng-model="searchModel" ng-keydown="selected=false" ng-keyup="searchItem(searchModel,searchobj)"/>
            </li>
        </ul>
    </div>
    <div class="typeahead" ng-hide="!searchModel.length || selected">
        <div class="typeahead" ng-repeat="item in searchData | filter:searchModel | limitTo:8" ng-click="handleSelection(item,searchobj,$index,searchid)" style="cursor:pointer" ng-class="{active:isCurrent($index)}" ng-mouseenter="setCurrent($index)">
            <div class="bs-example">
                <div class="list-group list-group-item active">
                    {{item.displayConfig[0].propertyValue}} {{item.displayConfig[1].propertyValue}}
                </div>
            </div>
        </div>
    </div>
</div>

I tried using $emit to send the data

In the controller:

$rootScope.$emit("displayEvent", {displayItems: $scope.displayPeople});
$rootScope.$emit("displayEvent", {displayItems: $scope.displayOrg});

In the directive:

$rootScope.$on('displayEvent', function (event, args) {
    $scope.displayOrgs = args.displayItems;
    console.clear();
    console.info($scope.displayOrgs);
});

However, this approach is resulting in duplicates. Both people and org data are being duplicated. How can I solve this issue? Please help. Thank you in advance.

Answer №1

When you set 'scope: false' in your directive, you are able to access the controller's scope. This means that an isolated scope is not created, and the directive inherits the controller's scope.

.directive('myDirective', function() {
  return {
    scope: false,
    link: function($scope){
        //Perform actions with $scope.displayOrgs
        //Perform actions with $scope.displayPeople
    }
  };
});

On the other hand, creating an isolated scope and inheriting selected variables is another option that provides a cleaner approach.

 .directive('myDirective', function() {
      return {
        scope:{
           displayPeople:'=',
           displayOrg :'=',
        },
        link: function($scope){
            //Perform actions with $scope.displayOrgs
            //Perform actions with $scope.displayPeople
        }
      };
 });

Answer №2

It is not recommended to use $emit for communication between controller and directive. Instead, you should use the "=" scope of the directive to enable two-way communication. Here is an example:

Directive
<pre><code><pre><yourDirectiveName displayPeople="displayPeople" displayOrg="displayOrg"></yourDirectiveName></pre>

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

Exploring the power of React Hooks with the useState() function and an array filled

When creating new "Todo" items and modifying the fields, everything works fine. However, my problem arises when trying to retrieve the child data after clicking the "show all objects" button. To better understand my issue, here is a code example: const Co ...

Step-by-step guide on building a personalized rxjs operator using destructured parameters

I am in the process of developing a unique RxJS filter operator that requires a destructured array as a parameter. Unfortunately, TypeScript seems to be throwing an error related to the type declaration: Error TS2493: Tuple type '[]' with a len ...

Guide to adding sound effects to your Vue 3 app using the Composition API

I'm having trouble setting up a basic button click feature in Vue 3 Composition API to play a sound effect. In my setup function, I have imported an mp3 sound effect from the assets folder and passed it into a ref method with an HTMLAudioElement type, ...

Even after implementing a setTimeout function, both Promises and Axios requests are still resulting in a

Recently, I've encountered an issue with the Reverse Geocode API from TomTom. The problem arises when I send multiple latitude and longitude coordinates (around 72 of them) to the API, resulting in frequent 429 responses. To address this issue, I att ...

How can I create space between a checkbox and its label in Google Web Toolkit (GWT)?

How can I create space between a Checkbox and its content in GWT? Checkbox c = new Checkbox("checkme"); c.setStyleName("checkbox_style"); When I try using padding or margin, the entire checkbox and its content move together. Is there a way to achieve a g ...

Retrieving information from MongoDB queries using Node.js

I am facing an issue while trying to retrieve data from the find() method and use it outside the method. My goal is to incorporate this data into a JSON response. Unfortunately, my current code is not working as expected and the data is not accessible outs ...

An error was encountered involving an unexpected token < at the beginning of a JSON file while using express with firebase

After setting up an authentication system in express using firebase auth, I established an endpoint in my express server: app.post('/users/login', (req, res) => { console.log('logging in...'); firebase.auth().signInWithEmail ...

Retrieving JSON information from a lone field in a MySQL table

I am currently working with a PHP REST Web service that is being accessed from JavaScript. Everything works fine when I run a MySQL SELECT statement to select text fields and then use json_encode to convert the returned array into JSON objects. However ...

What is the best way to handle a confirm() dialogue box using Jasmine / Protractor for testing AngularJS applications?

I've been trying to incorporate end-to-end testing into my current application, but I've hit a roadblock. There's a confirm() dialogue box that pops up in my code (asking the user to confirm if they want to remove something) and I'm not ...

I'm surprised by the fact that array.findIndex is not functioning properly. According to Mozilla, it should be working fine

It was necessary to change state.findIndex to state.ids.findIndex in order to resolve the issue I was facing. However, an unexpected behavior occurs when calling the function onClick, as it automatically updates ALL of the active values to true, instead o ...

Issue encountered in performing a post request using AngularJS

One of the functions in my code is a post call: save2 : function ( lotto ) { var configDistintaIngrediente = { params: { distintaBaseGelato_id: 1, ingrediente_id: 2, quantit ...

Experimenting with the inner workings of a method by utilizing vue-test-utils alongside Jest

Is there a way to properly test the internal logic of this method? For instance: async method () { this.isLoading = true; await this.GET_OFFERS(); this.isLoading = false; this.router.push("/somewhere"); } This method toggles isLoading, ...

Verifying with VueJS and Jest: How to test if a component's method calls an imported function

I've created a VueJS 2 component that has the following structure: <template> <div> <button @click="onFavorite"> Add to favorites </button> </div> </template> <script> import { tra ...

The Angular web application utilizing an ASP.NET Web API that is hosted on AppHarbor is showing the incorrect webpage

Working on a web application using Angular and ASP.NET Web API in Visual Studio 2015 has been quite the journey for me. Upon running the solution in VS2015, I encountered two tabs opening in Chrome - one for my Angular client-side application and another ...

Is it possible to deactivate an element based on a specific string present in the URL?

<div class="custom-class1"> <div class="custom-class2" id="custom-id1">hello 1</div> <div class="custom-class3" id="custom-id2">hello 2</div> <div class="custom-class4" id="custom-id3">hello 3&l ...

Tips on obtaining checkbox value in an AJAX request

I need to retrieve the value of a checkbox using Ajax in order to store it as a user preference in the database. This task is new to me, and I'm feeling a bit overwhelmed. Here is my JavaScript file: $(document).ready(function() { E.accounts.chang ...

Is it possible for me to transfer a class attribute to a directive template in AngularJS?

I recently came across this directive in AngularJS: productApp.directive('notification', function($timeout) { return { restrict : 'E', replace : true, scope : { type: "@", message: "@ ...

What are the differences between ajax loaded content and traditional content loading?

Can you explain the distinction between the DOM loaded by AJAX and the existing DOM of a webpage? Is it possible to load all parts of an HTML page via AJAX without any discrepancies compared to the existing content, including meta tags, scripts, styles, e ...

What is the process for uploading an image and entering text into the same row in Google Sheets?

Hello, I am currently working on a Google Script web app that enables users to upload 10 photos along with comments for each photo. This information will then be inserted into a Google Sheet when the user clicks the 'upload' button on the web app ...

Arrangement of Axes in Google Graphs

I have a basic form where users can input data through drop-down selectors. There are 10 questions, each with a rating out of 10. The entered data is then used to generate a Google graph on the same page. Although the graph populates correctly, the axis ...