AngularJS dynamic resources allow for web applications to access and

I have created a directive for a search form that provides a template with a <form> tag, automated messages such as "No results found," and an optional suggestion message like "You can search by name or id."

However, I am facing an issue where I need to reuse this directive for searching books, authors, or users on different pages of my application. I have set up resources (using ngResource) for each of them, so I want to dynamically pass these resources to my directive but I am unsure how to do so. Here is my code:

angular
    .module('my-app')
    .directive('searchForm', searchForm)
    .controller('searchFormController', searchFormController);

function searchForm() {
    return {
        restrict: 'E',
        scope: {
            info: '@'
        },
        controller: 'searchFormController',
        templateUrl: 'templates/directives/search-form.html'
    };
}

function searchFormController($scope, maybe_dynamic_resource_here) {
    $scope.results = [];

    $scope.searchSubmit = function(form){
        // perform the search here using the dynamic resource
    };
}

Here is my template:

<form name="searchform" ng-submit="searchSubmit(searchform)" novalidate>

<div class="wrapper-form center-block well">
    <div class="input-group">
        <input type="search" ng-model="search" name="search" class="form-control" required>
        <span class="input-group-btn">
            <button class="btn btn-default" type="submit">Search</button>
        </span>
    </div>
</div>

<!-- messages -->
<div class="msg-info" ng-show="info && !searchform.$submitted">
    <i class="fa fa-question-circle"></i> {{info}}
</div>

<div class="msg-info" ng-show="searchform.$submitted && !results.length">
    <i class="fa fa-exclamation-triangle"></i> No results found.
</div>
<!-- /messages -->

<card-of-results ng-repeat="result in results" />

</form>

To use my directive, I write:

<search-form
    info="You can search by name or id."
/>

Ideally, I would like to call the directive like this:

<search-form
    info="You can search by name or id."
    resource="Books" <-- this is how I specify the dynamic resource
/>

If there is a better way to achieve this functionality, any help would be greatly appreciated.

Thank you!

Answer №1

I comprehend your goal and will strive to offer a possible solution based on my experience.

Initially, I would establish a search factory.

.factory('SearchAPI', function ($resource) {
     return {
         search: function () {
             return $resource('search/:path/:id', {}, {
                 books: {
                     method: 'GET',
                     params: { path: 'books' }
                 },
                 authors: {
                     method: 'GET',
                     params: { path: 'authors' }
                 },
                 users: {
                     method: 'GET',
                     params: { path: 'users' }
                 }
             })
         }
     }
 });

Within my controller, the call will appear as follows:

The type will be either book, author, or user

$scope.searchSubmit = function(type){
      switch(type){
       case 'books' : 
         SearchAPI.search().books(function(data){

         });
        break;
        case 'authors' : 
           ......
    };
}

An alternative approach could be

.factory('SearchAPI', function ($resource) {
      return $resource('search/:path/:id', {}, {
              get: {
                  method: 'GET',
                  params: { path: '@path' }
              },
       });

});

Subsequently, your call would be simplified to:

$scope.searchSubmit = function(type){ 
       SearchAPI.get({path : type}).then(function(data){

        });
}

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

Next.js does not support loading jsx files

Recently, I have been exploring Next.js, which is currently considered to be the trending JavaScript framework. Eager to start practicing with it, I encountered a major roadblock as it refuses to run on my computer through any means. The standard way of c ...

Is there a way to use JavaScript to add content to a document and then facilitate the download of that document?

