Include the attrs directive within the template of your AngularJS application

Here is the code snippet I am working with:

appForm.directive('inputRadio', function(){
    return {
        restrict: 'E',
        link: function (scope, elem, attrs){

        },
        compile: function(elem, attrs){
            return {
                pre: function preLink( scope, elem, attrs ) {

                },
                post: function postLink( scope, elem, attrs ) {

                }
            }
        },
        template: '' +
        '<div class="radio">' +
        '<label class="required"><input type="radio" id="attrs.twigId" name="attrs.twigName" ng-model="optionMultipleChoice" ng-required="required" value="attrs.twigValue" >attrs.twigLabel</label> ' +
        '</div>'
    }
});

I'm trying to directly insert attributes with the variable " attrs " into the template, like id = " attrs.twigid ". However, I'm not sure if I should do this in the compile or link function...

Thank you!

Edit:

appForm.directive('inputRadio', function(){
    return {
        restrict: 'E',
        link: function (scope, elem, attrs){

        },
        compile: function(elem, attrs){
            return {
                pre: function preLink( scope, elem, attrs ) {
                    scope.varstwig = attrs;
                },
                post: function postLink( scope, elem, attrs ) {

                }
            }
        },
        template: '' +
        '<div class="radio">' +
        '<label class="required"><input type="radio" id="[[ varstwig.twigid ]]" name="[[ varstwig.twigname ]]" ng-model="optionMultipleChoice" ng-required="required" value="[[ varstwig.twigvalue ]]" >[[ varstwig.twiglabel ]]</label> ' +
        '</div>'
    }
});

This code is functional, but there is a bug where the "scope" gets overwritten when multiple directives instances exist, causing them all to have the same values.

Is there a way to fix this issue?

The call looks like this:

{% block _test_optionsExpanded_widget %}
    <div class="form-group">
        <label class="control-label required">Options expanded</label>
        <div id="test_optionsExpanded">
            {% for option in form.children %}
                <input_radio twigId="{{ option.vars.id }}" twigName="{{ option.vars.full_name }}" twigValue="{{ option.vars.value }}" twigLabel="{{ option.vars.label }}" twigShortName="{{ option.vars.name }}"></input_radio>
            {% endfor %}
        </div>
    </div>
{% endblock %}

Answer №1

After some tinkering, I finally cracked it! Haha!

By setting the variable scope as " @ ", I was able to prevent it from being overwritten, ensuring that each directive retains the specific values provided by twig.

Big thanks to everyone who helped me figure this out :)

appForm.directive('inputRadio', function(){
        return {
            restrict: 'E',
            scope: {
                varstwig: '@'
            },
            link: function (scope, elem, attrs){

            },
            compile: function(elem, attrs){
                return {
                    pre: function preLink( scope, elem, attrs ) {
                        scope.varstwig = attrs;
                    },
                    post: function postLink( scope, elem, attrs ) {

                    }
                }
            },
            template: '' +
             '<div class="radio">' + 
             '<label class="required"><input type="radio" id="[[ varstwig.twigid ]]" name="[[ varstwig.twigname ]]" ng-model="optionMultipleChoice" ng-required="required" value="[[ varstwig.twigvalue ]]" >[[ varstwig.twiglabel ]]</label> ' +
             '</div>'
        }
    });

Answer №2

It seems like your goal is to access certain attributes that are defined within the HTML element. The key is to create a separate scope for isolation.

appForm.directive('inputRadio', function(){
    return {
    restrict: 'E',
    scope: {
       twigId : "=",
       twigName: "=",
       twigValue: "=",
       twigLabel: "="
    },
    link: function (scope, elem, attrs){

    },
    compile: function(elem, attrs){
        return {
            pre: function preLink( scope, elem, attrs ) {

            },
            post: function postLink( scope, elem, attrs ) {

            }
        }
    },
    template: '' +
    '<div class="radio">' +
    '<label class="required"><input type="radio" id="{{twigId}}" name="{{twigName}}" ng-model="twigValue" ng-required="required" >{{twigLabel}}</label> ' +
    '</div>'
}
});

This approach should address your requirement. You may need to double-check the radio parameters for accuracy. It's important to understand the significance of using "=" in "twigValue: =" and similar declarations.

When you use "=", it indicates that the attribute is linked to a variable in the parent scope. Alternatively, "@" is used if the attribute is solely a value.

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

nested distinct apartment in js

