The process of programmatically including ng-repeat within an element in an Angular directive

How can I add 'ng-repeat="n in counter"' to the 'form' tag inside my directive? I attempted to access the element via compile, but tElement.find('form') did not work as expected.

You can view my code here: http://jsfiddle.net/fea40v2c/1/

I experimented with different variations, such as:

console.log(tElement.find('form')); // fails
console.log(tElement[0].querySelector('form')); // null
console.log(document.querySelector('form')); // fails

Answer №1

Is it necessary for the add button to be defined by the user of the directive? If not, you can achieve the desired functionality like this.

<script id="repeatableForm.html" type="text/ng-template">
    <input type="button" value="add" ng-click="add()">
    <div ng-repeat="c in counter">
        <div ng-transclude></div>
    </div>
</script>

Update

After some adjustments, a solution was created that enables users to provide their own markup for the add button. It's slightly more complex and involves a nested directive. Some key points to note are:

  • The repeatableForm directive does not have an isolated scope. It alters the host scope by adding or overwriting the repeatableForm property, preventing multiple instances from running in the same host scope.
  • The controller of repeatableForm is made accessible in its host scope as the repeatableForm property. This approach keeps the host scope cleaner and provides namespace separation for controller methods.

The view

<repeatable-form>
    <input type="button" value="add" ng-click="repeatableForm.add()"/>
    <form action="">
        First Name: <input name="fname" type="text" />
        Last Name: <input name="lname" type="text" />
        <input type="checkbox" name="food" value="Steak"/> Steak
        <input type="checkbox" name="food" value="Egg"/> Egg
        <input type="button" value="remove" ng-click="repeatableForm.remove($index)" />
    </form>
</repeatable-form>

The directives

app.directive('repeatableForm', function () {
    return {
        templateUrl:'repeatableForm.html',
        restrict: 'E',
        transclude: true,
        controller: function () {
            var repeatableForm = this
            repeatableForm.add = function () {
                repeatableForm.forms.push(repeatableForm.forms.length + 1);
            };
            repeatableForm.remove = function (index) {
                repeatableForm.forms.splice(index, 1);                 
            };
            repeatableForm.forms = [1, 2, 3];
        },
        controllerAs: 'repeatableForm',
    };
});

app.directive('form', function () {
    return {
        templateUrl: 'repeatedForm.html',
        restrict: 'E',
        transclude: true,
    };
})

The templates

<script id="repeatableForm.html" type="text/ng-template">
    <div ng-transclude></div>
</script>
<script id="repeatedForm.html" type="text/ng-template">
    <div ng-repeat="form in repeatableForm.forms"><div ng-transclude></div></div>
</script>

See the demo.

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

Using AngularJS, you can display repeated elements in a single textarea by utilizing

--> I want to be able to input data into a textarea using just one textarea element. --> The reason for this is so that when the data in MySQL is updated, I can type new data in the textarea while still keeping the existing data. I have tried using ng-re ...

Best location for the classes of the Domain Model suggested

Currently, I am delving into Angular 2 and making use of angular-cli for creating components and services. Adhering to the directory structure suggested by angular-cli (view screenshot below), I am uncertain about where to include domain model objects like ...

Upgrade from AngularJS to the latest version of Angular, version 8

I'm trying to convert this AngularJS code into Angular 2+, but I'm having some trouble. Any ideas on how to do it? I've searched around, but this specific line is confusing me. scope.variable.value = event.color.toHex() Old Code: functi ...

Using an AngularJS directive to modify CSS styles

I'm attempting to modify DOM CSS styles using Angular. If the textbox value is set as the height, I have assigned ng-model to the textbox and then ng-style="{height:heightdef}" How can I achieve this using a directive? Fiddle :: http://jsfiddle.n ...

Verifying Function Calls in Angular Unit Testing: Handling Cleared $scope Elements

