Passing data to an Angular directive

I am facing an issue while trying to pass information through a view in a directive. Despite binding the scope, I keep seeing the string value 'site._id' instead of the actual value.

Below is the code for the directive:

angular.module('app')
    .directive('anomalieTableau', function () {

        var controller = ['$scope', '$attrs', 'srv_traitementsSite', function ($scope, $attrs, srv_traitementsSite) {
            $scope.anomalies = [];

            var idSite = $attrs.idsite;
            alert(idSite);
            var idAgence = $attrs.idagence;
            var dateDebut = $attrs.datedebut;
            var dateFin = $attrs.datefin;

            var promise = undefined;
            if (idAgence && idSite) {
                promise = srv_traitementsSite.TraitementSiteAgenceAnomalie(idSite, idAgence, dateDebut, dateFin);
            }

            promise.then(function (response) {
                $scope.anomalies = response.data;
            }, function (response) {

            });
        }];

        return {
            restrict: 'EAC',
            templateUrl: 'tpl/directive/AnomalieTableauDirective.html',
            controller: controller,
            scope: {
                idsite: '=',
                idagence: '=',
                datedebut: '=',
                datefin: '='
            }
        };
    });

Here's how the directive is called in HTML:

<div anomalie-tableau idsite="site._id" idagence="AgenceId" datedebut="dateDebutStats"
                     datefin="dateFinStats" class="col-md-12"></div>

The alert result in the directive is showing 'site._id' instead of the expected value '123456789'.

Upon editing 'site._id' to {{site._id}} in the attribute directive's call, it triggers an error:

Syntax Error: Token 'site._id' is unexpected, expecting [:] at column 3 of the expression [{{site._id}}] starting at [site._id}}].

I'm unsure what mistake I'm making. Can anyone provide insights?

Answer №1

When working with attributes in Angular, it's important to remember that they are always treated as strings. To use these attribute values in your directives, you may need to interpolate them first using {{site._id}}. If the attribute value is stored as a string, like in $attrs.idsite, you may also need to convert it to the desired type.

Regarding scope settings, if you're accessing values from attributes within your directive, make sure to use $scope instead of $attrs. This way, Angular will automatically copy the values to your scope. When using two-way binding (=), there is no need for interpolation as Angular handles this for you.

However, if you must use $attrs, you can perform the interpolation manually by removing the scope settings, utilizing idsite="{{...}}", and injecting the $interpolation Service into your directive.

To get the interpolated value as a string, you can then use

$interpolate($attrs.idsite)($scope.$parent)
.

For an example showcasing these concepts, visit: http://plnkr.co/edit/zhBXyiz82EdmysLzeBNL?p=preview

(Note that in my Plunker demo, I used @ in the scope settings. You can choose to leave it or remove it. Using @ tells Angular to handle the interpolation for you and store the value in the $scope object within your directive.)

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

Utilizing PHP to create an interactive website

As a novice PHP developer, I took to Google in search of tutorials on creating dynamic PHP websites. What I found was that many tutorials used the $_GET variable to manipulate URLs and make them appear like this: example.com/?page=home example.com/?page= ...

Display the name of the file on the screen

