Attempting to send $scope.data into a parameter object when transferring from controller to service within Angular framework

Within my index.html file, the following code exists:

<input type="text" ng-model="title" placeholder="Search..." >
<button type="submit" href="#" ng-click="getSearch()">Submit</button>
<select ng-model="selected" ng-options="obj.val as obj.display for obj in things"></select>

Accompanied by my controller implementation:

$scope.getSearch = function(){
   svc.search($scope.selected)
    .then(function(response){
     $scope.searchData = response;
     });
  };

$scope.things = [
  {display: 'Movie',
  val: {s: $scope.title}},
  {display: 'Series',
  val: 'series'},
  {display: 'Epsiode',
  val: 'episode'},
];

Lastly, my service holds the following logic:

this.search = function(params){
  return  $http.get('http://www.omdbapi.com/',params)
    .then(function(response) {
     var results = response.data.Search;
     return results;
   });
  };

Seems like everything is nearly operational. The only hiccup is with how the params are encoded when communicating with omdbapi.

  $scope.getSearch = function(){
svc.search($scope.selected())
.then(function(response){
  $scope.searchData = response;
});


};

  $scope.things = [
  {display: 'Movie',
  val: function(){return {'type=movie&s': $scope.title};}},
    {display: 'Series',
    val: function(){return {'type=series&s': $scope.title};}},
  {display: 'Epsiode',
  val: function(){return {'type=episode&s': $scope.title};}},
];

And success! Finally cracked it after a long troubleshooting session.

  val: function(){return {type: 'movie',s: $scope.title};}},

Answer №1

Here's a simple guide for you to follow. It's really easy and uses a nice movie API.

<!DOCTYPE html>
<html ng-app="plunker">

<head>
    <meta charset="utf-8" />
    <title>AngularJS Plunker</title>

    <link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
    <script>document.write('<base href="' + document.location + '" />');</script>
    <script data-require="<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="71101f16041d10035f1b0231405f455f455af7">[email protected]</a>" src="https://code.angularjs.org/1.4.9/angular.js" data-semver="1.4.9"></script>

</head>
    <body ng-controller="MainCtrl">
        <div class="container">
            <div class="row">
                <div class="col-lg-3">
                    <form>
                        <div class="form-group">
                            <label>Choose type</label>
                            <select class="form-control" ng-model="title">
                                <option ng-repeat="x in things">{{x.type}}</option>
                            </select>
                        </div>

                        <div class="form-group">
                            <label>Title (Minimum 2 chars) : </label>
                            <input type="text" ng-model="search_keyword" class="form-control"/>        
                        </div>

                        <button class="btn" ng-click="search_movie()">
                            Search movie
                        </button>
                    </form>      
                </div>            
            </div>
        </div>
        <div class="container">
            <pre>
            {{result | json}}
            </pre>    
        </div>

    </body>
</html>

<script type="text/javascript">
    var app = angular.module('plunker', []);
    app.controller('MainCtrl', function($scope,$http) 
    {   
        $scope.search_keyword = '';
        $scope.title = '';

        $scope.things = [{type:'movie'},{type:'series'},{type:'episode'}];   

        $scope.search_movie = function()
        {
            console.log($scope.search_keyword+""+$scope.title); 

            $http.get('http://www.omdbapi.com?t='+$scope.title+"&h="+$scope.search_keyword)
            .then(function(response) 
            {
                $scope.result = response.data;
            });  
        }

    });
</script>

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

Ensure both mouse clicks and pressing the enter key are functional for improved accessibility

Consider the following form with a tabindex property: <form id="settings-form"> <input type="text" /> <input type="submit" /> <a href="#" class="cancel-save" tabindex="0">cancel</a> </form> An action is bou ...

Having trouble parsing JSON with Ajax in Pusher using PHP?

I am facing an issue while sending multiple parameters using the Pusher AJAX PHP library. This is the error I encounter: SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data Here is my PHP and JS code: <script src="https: ...

Setting an environment map in Three.js can replace the original texture on a model

I'm having trouble setting an environment map to an OBJ model. It seems like the appearance has changed drastically! In its usual view, it looks like this: https://i.sstatic.net/4VcIG.png But when I set the environment map, it transforms into this: ht ...

Refining a JQuery scroll animation using mouseover functionality

