The parameters remain consistent across all Angular directives

I have created a directive called 'filterComponent' with the following code:

app.directive('filterComponent', function() {  
  return {
    restrict: 'E',
    templateUrl: 'filter-component.html',
    link: function(scope, element, attrs) {
        console.log(attrs);
        scope.type =  attrs["type"];
    }
  };
});

This directive is used three times in different places in my HTML like this:

<filter-component type="TYPE1"></filter-component>
<filter-component type="TYPE2"></filter-component>
<filter-component type="TYPE3"></filter-component>

The content of the directive's HTML template is as follows:

<div id="{{type}}" class="filter-container">
    <div layout="row" class="rhs-text" ng-show="!noTargetSelectedYet">
        <md-input-container flex="">
             <label>Search</label>
             <input style="position: relative; top: 7.8px;" ng-model="filterText">
         </md-input-container> 
    </div>
</div>

The issue I am facing is that although I pass different values for the attribute 'type' in each usage of the directive, the 'id' attribute becomes the same (specifically the last value, 'TYPE3'). This behavior can be seen in the console log messages as well.

What could possibly be causing this problem?

Answer №1

If you want your directive to have its own isolated scope and not affect the outer scope, follow these steps:

app.directive('filterComponent', function() {  
  return {
    restrict: 'E',
    scope: {
        type: '='
    },
    templateUrl: 'filter-component.html',
    link: function(scope, element, attrs) {
        console.log(attrs);
        scope.type =  attrs["type"];
    }
  };
});

It's a best practice to use the scope option for creating isolate scopes when building reusable components in your app.

Learn more about directives in AngularJS here

Update:

To also utilize filterText:

app.directive('filterComponent', function() {  
  return {
    restrict: 'E',
    scope: {
        type: '@', // Pass as string
        filterText: '=' // Pass by reference
    },
    templateUrl: 'filter-component.html',
    link: function(scope, element, attrs) {
        console.log(attrs);
        scope.type =  attrs["type"];
    }
  };
});

HTML:

<filter-component type="TYPE1" filterText="filterText"></filter-component>

For a deeper understanding of isolate scopes, refer to this resource: Isolate Scope in AngularJS Directives

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 a more streamlined approach to creating a series of methods and functions that alter a single variable consecutively?

My JavaScript project involves handling sub-arrays within a long data file that cannot be altered. The data, stored in a variable named data, is retrieved via a script tag with a specified URL property. I need to extract and modify specific sub-arrays from ...

Learn how to easily incorporate a drop-down list into the material-UI Search component within the navbar to enhance the search results

I integrated a Material UI search bar into my React app's navbar following the instructions from the official documentation on MUI. However, the article does not provide any guidance on how to add a dropdown list when selecting the search input field. ...

Configure your restify REST API server to handle both HTTPS and HTTP protocols

I'm currently utilizing node.js restify version 4.0.3 The code snippet below functions as a basic REST API server supporting HTTP requests. An example of an API call is var restify = require('restify'); var server = restify.createServer( ...

A function that listens for the onmouseover event and updates the image source of an HTML img element

I have created a function that positions my objects based on the array they are assigned to. For example, if they are in players[0], they will be placed in one position, and if they are in players[1], they will be placed elsewhere. The X and Y values are ...

The model fails to update when a blur event occurs

I am a beginner with Angular2 and I am currently working on creating a reactive form, specifically an interactive date input field. Here is my HTML code: <div class="date ui-input"> <input type="text" name="dateD" [ngModel]="model.date | dat ...

Converting line breaks or newlines in AngularJS textareas

My textarea is populated with content through ng-model: <textarea data-ng-model="messageBody"></textarea> I need to store the messageBody in the database using newline characters (\n) instead of line breaks. However, when I attempt to co ...

Utilize JSON data from a service to populate a Bootstrap Modal

I need assistance with populating a Modal using the JSON values I received from a service call. The object structure is simple and understandable, like this: var object = [ {Value1: "Val1", Value2: "Val", Value3: [{a:"a",b:"b"}] }] The ajax call looks ...

Troubleshooting jsPDF problem with multi-page content in React and HTML: Converting HTML to PDF

I need to convert HTML content in my React application into a PDF file. My current approach involves taking an HTML container and executing the following code snippet: await htmlToImage .toPng(node) .then((dataUrl) => { ...

Is there a way to assign the value of a textfield to a session attribute in JSP prior to rendering?

Imagine I have the following code snippet: <html> <head> <script> function setSession() { var roll=document.getElementById("rollno").value; session.setAttribute("rollno", roll); } & ...

What is the method for retrieving the values of multiple numbers entered in table rows using ASP?

I am trying to customize an input field so that the client can add or delete N number of input fields as needed. While I have successfully implemented adding input fields, I am facing difficulty in retrieving values from these dynamically added text fields ...

VUE JS - My methods are triggering without any explicit invocation from my side

I've encountered a frustrating problem with Vue JS >.<. My methods are being triggered unexpectedly. I have a button that is supposed to execute a specific method, but this method gets executed along with other methods, causing annoyance... Her ...

Dropdown element vanishes upon selecting in HTML

Utilizing Angular's ng-init to populate a rest call function and populate $scope.races before filling up the dropdown. Initially, everything appears to be working correctly. However, upon selecting an option from the dropdown menu, it immediately cle ...

Looking for assistance with PHP if statement and troubleshooting iFrame issues

Using the PHP if statement below on my website: <?php if(empty($_GET['tid'])) echo '<iframe src="http://tracking.mydomain.com/aff_goal?a=33&goal_id=47" scrolling="no" frameborder="0" width="1" height="1"></iframe>'; ...

The problem with escaping characters in Javascript occurs when a backslash is duplicated within an object

My intention was to save the JSON object with an escape character by escaping "/". I achieved this by using string replace to convert my string into "\/". Afterwards, I assigned this to an object variable and attempted to console log it, only to find ...

Issues with posting form data in AngularJS are occurring

Here is the code I am currently using: On the Angular side vm.onSubmit = function(){ var person = vm.formData.slice(0, 1)[0]; //This line extracts the required fields from the model object which is nested in an array. $http({ ...

Here is a guide on setting up a placeholder for an editable-select component

I'm looking for a way to add a placeholder in an editable-select using x-editable angularjs. <span editable-select="data.CenterId" e-name="CenterId" e-form="rowform" e-placeholder="Select Center" e-ng-options="s.Id as s.Name for s in locationLis ...

How to retrieve an unknown JSON key in Vue.js when using v-for loop?

I have developed a code analysis tool and I am looking to display my JSON data in a Vue table. The challenge is that I need the JSON key, which represents the package/file name of the directory whose data I want to showcase. Below is an excerpt of the JSO ...

Exploring the ideal scenarios for utilizing propTypes in React

When creating in-house components that require specific props to function properly, I believe it is best to conduct prop requirement checks during testing rather than including propTypes in the production code. This is especially important for components t ...

Mastering preventBack() Functionality - A Foolproof Method to Eliminate a Div on Back

This unique code prevents the page from going back when using the back button: <script type = "text/javascript" > function stopGoingBack(){window.history.forward();} setTimeout("stopGoingBack()", 0); window.onunload=function(){null}; ...

Selecting an entire row in a Kendo grid

Is there a way to configure kendoGrid to highlight the entire row when clicked on? I have tried setting: scrollable: { virtual: true } and disabled paging, but it doesn't seem to work as intended. You can view an example here: Kendo UI Dojo When ...