Adding an AngularJS directive dynamically that utilizes a $http request for fetching data

Currently facing an intriguing issue,

I am attempting to create something like this:

input key 1 , input value 1

input key 2 , input value 2 < button to add more >

< submit button >

Essentially, a user can click submit and send a Get request to a specific URL. When they click to add more, a new row will appear with two input fields where additional http get parameters can be added.

I have tried coding this out, but I am stuck at this point: http://jsfiddle.net/d2jL2n35/1/

Your assistance would be greatly appreciated...

Two inquiries:

  1. How can a new row be dynamically added after the plus box is clicked?

    myApp.directive('options',function(){
    return {
        restrict:"E",
        template:"<div><input placeholder='params1' type='text'/><input placeholder='params2' type='text'><button><i class='glyphicon glyphicon-plus'></i></button></div>"
    }
    

    })

Resolved the first query by using $compile: http://jsfiddle.net/KyEr3/216/

  1. How do you retrieve all the params and send a get request?????

Answer №1

Look at this basic example:

http://example.com/jsfiddle/abc123/

The key idea is to save each group of values in an array and utilize your directive to display them. I omitted the http call for simplicity, but in a real scenario, it might look something like this:

$http.get('/data').then( function( response ) {
    $scope.data = response;
} );

Answer №2

If you're looking for a similar setup, consider the following example:

Sample

Preview:

<div ng-app="myApp" ng-controller="mainController">
    <options parameters="parameters"></options>
</div>

Controller:

var myApp =  angular.module('myApp',[])
.factory('yourAPI', ['$http', function ($http) {
    var submitResults = function (parameters) {
        return $http.get("http://wwww.whateverURL.com?" + parameters.map(function(parameter){return parameter.key + "=" + encodeURI(parameter.val) }).join('&'));
    };   
    return {        
        submitResults: submitResults
    }
}])
.directive('options', function(){
    return{
        restrict:"E",
        replace:true,
        template: 
            "<div><option parameter='parameter' ng-repeat='parameter in parameters'></option>"+
        "<div>"+
            "<input type='text' placeholder='key' ng-model='newKey' /> " +
            "<input type='text' placeholder='value' ng-model='newVal' /> " +
            "<button ng-click='addItem()'><i class='glyphicon glyphicon-plus'></i></button>" +
        "</div>" +
        "<input type='submit' value='submit' ng-click='sendRequest()' /></div>",
        scope: { parameters:'='},
        controller: function($scope, yourAPI){            
            $scope.newKey="";
            $scope.newVal="";
            $scope.addItem = function(){
                $scope.parameters.push({key:$scope.newKey, val:$scope.newVal});
                $scope.newKey="";
                $scope.newVal="";        
            };
            $scope.sendRequest = function(){
                yourAPI.submitResults($scope.parameters).success(function(data, status, headers) {           
                    console.log(data);
                });
            }   
        }

    }
})
.directive('option', function(){
    return {
        restrict:'E',
        require: '^options',
        replace: true,
        scope: { parameter:'='},
        template: "<div>"+
                    "<input type='text' placeholder='key' ng-model='parameter.key' />" + 
                    "<input type='text' placeholder='value' ng-model='parameter.val' /></div>"
    }
})
.controller('mainController', function($scope){
    $scope.parameters=[];    
});

Please note that jsFiddle may block the get request, but this configuration should function in your application.

Answer №3

Congratulations on leveling up to LEVEL 2 AWESOME ANGULAR HACKER!

As a beginner, it might be beneficial to start with just one directive instead of two when your directives are small. Directives can be powerful tools but can also add complexity to your code.

