Utilizing a drop-down menu in AngularJS to dynamically change a URL and fetch images

Currently, I am in the process of creating a website using AngularJS that accesses images from reddit and showcases them based on various parameters such as number of votes and date posted. While this is not groundbreaking, my main goal is to enhance my skills with Angular. At this point, I have managed to make it function by hardcoding the subreddit page into the controller line as shown below:

  $http.jsonp('http://reddit.com/r/pics.json?jsonp=JSON_CALLBACK').success(function(response) {

However, I am facing difficulty in changing the URL dynamically. I have created a $scope.subreddit in the controller along with a dropdown for selecting the desired subreddit, but it is not functioning properly.

This is what my index.html looks like:

<!doctype html>
<html lang="en" ng-app>
<head>
  <meta charset="utf-8">
  <title>Reddit Picture Viewer</title>
  <link rel="stylesheet" href="css/app.css">
  <link rel="stylesheet" href="css/bootstrap.css">
  <script src="lib/angular/angular.js"></script>
  <script src="js/controllers.js"></script>
</head>
<body ng-controller="RedditPosts">

  <div class="container-fluid">
    <div class="row-fluid">
      <div class="span2">
        <!--Sidebar content-->

        Search: <input ng-model="query">
        Sort by:
        <select ng-model="orderProp">
          <option value='data.score'>Most Down Votes</option>
          <option value='-data.score'>Most Up Votes</option>
        </select>
    Subreddit:
        <select ng-model="subreddit">
          <option value='pics'>pics</option>
          <option value='earthporn'>earth</option>
          <option value='spaceporn'>earth</option>
        </select>

      </div>
      <div class="span10">
        <!--Body content-->

        <ul class="Post">
          <li ng-repeat="entry in Post.children | filter:query | orderBy:orderProp ">
    <a href="{{entry.data.title}}" class="thumb"><img ng-src="{{entry.data.url}}"  height="250" width="250"></a>
    {{entry.data.ups}}
    {{entry.data.downs}}   
         </li>
        </ul>

      </div>
    </div>
  </div>
</body>
</html>

And here is the controller code:

'use strict';

/* Controllers */

function RedditPosts($scope, $http) {
  $http.jsonp('http://reddit.com/r/pics.json?jsonp=JSON_CALLBACK').success(function(response) {
    $scope.Post = response.data
  });

   $scope.orderProp = '-data.score';
   $scope.subreddit = 'pics';
}

Answer №1

If you include the variable in your URL, you can then fetch new posts every time it changes.

For instance: http://jsfiddle.net/TheSharpieOne/x8XXR/1/

function RedditPosts($scope, $http) {
    $scope.orderProp = '-data.score';
    $scope.subreddit = 'pics';
    $scope.updatePosts = function () {
        $http.jsonp('http://reddit.com/r/'+$scope.subreddit+'.json?jsonp=JSON_CALLBACK').success(function (response) {
            $scope.Post = response.data
        });
    };
    $scope.updatePosts();
}

Include ng-change to automatically trigger an update when the variable is changed.

            <select ng-model="subreddit" ng-change="updatePosts()">
                <option value='pics'>pics</option>
                <option value='earthporn'>earth</option>
                <option value='spaceporn'>earth</option>
            </select>

Please note that the orderProp aspect was not fully clarified in the post, focusing only on pics.

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

Issue: unable to establish a connection to [localhost:27017]

Upon executing node app.js, an error message is displayed: Failed to load c++ bson extension, using pure JS version Express server listening on port 3000 events.js:85 throw er; // Unhandled 'error' event ^ Error: failed to conn ...

Ways to retrieve a single $interval() invocation from the controller

In order to ensure my controller refreshes certain services (by calling a webservice) every minute, I implemented the following code: angular.module('App').controller('dashboardCtrl', function($scope, $interval, ServiceOne, ServiceTwo, ...

Showing all elements on page load that are currently being filtered out in React

I've created a page that displays a grid of images with various details like title, description, author, and more. All this data is being pulled from my SQL table (referred to as marketplaceData). To enhance user experience, I added a search bar to f ...

DailyCodingChallenge: Discover two elements in an array that add up to a specified value

As someone who is relatively new to coding, I recently signed up for the daily coding problem mailing list and received the following question: If given a list of numbers and a specific number k, can you determine whether any two numbers from the list a ...

How can I retrieve the controller variable of a class within an angular material $mdDialog.confirm()/prompt()?

Can the value of this.status be changed after confirming a dialog with either answer? class ComponentCtrl { constructor($scope, $reactive, $mdDialog) { 'ngInject'; $reactive(this).attach($scope); this.$mdDialog = $md ...

Steps for adding an onclick function to a collection of div elements

My current project involves utilizing the Flickr API and I am interested in creating a popup div that opens when clicking on each image. The goal is to display the image in a larger form, similar to how it's done using Fancybox. I'm looking for ...

Discover the best way of utilizing the `ng-class` directive for adding and removing classes!

When using the ng-class to dynamically add and remove a class by clicking a button in Angular1, I am encountering some issues. What could be causing this problem? <html lang="en" ng-app="xxx"> <head> <meta charset="UTF-8"> <ti ...

When there is only one value, the BehaviorSubject can be hit multiple times

Recently, I implemented BehaviourSubject in a shared service to retrieve the current value when clicking a button. Everything seems to be working fine, however, there are instances where the API call within the subscribe block of BehaviourSubject is being ...

Issue specifically with Android 6 WebView - jQuery 1.9.1 where a RangeError is thrown due to the call stack size being exceeded

An error message "Uncaught RangeError Maximum call stack size exceeded" is causing a web application to fail in the jQuery-1.9.1 extend() function, but strangely it only occurs on Android 6. The application runs smoothly on all other platforms such as Des ...

Creating dynamic forms in Vue using v-for

I'm currently experimenting with creating dynamic form fields using v-for and vuex. My approach involves nesting a v-for inside another v-for. The process of adding new form fields works smoothly, but I encountered an issue when attempting to delete t ...

In React Router version 4, it is stated that each router is only allowed to have a single child element when using multiple routes

I'm currently working on implementing a sidebar alongside the main content area using react-router-dom. Instead of just rendering <Sidebar/> directly, I want to pass it the location prop due to another issue where clicking a <Link/> in the ...

Create a fresh instance of an object in node.js by utilizing the require/new method

I am encountering a beginner problem with node.js where I cannot seem to create objects using the 'new' operator in the index.js file. My goal is to define a simple Person object within a Person.js file, located in the same directory as my index ...

No content in Axios response

axios.post( 'http://localhost:3001/users', { username:user.username } ).then((res)=> console.log(res.data)) Response From FrontEnd : data: &qu ...

What is the reason behind the non-reversible nature of atob and btoa

Looking for a simple way to obscure answers to quiz questions in Markdown temporarily? The idea is to reveal the answers during the presentation, no need for secure encryption. Considered using atob('message I want to obfuscate') and letting stu ...

Issue with Vue: Calling method instantly when using :mouseover in v-for within a component

Whenever I try to incorporate :mouseover in a v-for loop within the <component>, I encounter an issue. The method assigned to the :mouseover event is triggered for each element, rather than just for the hovered elements. <Single-technology ...

Utilizing Ajax, Jquery, and Struts2 for File Uploading

Can someone please provide guidance on uploading files using a combination of Ajax, jQuery, and Struts2? I have searched through numerous tutorials online but haven't found a suitable solution yet. The goal is to trigger a JavaScript function when a b ...

Tips for using the deferred method in ajax to enhance the efficiency of data loading from a php script

I recently discovered this method of fetching data simultaneously using ajax. However, I'm struggling to grasp the concept. Can someone please explain how to retrieve this data from a PHP script and then add it to a div similar to the example provided ...

Angular is unable to fulfill the promise

I have developed a new service to establish communication with a server using $http.post. app.factory("dataService", [ "$http", "$q", function ($http, $q) { function post(url, data) { var deferred = $q.defer(); $http.p ...

Tips on fetching the ID of the selected option using JavaScript without relying on jQuery

Looking to print the selected option ID using pure Javascript (not JQuery) for multiple select tags. If we have more than one select tag, how do we achieve this? <select onchange="showOptions(this)" id="my_select1"> <option value="a1" id="ida ...

Increase the jQuery Array

After successfully initializing an Array, how can I add items to it? Is it through the push() method that I've heard about? I'm having trouble finding it... ...