Is there a way in JavaScript to write content to a JSON or TXT file and then download it, similar to how it is done in Python? const content = "Hello"; const link = document.createElement('a'); link.setAttribute('download', 'FileTo ...

What could be causing a blank page to appear after being redirected? (Using NextJS 13 API Route)

After struggling with this issue for 2 days, I'm throwing in the towel and reaching out to the community for assistance. I've been tasked with setting up a basic login system for a new project using NextJS v13. However, it seems like a lot has c ...

Combining multiple data sources into a single input field in VueJs

I've been exploring the idea of incorporating multiple values into a vue form input binding Here's an example snippet of my code. <template> <div> <label for=""> Employee </label> <input class="form-contro ...

Restrict Angular 2 Component to specific ancestor Component

Is it possible in Angular 2 to restrict a Component so that it can only appear within a specific parent element on a page? In other words, the Component should only be allowed if it has a certain parent element. Here is an example: Allowed: <parent> ...

Trying out $window.location.href in Karma with Angular testing

I'm currently working on properly injecting the $window service into my Angular controller, and then testing to ensure that it redirects correctly. However, I'm running into an issue where I'm getting an error message that says undefined is ...

What steps do I need to take to successfully implement a $.fn. function that runs automatically when it is called?

I'm struggling with the following piece of code: function init() { var $contentButtonPanel: JQuery = $('#content-button-panel') $contentButtonPanel .find('.arbo .toggle, .collapsible-list li:has(ul) > ...

The domain retrieval is contingent on the language preference of the user

A task has been assigned to create a script in JavaScript/jQuery (or other suitable technologies) that will return a domain with a .pl extension if the user's browser language is set to Polish. Otherwise, the script should return a .eu domain extensio ...

How can I pass a JavaScript variable through the URL in a Rails 4 application to access it in the controller?

Struggling to pass the value of a JavaScript variable in the URL and then retrieve it in my Rails 4 app controller using param[:my_variable]. Despite trying various methods, none seem to work for me. I am unable to successfully pass my JavaScript variable ...

Tips for iterating through the properties of every object within a Knockout observableArray and dynamically generating a table

My observableArray is dynamically populated with SQL data, resulting in varying columns each time. I am trying to present the SQL results in an HTML table but facing issues with the code below. This is the desired output format... https://i.sstatic.net/ ...

Flask integration with AJAX for a HTML range slider

I'm currently facing a challenge with my HTML control panel that features an array of buttons and sliders. While the buttons are fully functional and trigger post requests that are received and executed by my Python app, I'm encountering issues w ...

Utilizing the options object within JavaScript functions: A step-by-step guide

My current task involves gathering input as an argument along with some objects. function display(parameter) { var text = parameter.text; var element = parameter.element; document.getElementById(element).innerHTML = text; } As part of this task, I a ...

How to clear a particular select option in react-bootstrap

I am looking for a solution to clear the second select when the first one selects option B. The clearing should involve removing the value, disabling it, and setting the default option to Select.... import React, { useState } from "react"; import ...

Guide to creating a functional Async API

I am currently facing a challenge while developing an application for my institution. I need to allow users to access database information (currently using firebase) from an external server, so I set up a node.js server to facilitate communication and hand ...

What advantages does event delegation in JavaScript offer compared to using jQuery's event handling?

Vanilla JavaScript: parentNode.addEventListener("click", function(event) { if (event.target === childNode) { code here } }); versus jQuery: $(parentNode).on("click", childNode, function() {}); ...

Display only one dropdown menu at a time

Hey there, I'm currently working on a dropdown menu and struggling to figure out how to keep only one item open at a time. I've tried using an array with useState for all my dropdowns but haven't been able to find a solution yet: code co ...

best way to return a function variable in JavaScript

Hey there, I've been working with react native and have run into a bit of an issue... const SignIn = () => { screensplash() fetch('http://api.megamouj.ir/api/v1/logincheck/', { method: 'POST', headers: { ...

Troubleshooting overload errors within ReactJS: tips and tricks

import React from 'react' import { Link } from 'react-scroll' import "./Protocol.css" import { ANALYTICS, TRADE, USERS, TRADERS, VOTES, ZEROES } from "../../Constants" const Protocol = () => { return ( ...

Navigating through a JSON array of objects within an array of objects in a React Fetch request: How can I effectively utilize mapping?

I successfully retrieved data from the API and was able to display it in the browser. However, I encountered difficulty handling an array of objects in JSON format. The API I used is for countries, some of which have multiple languages. My goal is to dis ...

Tips for Successfully Sending Vue Data in Axios POST Call

I'm struggling to pass Vue data to an axios.post request. Using the Vue template doesn't seem to work. How can I successfully pass the Data? Here is my Code: <body> <div id="app" class="container"> <div> ...