Inserting variables into Angular queries

I am encountering a dilemma on how to insert a variable from an array into a query string. The filter function is functioning properly, but the search function seems to be ineffective. The variable 'id' successfully retrieves the id from the selected user, however, the subsequent 'vm.search' does not yield any results. As I am relatively new to Angular and JavaScript, I might be overlooking something quite simple. Below is my code snippet:

(function () {
'use strict';

angular
    .module('app.pil')
    .controller('userListController', ctrl);

ctrl.$inject = ['$rootScope', 'users', 'pilService', 'notificator'];

function ctrl($rootScope, users, pilService, notificator) {

    var vm = this;

    vm.filter = function () {
        vm.users = users;
        vm.users = pilService.filter.query(vm.data);
    };

    vm.search = function () {
        var id = vm.users[0].id;
        vm.search = pilService.search.query(id);
    }

}

})();

Thanks for any insights!

pilService code:

(function () {
  'use strict';

  angular.module('app.pil').factory('pilService', service);

  service.$inject = ['CONFIG', '$resource'];
  function service(CONFIG, $resource) {

    var users = $resource(CONFIG.API_END_POINT_URL + '/pil/api/pilot/clients', {}, {
      query: {isArray: true},
      update: {method: 'GET'}
    });

    var filter = $resource(CONFIG.API_END_POINT_URL + '/pil/api/pilot/clients/filter', {}, {
        query: {isArray: true},
        update: {method: 'GET'}
    });

    var search = $resource(CONFIG.API_END_POINT_URL + '/pil/api/pilot/clients/search', {}, {
      query: {isArray: true},
      update: {method: 'GET'}
    });

    return {users: users,
            filter:filter,
            search:search
    }
  }
})();

Answer №1

It seems like there is a conflict between your function name vm.search = function () and the ng-model name vm.search. This might be causing Angular to become confused when trying to perform the binding action.

I suggest defining the names separately and then checking if everything is working properly.

Answer №2

After facing a challenge, I found a solution that may not be perfect, but it does the job. It turns out that the issue was with how the id was set as a String instead of an array. To resolve this, I modified my code to:

vm.search = function (user) {
          vm.id =  gpilotService.search.query(user);
        }

By implementing this change, the front end now sends the entire user object with all its arrays as parameters, while the back end only extracts the ID.

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 your CPU overheating due to IE7, encountering script issues, and need help with debugging

My current web design project is running smoothly on all Mac browsers and Windows Firefox, Chrome, and IE 8. However, I'm facing significant issues with IE 7. Despite having the CSS almost in place with a few adjustments needed, the CPU usage spikes t ...

Vue alert: The instance does not have a defined "hp" property or method, but it is referenced during rendering