To retrieve data from inputs, you can utilize ng-model (https://docs.angularjs.org/api/ng/directive/ngModel)

After pasting your options' template into your values template, you can add a click event using ng-click=addParam() to the button.

HTML:

<button ng-click="addParam()>

JS:

$scope.param1 = null;
$scope.param2 = null;

$scope.addParam = function () {
  $http.get('some url', {param1: param1, param2: param2}).success(data) {
     // add another option row
  };
}

In the addParam function, you will need to add another option row. One method is to use a for loop that creates a div for each ng-repeat, resulting in a template like this:

<div ng-repeat="n in noptions">
  <input placeholder="params1" ng-model="param1" /> 
  <button ng-click="addParam()>
</div>

To dynamically add another option row, increment noptions by 1 with $noptions += 1

https://docs.angularjs.org/api/ng/directive/ngRepeat

$scope.noptions = 0;

$http.get('some url', {param1: param1, param2: param2}).success(data) {
    $scope.noptions += 1;
};

By doing this, another option row will be dynamically added to your form.

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

Is there a way to automatically extract data from a CSV file and display it on a website using either PHP or JavaScript?

I have a web service link at www.xyz.com/abcdefg. When I visit this link, it automatically downloads a CSV file. The CSV file contains columns of data organized like this: Column A Column B Column C Column D test1 1 5 ...

A Guide to Organizing Vue Js: Dividing 'methods', 'data', 'computed', and More into Separate JavaScript Files

Is it feasible to separate methods, data, computed properties, etc. into individual .js files and then import them into a component.vue file? I prefer not to include all JavaScript logic in a single .vue component. My ideal code organization for each com ...

Prisma DB is a versatile database that excels in handling m-n

In my database, I have implemented a structure with 3 tables: Member, Characters, and MemberCharacters. Each member can have multiple Characters, and each Character can be used by multiple Members. To handle this many-to-many relationship, I have utilized ...

Finding the index of a chosen option in Angular

Attempting to retrieve the index of the selected option from a select element using Angular. The Angular (4) and Ionic 3 frameworks are being utilized. The template structure is as follows: <ion-select [(ngModel)]="obj.city"> <ion-option ...

Replacing text with new content when text is stored in a separate file

After organizing all the strings from my code, I compiled them into a file named constants.ts. export class Constants { public static API_URL = '/api/'; public static CREATE_CHILD_API_URL = Constants.API_URL + '%s' + '/create- ...

"Within Angular 2+, the attribute referenced is not recognized as a valid property, even though it is explicitly defined within the @Input

The main goal here is to increase the vertical pixel count. <spacer [height]="200"></spacer> Initially facing an issue where an error message states that height is not a recognized attribute of spacer. To address this problem, I set up the fo ...

Incorporating HTML with ng-binds through transclusion

I have been developing an angular directive to enhance the functionality of ng-table by adding filtering and exporting features. The main goal is to make this directive reusable for multiple tables, which requires the <td> elements to be dynamic. To ...

Update the link to a KML file used by Google Maps when a button is clicked

On the initial page load, I want to showcase an 8 Day Average KML file on Google Maps. However, users should have the option to click on the "1 Day" and "3 Day" buttons to switch the reference in Google Maps from the "8 Day" file. The aim is to design a s ...

ng-tags-input not functioning as expected with autocomplete feature

When I add a tag by selecting from a list populated using an $http request, the tag is added but the text that I have typed remains with an ng-invalid-tag class. Screenshots: 1) Initially: https://i.sstatic.net/g7K4U.png 2) Typing 3 letters to make an H ...

encountered empty values when retrieving static paths

I need to retrieve the values of slug and tags in my params. It's important to note that tags is not an array, but just a string. export async function getStaticPaths() { const chapters = await client.fetch( `*[_type == "chapters" & ...

Elements that are added dynamically do not contain any space between each other

I have a markup template that looks like this. <template id="unsequenced-template"> <button type="button" class="btn btn-primary railcar"></button> </template> Then, I use the following JavaScript ...

Error message encountered in node-schedule: Unable to read undefined property upon job restart

Using node-schedule, I have successfully scheduled jobs on my node server by pushing them into an array like this: jobs.push(schedule.scheduleJob(date, () => end_auction(req.body.item.url))); Everything is working as expected. When the designated date ...

Guide to sending back a promise using JQuery

Here is the Durendal code I am working with: var variable = ko.observable(""); function activate(){ return myModel.doSomething(variable); } The doSomething function looks like this: function doSomething(variable){ if(someCondition) return ...

Add a static line of names to a JavaScript file

Looking for a way to generate data with the following javascript snippet: for (var l = 0; l < table.length; l +=1) { fs.appendFile('results/Test'+ username +'.csv', var1+i, var2 , function(err) { if(err) { return c ...

Interactive selection menu with jquery technology

I am in the process of developing a dynamic dropdown feature using jQuery var rooms = $("<select />"); $(res.data).each(function () { var option = $("<option />"); option.html(this.name); op ...

Changing values in a select with multiple directives in AngularJs

Currently, I am developing a font selector directive using angularjs for an Umbraco property editor. Within the directive, there is a select element containing various fonts that are linked to the isolated scope. A peculiar issue arises when two directiv ...

Change the position of a Div by clicking on a different Div using JQuery for custom movements

I have successfully managed to slide the div left/right based on the answers below, but I am encountering some issues with the top div. Here are the specific changes I am looking to make: 1. Make both brown lines thinner without affecting the animations. ...

What is the best way to locate an element through its parent?

I am working with the following HTML structure: <div class="row" id="row-1"> <div class="row-wrapper"> <div class="cell-1"></div> <div class="cell-2"></div> <div class="cell-3"></div> ...

What are the proper ways to implement JavaScript conditions?

Having an issue with my slider function, as it currently only works once with the moveRight() method. To address this problem, I attempted to implement a condition that disables the move function and modifies the attributes of links on the second click. H ...

How can I use oboe.js to target a specific node instead of selecting all matching nodes?

Currently, I am receiving a JSON array through an http stream. The objects within this array are structured as follows: { "ID" : 1234, "Item" : { "ID" : "ABC123", "name" : "a thing" } } In reality, the objects are part of an array and look ...