I came across a JQuery scroll animation (inspired by this specific answer to a similar question that almost perfectly suited my requirements), and I managed to get it working. My goal is to achieve a side-scroll effect of icons when the user hovers over th ...

My function invocations seem to be malfunctioning

Originally, I wrote code without using functions to prototype and it worked perfectly fine: $(function() { $(".PortfolioFade img") .mouseover(function() { popup('PORTFOLIO'); var src = $(this).attr("src").rep ...

Extra Pathway

Having trouble adding a second route to the /privacy page. The error "Cannot GET /privacy.html" keeps popping up. Any suggestions? This code seems to be failing to display the privacy.html content app.get('/privacy', function(req, res) { res.s ...

I am experiencing issues with my React implementation of the bootstrap carousel

My carousel seems to be having some issues and I'm not sure what's causing it. Can someone provide guidance on how to resolve this problem? Here is the link to my code on Codesandbox: https://codesandbox.io/s/nice-heyrovsky-8yucf?file=/src/Prompt ...

The state remains constant on the PrivateRoute Component

I am currently working on creating a private router component for my application. Below is the code I have written. const history = createBrowserHistory() class PrivateRoute extends Component { constructor(props) { super(props); this.state={auth ...

Using Vue to append elements that are not part of the loop

While looping over a table row, I realized that each of the table rows should be accompanied by another table row containing additional data from the loop. Unfortunately, I am struggling to insert <tr class="data-spacer"></tr> <tr& ...

Having trouble with AngularJS - struggling to diagnose the issue

HTML Page <head> <title>TODO supply a title</title> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <script src="assets/js/angular.min.js"></script> ...

How to access an array mapped to a specific key within an object in JavaScript

Is there a way to access an array mapped to a specific key in a JavaScript object? data = {}; data.key = 'example'; data.value = 'test'; data.list = [111, 222, 333]; Viewing the list of items works fine: alert(data.list); // displays ...

Attempting to evaluate objects for the purpose of identifying differences and adjusting the range of updates accordingly

I'm struggling to figure out the best way to handle this situation in my code. I need to compare data from the database and update the scope if it has changed, but for some reason it always detects a difference and triggers the update: $scope.tickets ...

What is the best way to incorporate a button in my code that automatically triggers changes at regular intervals?

Is there a way to automatically change the color of my working traffic light in JavaScript on a timed basis, rather than relying solely on button clicks? Here is the current code I am using: <!DOCTYPE html> <html> <head> <style> # ...

Utilizing the $cond operator within a subset in MongoDB/Mongoose aggregation operations

Imagine having the following data in a document: { "_id" : 1, "first_name" : "Matt", "roles": ['editor', 'publisher', 'siteAdmin'] } { "_id" : 1, "first_name" : "Harry", "roles": ['publisher', 'siteAdmin'] ...

Navigating a collection of objects after a button is clicked

My current library project involves looping through an array of objects to display them on a grid based on input values. Here is the code snippet for my loop: const addBook = (ev) => { ev.preventDefault(); let myLibrary = []; let bookIn ...

Tips for resizing an object in a single direction using THREE.JS

I have encountered an issue while adding a cube to my scene using THREE.JS. When I try to change the height of the cube by increasing its y coordinate, it also seems to expand in the negative y direction as well. var cubeGeometry2 = new THREE.BoxGeomet ...

A guide on accessing the JSON file data using jQuery

Currently, I am attempting to retrieve data from an API. Essentially, there is a URL that returns JSON data which I need to utilize. var url = "http://212.18.63.135:9034/played?sid=1&type=json"; $.getJSON(url, function(data) { console.log(data) ...

Incorporating an NPM JavaScript library into Laravel version 8

I've integrated the mobiscroll javascript component library into my new Laravel 8 app by adding the minified css/js files to the public/css and public/js directories. However, I'd like to find a more seamless way to include these components by us ...

How to retrieve the content of a textarea element without knowing its id?

I am struggling to retrieve the value of a textarea whose id is dynamically populated with values from a database. How can I achieve this using jQuery? function updateTextarea(textarea, updateUrl) { var field = textarea.attr("data-field"); var id ...

unable to assign values to this.props (appears as undefined or an empty array)

Upon setting up react/redux, I encountered a peculiar issue. When my component mounts, it should render the information stored in this.props.heroes.data. However, upon logging this data, I receive an unexpected value of [{id:1,heroname:'Batman',r ...