In my controller function, I have the following code: $scope.clearMarkers = function(){ for(var i = 0; i < $scope.markers.length; i++){ $scope.markers[i].setMap(null); } $scope.markers = []; }; The unit test I wrote for this code i ...

Unexpected behavior with ng-show binding

I am currently working on implementing a toggle feature in my form. The idea is that when I click one button, it should display a section with the corresponding name, and hide the other sections. However, I am facing an issue related to scope. When I do no ...

`No valid form submission when radio buttons used in AngularJS`

Within my form, I have a single input text field that is required (ng-required="true") and a group of radio buttons (each with ng-model="House.window" and ng-required="!House.window"). Interestingly, I've discovered that if I select a radio button fir ...

AngularJS Object Comparison: A Comprehensive Guide

My form initiates a GET request to the server upon loading, receiving data that is stored in 'master' and then copied to 'local' as shown below. $scope.dirty = false; init(data); function init(data) { $scope.master = angular.copy ...

Establishing the null values for input parameters

Whenever the button is clicked, I want to reset the input values to null. The function spremi() gets triggered when the button is clicked, but I want to set the values of podaci.tezina and podaci.mamac back to their initial values so that the user can en ...

Transforming JSON dates to Javascript dates using AngularJS and ASP.NET

How can I convert a JSON date /Date(1454351400000)/ into a proper date format using AngularJS and ASP.NET? $http.get('/home/GetProducts') .success(function (result) { $scope.products = result; }) .error(function (data) { ...

Top approach for inserting Class instance into a group

I need some guidance on how to approach this issue. I am interested in creating a set of objects similar to the example below: Person P = new Person(); P.Name = 'John'; P.Surname = 'Dough'; var People = []; People.push(P); Can this b ...

Is there a way to deactivate a button upon clicking and then substitute it with a new button that serves a different purpose in AngularJS?

Is there a way to deactivate a button once clicked and substitute it with another button that performs a different task using AngularJS? Here is the button in question: <button type="submit" class="btn btn-small btn-default" ng-disabled="isteam==0 || ...

Tips for transferring the currently signed in user id to the resolve block in the ui-router state (AngularJS)

Seeking assistance with passing the currently signed-in user to the resolve block of a 'user' state using ui-router. The objective is to have the user's id in the URL like .../users/:id after sign-in. The nested routes are inside the :user ...

Looking to transfer a file to a server with the help of angularJS, NodeJS, and ExpressJS

I attempted to use the instructions provided in this link but encountered an error The version of Node I am using is 4.4.7, and I received a modulerr error regarding ngFileUpload In order to upload files in app.js var multer = require('mul ...

Is it necessary for karma.conf.js to be located at the root of the application at all times?

My experience with building ng applications using just Angular has been centered around a typical structure like this: app js home home.controller.js home.directive.js shared usedByAll.cont ...

Prepare for a thorough cross-referencing session

In my attempt to create a tool with 3 inputs that are interdependent - "Earn %", "Earn $" and "Own Price". Initially, the default value for "Earn percentage" is set at "10", making the initial calculation function as intended. Changing this one value auto ...

Utilize ng-options to iterate through a dictionary object

I have an object called "a" that I need to loop through using ng-options: var a = { 'optionName1': 'optionValue1', 'optionName2': 'optionValue2', 'optionName3': 'optionValue3', 'optionName4& ...

Unable to receive notifications within an AngularJS service

<!DOCTYPE html> <html> <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script> <body> <div ng-app="canerApp" ng-controller="canerCtrl"> <button ng-click="click()"> ...

"Encountering timeout issues with Angular's resource module

I've encountered an issue where a database query called from the backend through the page controller seems to cause an error if it doesn't return immediately. I'm not sure whether the problem lies with Angular or Node.js. Just so you know, ...

Sending unchanging data from html to an AngularJS application

Is there a way to efficiently transfer static configuration data from a server (using .NET, PHP) to an Angular application without relying on web services? I came across a solution involving a generated javascript block, but I'm looking for alternati ...