Is there a way to dynamically display the file name in a view instead of hardcoding it? I would appreciate any assistance. Thank you! Here is my code snippet: <li> @if (Model.Picture2 != null) { base2 = Convert.ToBase64String(Model.Pict ...

Transforming an array of strings into a Name/Value object using JavaScript

Recently, I encountered a Web Service that sends an array of strings to the client. My goal is to transform this array into an object where each string has a name for future reference. Let's start with: var result = ["test", "hello", "goodbye"]; An ...

assign a JSON key to a variable

Is there a way to use a variable as a JSON key in JavaScript? var chtid = "1234" firebase.database().ref().set ({chtid :"hi"}); In this case, chtid is the variable. I have attempted this method without success: var chtid = "1234" firebase.database().re ...

Troubleshooting: Missing Headers in AngularJS HTTP Requests

When I make a request using AngularJS like this: var config = { headers: { 'Authorization': 'somehash', 'Content-Type': 'application/json; charset=UTF-8' } }; $http.get('htt ...

Problem with transferring data from Google Forms to Google Sheets using Google Apps Script

Currently, I am having an issue with my code that adds responses to a Google Sheets from a Google Forms sheet. The problem is that it always adds the responses to the first column, even if it should go into a different column based on its title. I suspec ...

Transmit form data via Ajax request

Thank you for your interest. I am looking to retrieve $_POST['Division'] from a dropdown list: <select name="Division" onchange="setImage2(this);"> <option value="1">Bronze</option> <option value="2">Silver</op ...

Creating a JavaScript and C# popup for deleting records in asp.net

I'm struggling a bit with understanding how server-side deletion works. I know how to use MessageBox, but it's not the best approach. I've been advised to use a popup on the server side. What I'm trying to achieve is that when you clic ...

The name field in the request body is currently undefined

Currently, I am working on developing a basic blog page using technologies such as ejs, JavaScript, Node.js, Express, and body-parser. While working on passing inputs to the command line, specifically for the title, I encountered an issue. When I used req ...

AngularJS can be used to display a webpage

After facing the need to print a given page using AngularJS, I came up with a simple solution as shown below: <div class="modal fade" id="extrait" aria-hidden="true" data-backdrop="false"> <table class="table table-hover table-bordered" i ...

"Utilizing a JavaScript array to track the start of the week and

I am encountering a logic problem with determining the start of the week. Below is a snippet of the code: WeekStarts(WeekN) { let WeekBD = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Sa ...

Steps for inserting an additional header in an Angular table

https://i.stack.imgur.com/6JI4p.png I am looking to insert an additional column above the existing ones with a colspan of 4, and it needs to remain fixed like a header column. Here is the code snippet: <div class="example-container mat-elevation-z8"> ...

ReactJS input range issue: Cannot preventDefault within a passive event listener invocation

I've been encountering some issues with the react-input-range component in my React App. It functions perfectly on larger viewports such as PCs and desktops, but on smaller devices like mobile phones and tablets, I'm seeing an error message "Unab ...

Executing a function when a webpage loads in Javascript

I have created a responsive website using Twitter Bootstrap. On my site, I have a video displayed in a modal that automatically plays when a button is clicked. Instead of triggering the function with a button click, I want the function to be called when ...

The Vue.js modal is unable to resize below the width of its containing element

My challenge is to implement the Vue.js modal example in a larger size. I adjusted the "modal-container" class to be 500px wide, with 30px padding and a max-width of 80%. However, I'm facing an issue where the "modal-mask" class, containing the contai ...

Is there a way to modify the document title using .ready()?

As I work with nested layouts in Ruby on Rails, one particular layout requires me to extract a string from a div and use it as the title of the document. What is the proper method (if there is one) to accomplish this task? <script type="text/javascri ...

React-Leaflet continuously updates the map with the "MouseMove" event

I'm looking to implement a feature in my React app that displays the geographic coordinates as the mouse moves. However, I've noticed that using "Mousemove" causes the map to be continually redrawn with all objects each time, resulting in poor pe ...

How to deactivate an option in md-autocomplete

I encountered a scenario where I converted an md-input-container with a md-select/md-option to a md-autocomplete. While in the initial setup of md-select/md-option, we were able to apply ng-disabled property to both the md-select and md-option. However, wh ...

programming / mathematics - incorrect circular item rotation

I need help arranging a sequence of planes in a circular formation, all facing toward the center. However, I seem to be experiencing issues with the rotation after crossing the 180-degree mark. While my objects are correctly positioned around the circle, t ...

creating grunt shortcuts with specified option values

Is it possible to create custom aliases in Grunt, similar to npm or bash? According to the Grunt documentation, you can define a sequence of tasks (even if it's just one). Instead of calling it "aliasing", I believe it should be referred to as "chaini ...