Are there any new and super powerful ES JavaScript features that can accomplish this task? (I could come up with a function to do it, but I'm curious if there's a cutting-edge ES202* technique available) let arr = [ ['cb', '&ap ...

Interactive ng-messages and validation

Validation rules have been set in JSON format and are stored within a factory service. "inputname":{ "rule":{ "required":"required", "ng-minlength":"3", "ng-maxlength":"16" }, "error":{ "required":"Name ...

Tips on transforming json data into a nested json data structure with data grouping?

Here is a sample of a json array: [{ id:1, topicid : 1, Topic:Topic_name, categoryid:1, category : category_name, subcategoryid:1, subcategory : subcategory_name, pageid: 1, pageurl : pageurl_name }] I am looking to convert the json dat ...

Tips for applying multiple colors to text within an option tag

I am currently struggling with adding a drop-down list to my form that displays 2 values, with the second value having a different text color (light gray). After some research, it seems like I need to use JavaScript for this customization. However, as I am ...

Propagating changes in child scope variables to parent scope in AngularJS

Is there a way to efficiently update variables in the ParentCtrl when a new variable is created in the ChildCtrl? Without relying heavily on $on and $watch functions for an easier implementation. ParentCtrl ChildCtrl / ChildCtrl2 / ChildCtrl3 / ChildC ...

Organize and eliminate items within a vessel

Looking to manipulate a container with span elements by removing two and re-arranging one. I attempted the following approach: $('span.class5').insertBefore('span.class0'); However, this inserted each span.class5 into every repeating ...

Utilizing JavaScript to Extract JSON Information from Knockout.js

Incorporating knockout into my project has been a great help as I retrieve JSON objects using Ajax. One question that arises is how to effectively utilize this data in my custom JavaScript code: After receiving the mapped item from the ajax call, here is ...

Clarification on deconstructing Mobx objects for props

Is it possible to substitute { todoList } with props.todoList in the TodoListView component and also replace all instances of todoList with props.todoList to achieve the same outcome? import * as React from "react"; import { render } from "r ...

What is the best way to retrieve the index of an object within an array?

https://i.sstatic.net/We8lJ.pngHow can I retrieve the index of an object's array? https://i.sstatic.net/hmDKx.png I am looking to access the index of the items array within the form object. https://i.sstatic.net/OxePH.png When adding a new item row ...

Encountering the issue of receiving an undefined class when using the img tag in a

In my React.js project, I encountered an issue where the class for the img tag is appearing as undefined. The problem lies within the Header.jsx component. In this file, I am using the <img> tag but the CSS properties are not being applied to the ima ...

Will the bootstrap carousel continue running in the background even if I hide it?

Currently, I have incorporated the twitter bootstrap carousel into my website with the following code: <div id="slider" class="carousel slide"> <!-- Wrapper for slides --> <div class="caro ...

show a fresh new page using react router

I have recently developed a mobile app that showcases a collection of movies. Currently, it is static and I am looking to implement a react router for navigation. Specifically, I want the user to be directed to a detail page for a TV Show when they click o ...

Dilemma: Navigating the Conflict Between Context API and Next.js Routing in React

Recently, I was following a Material UI tutorial on Udemy and decided to set up a Context API in Create React App without passing down props as shown in the tutorial. Later on, when I tried migrating to Next JS with the same Context API, I started encounte ...

Generate unique IDP SAML replies

Currently, I am working on creating unit test cases for validating SAML responses. To achieve this, I am seeking guidance on generating multiple SAML responses in XML format using the necessary certificates and private keys. Are there any Node.js librari ...

Failure to achieve closure - even after thorough study of the concept

I have a countdown that I'm trying to get working during onload, but I'm running into issues with closures. Here is my code: Check out the fiddle here for (var o in myDates) { var myDate = myDates[o]; var iid = o; funcs[o] = function() { ...

Issue with showing error messages in view when using ejs templates

I am a beginner with node.js and I'm struggling to show error messages in the view using ejs templates. I want to display This user already exists. Here is my code: node.js router.post('/signup', (req, res) => { var username = req. ...

Below is a compilation of items found within the JavaScript object that include the data from the previous list

I am currently experiencing an issue where the values in the list of objects within some object only contain values from the last object. My goal is to assign scores to locations based on various criteria (which are stored in a separate list). To simplify ...

Is there a way to retrieve a single value using AJAX instead of returning the entire HTML page?

(edited after initial version) I'm facing an issue where my AJAX call is returning the header.php page instead of just the $result value which should be 0 or 1. The AJAX function calls generateTicket.php, where I want to generate tickets only if no o ...

Custom AngularJS directive for ensuring the selection of a required HTML element

Today brings another question as I continue working on my web application. I've encountered an issue with the 'required' attribute not being widely supported in major browsers. The attribute only works if the first option value is empty, whi ...

"Patience is key when it comes to waiting for an HTTP response

Looking for a solution in AngularJS, I have a service that calls the backend to get some data. Here is how the service looks: app.factory('myService', ['$http', '$window', '$rootScope', function ($http, $window, $ro ...