Tips for implementing dynamic templates within an AngularJS directive

I am looking to develop a dynamic directive. This directive will have a template with an input element, and this element's ng-model attribute needs to be dynamic, utilizing $scope.name in the controller.

app.directive('helloWorld', function() {
    return {
        restrict: 'E',
        replace: true,
        scope: {
              name: '@',
              path:'@',
        },
        template: '<input\
             type="text"\
             name="{{name}}"\
             ng-model="{{name}}"\
              />\,
        link: function(scope, elem, attrs) {

        },
        controller:{
          $scope.$watch($scope.name, function (newValue, oldValue) {
            }
        }
    });

Answer №1

Check out this functional JSFiddle

Code Example:

var app = angular.module('app',[])
app.directive('helloWorld', function() {
   return {
   restrict: 'E',
scope: {
     name: '@',
     path:'@',
  },

   template: '<input type="text" name="{{name}}" ng-model="name"/> {{name}}',
 controller: function($scope) {
   $scope.name = "default value";
   $scope.$watch('name', function (newValue, oldValue) {
       console.log("New Value: ", newValue);
   })
 }       

} });

Answer №2

Initially, there seems to be an issue with your directive syntax. Here is the corrected version:

app.directive('helloWorld', function() {
   return {
     restrict: 'E',
      scope: {
        name: '@',
        path:'@',
      },
     template: '<input type="text" name="{{name}}" ng-model="name">',
     link: function(scope, elem, attrs) {
  
     },
     controller: function($scope) {
       $scope.name = 'asd';
       $scope.$watch('name', function (newValue, oldValue) {

       })
     }
  }
});

Furthermore, if you wish to have a dynamic model, it is recommended to use scope: {name: '='} instead of @ which is for one-time binding.

update

Modified name="name in the template to name="{{name}}"

Check out this demo as well

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

Expanding the reach of the navigation bar

Hello Everyone, Is there a way to stretch my navigation bar so that the links are evenly spaced out across the browser window instead of being clustered together? I want it to be responsive rather than fixed in size. This is my HTML code: <div class= ...

Hover over or click to automatically focus on the input field

I have an icon that triggers focus on an input field when hovered over. I also want the same functionality to occur when the user clicks on the icon. if(!mobile){ $('#search-icon').hover( function(){ if($('.sear ...

What is the method to determine the size of an array of objects where each object contains its own internal array?

Here is the data that I have: var a=[ { name: "time", Details:[ {value:"month",checked:true,id:1} ] }, { name: "product", Details:[ {value: ...

Retrieve data from specified <td> element in an ASP.NET MVC application

Within my View, I am displaying data using a table. Below is the code snippet: @foreach (var item in Model) { <tr > // Table row content here... </tr> } I have buttons with ...

We apologize, but the module you are looking for cannot be found: Unable to locate 'fs'

Trying to create a new MDX blog website using Next.js 13 with the latest app router, but encountering an error message saying "Module not found: Can't resolve 'fs'". It was working fine in Next.js 12 and pages directory, but not in the lates ...

Using Javascript to fetch undefined data from a C# backend with AJAX

I am struggling to create a web page using Google charts. I attempted to build it with C# as a web form and retrieve data from a local database to JavaScript. However, I keep receiving an error stating that the data is undefined in the response from Ajax. ...

The best way to dynamically render HTML based on screen size using server-side rendering in Vue/Nuxt

Imagine having specific markup that should only be displayed on desktop using v-if. If the user is on mobile, a different content should be shown using v-else. The vue-mq package allows for setting a default breakpoint to use for server-side rendering. ...

React transmits an incorrect argument through the function

Having a bit of trouble passing a parameter alongside the function in my for loop to create SVG paths. The props are working fine with the correct 'i' value except for selectRegion(i) which ends up getting the final value of 'i' after t ...

Creating Tree diagrams with pie charts using D3

Has anyone tried creating a D3 pie component within each node of a tree? I've managed to build the tree and a single pie separately, but I'm struggling to combine them. My JSON data looks like this: window.json = { "health": [{ "value" ...

Incorporating user input into a div element

So, I'm in the process of building my own Task Tracker using JavaScript to enhance my skills, but I've hit a roadblock. I successfully implemented adding a new div with user-inputted tasks, however, there's no styling involved. <div cla ...

Is the Messenger Bot ignoring random users?

I am facing an issue that I need help explaining. The bot works perfectly when I use it from my own Facebook account. However, when I ask others to use it, the bot does not respond to them, even though I have received a green tick on the pages_messaging a ...

Utilizing Algolia search hits in conjunction with React Router: A guide

I'm currently utilizing Algolia’s react instant search feature, and I’m seeking guidance on how to implement a code snippet that will direct me to a designated page when a "hit" from the hits widget is clicked. My project is built using Next.js. ...

"Setting up a filter for the first row in an Excel-like table using a pin header

Does anyone know how to create a table filter in Excel where the header and first row stay pinned while scrolling down, even after applying filters? Here is a JSFiddle demonstrating the issue: http://jsfiddle.net/6ng3bz5c/1/ I have attempted the followi ...

Using jQuery to create a drop-down menu

I currently have a table filled with data. Whenever a user clicks on a cell within a specific column, I would like it to transform into a select dropdown menu. This dropdown menu will allow the user to choose a category for that particular row. The selecte ...

Using the Google Identity Services JavaScript SDK in conjunction with Vue and TypeScript: A comprehensive guide

I am currently working on authorizing Google APIs using the new Google Identity Services JavaScript SDK in my Vue / Quasar / TypeScript application. Following the guidelines provided here, I have included the Google 3P Authorization JavaScript Library in ...

Save all dynamically received data from a form in PHP as an array

I have developed a PHP form that dynamically adds new text variables in this manner: <form action="" enctype=”multipart/form-data” method="post" action="<?php echo $_SERVER['REQUEST_URI'];?>"> <div id="div"> va ...

Issues with alignment in Bootstrap Table columns

I'm facing an issue with formatting a table properly. Despite adjusting the colspans, I can't seem to get it right. There's an additional column header on the right labeled "Operations" that is extending outside the div, making it impossible ...

How come my _.some function consistently returns false when using lodash library?

Hello, I am new to learning and trying my best to understand. Here is the object that I am currently working with: $scope.selectedPartners =[ {"name" : "Abc", "selected" : true}, {"name" : "Abc", "selected" : true} ] Along with that, here is the loda ...

Using string.startsWith() with Wildcards or Regular Expressions

Currently in the process of refactoring code that relies on string.startsWith() in JavaScript. The documentation here does not mention the use of wildcards or Regular Expressions with this method. Is there an alternative approach I can take? ...

Updating a List Conditionally in React

Hello there! I am relatively new to the world of React and currently trying to grasp the concept of modifying elements within a list. Below, you'll find a straightforward example that illustrates my current dilemma. const numbers = [1, 2, 3, 4, 5]; / ...