Below is the code snippet that I am currently working with: var example1; var hp = ["p"]; document.addEventListener("DOMContentLoaded", function(event) { hp = ["x"]; example1 = new Vue({ el: '#example-1', data: { iLoveMysel ...

Verify the accuracy of quiz responses with PHP and AJAX

I am working on a picture quiz that has one input field for each image. I am looking for a solution to verify if the value entered into the input field matches the correct answer. If it does match, I need to perform certain operations like adding or removi ...

Why do query values disappear when refreshing a page in Next.js? [Illustrative example provided]

In my current project, I am developing a simple Next Js application consisting of just two pages. index.tsx: import React from "react"; import Link from "next/link"; export default function Index() { return ( <di ...

Create a regular expression that matches a combination of alphabets and spaces, but does not allow for

Can anyone provide a regular expression that allows for a combination of alphabets and spaces, but not only spaces? After searching extensively and reading numerous articles, I came across the expression /^[a-zA-Z\s]*$/, which unfortunately permits j ...

Ways to display or conceal various divs by employing an if/else statement?

I am aiming to conditionally display various divs based on certain criteria: Show the "x" div if it's not already visible Display the "y" div only if the "x" div is already being displayed Show the "z" div only if both the "x" and "y" divs are alrea ...

The function causes an unexpected alteration in the coordinates of polygons on a leaflet map

I have been working on enhancing the functionality of a leaflet map by adding triangles with specific rotations to each marker that is created. The code snippet below demonstrates how I achieve this: function add_items_to_map( to_map, longitude, latitude, ...

How can I pass $scope between controllers in AngularJS?

Just starting out with Angular Js. Can I pass the scope of the RestaurantController to the MenuController like this? For example: angular.module('restaurants').controller('RestaurantController', ['$scope', function($sco ...

Is it possible to test an Angular application using Protractor within an iframe that is hosted by a non-Angular

While trying to migrate a legacy app to Angular, we encountered an issue where the legacy app loads the new app in an iframe. Testing this integration with Protractor has proven challenging due to the fact that the legacy app is not built on Angular. If t ...

The ngFor directive is not compatible with third-party library elements

I am currently working on an Angular application that utilizes a UMD library for the user interface. However, I have encountered a problem where I am unable to use the ngFor directive on an element from the library. Here is an example: <lib-select> & ...

Tips for preventing automatic sliding in a bootstrap 4 carousel on mobile with JavaScript or other methods

Can someone assist me in stopping my carousel from auto-sliding on mobile devices only? I have attempted solutions from similar queries on this platform, but they have not worked for me. Any suggestions would be greatly appreciated. Below is an example of ...

Create a generic function that retrieves a specific property from an array of objects using the select method

Currently, I have implemented four functions that select entries from an array based on different properties. if ($scope.filters.filter1) $scope.filteredEntries = $scope.filteredEntries.filter(function (o) { return o.field1 === $scope.filt ...

Manipulate objects in three.js to always face the mouse pointer

It seems that despite my efforts, I am struggling with this task as I am relatively new to it. Surprisingly, I am not getting any errors in Dreamweaver. I've started fresh by integrating the look at function with the OBJ loader, camera, and lights in ...

Discover the dynamic method for determining the value of a nested array based on a specific condition

Currently, I am delving into the world of nested arrays and attempting to locate a specific value within the array based on a condition. The data returned by the API is structured in the following format: data= { "ch_Id": "1234", "title": "Title" ...

What could be the reason for the unexpected "undefined" return value of this custom hook in

I've been working on creating a custom hook in React and here's the code I have so far: import {useEffect} from 'react'; const useFetch = (url) => { useEffect(() => { const fetchData = () => { const dat ...

The command 'ng' is not a valid internal or external command, and it cannot be run as an operable program or batch file on the Mean Stack platform

Hey there, I'm in the process of developing a meanstack application. Every time I try to run 'ng new client' command, it gives me an error saying 'ng' is not recognized as an internal or external command, operable program or batch ...

Difficulty transmitting Heroku environment variable to Angular CLI application using Node.js

Currently, I am tackling a project that requires passing a stripe key as JSON within Angular. I've stored the key in Heroku config vars and have been attempting to pass that value through the Node.js backend to Angular using the process.env.STRIPE_KE ...

Best practices for running Javascript based on PHP output

I'm trying to figure out how to add a PHP Exception to my JavaScript function that sends form data to a database. I want it to work like this: "if 'whatever' condition is met, execute the JavaScript function; otherwise, throw an Exception me ...

Creating new Angular2 Observables - Subscribing to undefined developments

Is it a scoping issue or a problem with how my observables are set up? Can you assist me in figuring it out? To explain my logic: My goal is to first check if the data is available locally before making an http.get request for it. I want to return the loc ...

The API response in JSON format is displaying as "undefined"

My current code is running as follows: const request = require('request') const apiKey = 'XXXXXXXXXXXXXX' var dat; let url = 'http://api.worldweatheronline.com/premium/v1/marine.ashx' let qs = { q: '-34.48,150.92&ap ...