Utilizing AngularJS for Managing JSON Data

I'm facing a new challenge and need some assistance. My goal is to create 9 buttons and a panel that will display movie details based on the button clicked. For example, if I click 'Transformers', I want the panel to show details about Transformers. If I then click 'Fury', I want the panel content to switch to Fury's details. To achieve this, I plan to store the data in a JSON file. However, I am struggling to figure out how to implement this. Here is my current progress:

JS:

var app = angular.module("myApp", []);

app.controller('MainController', ['$scope', function ($scope) {

}])

JSON:

{
  "movie": [
  {
    "id": 1,
    "name": "Star Wars The Phantom Menace",
    "format": "DVD",
    "rate": 4,
    "price": 2
  },
  {
    "id": 2,
    "name": "Star Wars A New Hope",
    "format": "DVD",
    "rate": 6,
    "price": 4
  },
  {
    "id": 3,
    "name": "Transformers",
    "format": "Blu-Ray",
    "rate": 7,
    "price": 3
  },
  {
    "id": 4,
    "name": "Transformers Dark of the Moon",
    "format": "Blu-Ray",
    "rate": 6,
    "price": 5
  }
]}

HTML:

  <body ng-controller="MainController" ng-app="myApp">
    <h1 style="text-align:center">Garrett's Rentals</h1>

    <div ng-repeat="movie in movies">
      <button>{{movie.name}}</button>
    </div>

    <div class="panel">
      <h3>You have selected:</h3>
      <p>{{movie.name}}</p>
      <p>{{movie.format}}</p>
      <p>{{movie.rate}}</p>
      <p>{{movie.price}}</p>
    </div>
  </body>

Answer №1

utilize

let application = angular.module("myApp", []);

application.controller('MainController', ['$scope', function ($scope) {
    let json={
  "movie": [
  {
    "id": 1,
    "name": "Star Wars The Phantom Menace",
    "format": "DVD",
    "rate": 4,
    "price": 2
  },
  {
    "id": 2,
    "name": "Star Wars A New Hope",
    "format": "DVD",
    "rate": 6,
    "price": 4
  },
  {
    "id": 3,
    "name": "Transformers",
    "format": "Blu-Ray",
    "rate": 7,
    "price": 3
  },
  {
    "id": 4,
    "name": "Transformers Dark of the Moon",
    "format": "Blu-Ray",
    "rate": 6,
    "price": 5
  }
  ]};
console.log(json);
$scope.movies=json.movie;
    console.log($scope.movie);
}]);

XHTML

    <body ng-controller="MainController" ng-app="myApp">
    <h1 style="text-align:center">Garrett's Rentals</h1>

    <div ng-repeat="movie in movies">
      <button>{{movie.name}}</button>
    </div>

    <div class="panel">
      <h3>You have selected:</h3>
      <p>{{movie.name}}</p>
      <p>{{movie.format}}</p>
      <p>{{movie.rate}}</p>
      <p>{{movie.price}}</p>
    </div>
  </body>

Support Fiddle:http://jsfiddle.net/sXkjc/993/

Answer №2

Implement the ng-click directive on a button to dynamically set the currently selected movie as shown below:

var app = angular.module("myApp", []);

app.controller('MainController', ['$scope', function ($scope) {
   $scope.movies= movies; // The variable movies represents your JSON object
   $scope.selectedMovie=$scope.movies[0]; // Assume that the first movie is selected by default
}])

HTML

<div ng-repeat="movie in movies">
  <button ng-click="selectedMovie=movie">{{movie.name}}</button>
</div>

<div class="panel">
  <h3>You have selected:</h3>
  <p>{{selectedMovie.name}}</p>
  <p>{{selectedMovie.format}}</p>
  <p>{{selectedMovie.rate}}</p>
  <p>{{selectedMovie.price}}</p>
</div>

Answer №3

JavaScript

angular.module('myApp', [])

.controller('MainController',['$scope','$http',function($scope,$http){


  $scope.data = null;
  $http.get('URL TO JSON').then(function(response){
    console.log('Success', response);
    $scope.data = response.data;


  },
  function(error){
    console.error('Error', error);
  })

}]);

HTML

<body ng-controller="MainController" ng-app="myApp">
<h1 style="text-align:center">Garrett's Rentals</h1>

<div ng-repeat="movie in movies">
  <button>{{movie.name}}</button>
</div>

<div class="panel">>
  <h3>You have selected:</h3>
  <p>{{movie.name}}</p>
  <p>{{movie.format}}</p>
  <p>{{movie.rate}}</p>
  <p>{{movie.price}}</p>
</div>

Answer №4

Angular Controller Code:

var app = angular.module("movieApp", []);

    app.controller('MovieController', ['$scope', function ($scope) {

        $scope.movies = {
            movieList: [
                {
                    id: 1,
                    name: "The Matrix",
                    format: "DVD",
                    rate: 8,
                    price: 3
                },
                {
                    id: 2,
                    name: "Inception",
                    format: "Blu-Ray",
                    rate: 9,
                    price: 5
                },
                {
                    id: 3,
                    name: "Pulp Fiction",
                    format: "DVD",
                    rate: 7,
                    price: 4
                }
            ]
        }

        $scope.selectMovie = function(movie) {
            $scope.selectedMovie = movie;
        }

    }])

HTML Structure:

<html ng-app="movieApp">

    <head>
        <link rel="stylesheet" href="styles.css">
        <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.7.9/angular.min.js"></script>
        <script src="app.js"></script>
    </head>


    <body ng-controller="MovieController" >
        <h1 style="text-align:center">Movie Rentals</h1>

        <div ng-repeat="movie in movies.movieList">
            <button ng-click="selectMovie(movie)">{{movie.name}}</button>
        </div>

        <div class="panel">
            <h3>You have selected:</h3>
            <p>{{selectedMovie.name}}</p>
            <p>{{selectedMovie.format}}</p>
            <p>{{selectedMovie.rate}}</p>
            <p>{{selectedMovie.price}}</p>
        </div>
    </body>

</html>

Live demo available here

Answer №5

Here is a sample code snippet that meets your requirements: Sample Code

Modify the html as follows:

<div ng-repeat="movie in movies">
      <button ng-click="selectedMovie(movie)">{{movie.name}}</button>
    </div>

    <div class="panel">
      <h3>You have selected:</h3>
      <p>{{movie.name}}</p>
      <p>{{movie.format}}</p>
      <p>{{movie.rate}}</p>
      <p>{{movie.price}}</p>
    </div>

Update the javascript to:

myApp.controller('MainController', ['$scope', function($scope) {
    var data = {
  "movie": [
  {
    "id": 1,
    "name": "Star Wars The Phantom Menace",
    "format": "DVD",
    "rate": 4,
    "price": 2
  },
  {
    "id": 2,
    "name": "Star Wars A New Hope",
    "format": "DVD",
    "rate": 6,
    "price": 4
  },
  {
    "id": 3,
    "name": "Transformers",
    "format": "Blu-Ray",
    "rate": 7,
    "price": 3
  },
  {
    "id": 4,
    "name": "Transformers Dark of the Moon",
    "format": "Blu-Ray",
    "rate": 6,
    "price": 5
  }
]};
$scope.movies = data.movie;
$scope.selectedMovie = function(movie){
  $scope.movie = movie;
}
}]);

Answer №6

To display movies on your front-end, simply define the movies object within your controller. To embed the movies JSON directly in your controller, it would look like this:

app.controller('MainController', ['$scope', function ($scope) {
  $scope.movies1 = 
    [{
      "id": 1,
      "name": "Star Wars The Phantom Menace",
      "format": "DVD",
      "rate": 4,
      "price": 2
    },
    {
      "id": 2,
      "name": "Star Wars A New Hope",
      "format": "DVD",
      "rate": 6,
      "price": 4
    },
    {
      "id": 3,
      "name": "Transformers",
      "format": "Blu-Ray",
      "rate": 7,
      "price": 3
    },
    {
      "id": 4,
      "name": "Transformers Dark of the Moon",
      "format": "Blu-Ray",
      "rate": 6,
      "price": 5
    }];
}]);

I've converted movies to an array and removed the movie property inside the object for proper functioning of ng-repeat.

If you prefer to have the movies JSON in a separate file, you can load it using the $http service as @KuZon mentioned.

$http.get('movies.json').then(function(json) {
    $scope.movies1 = json.data.movie;
  });

In this scenario, I have kept the movie attribute inside the JSON object and used it to select the array to store in $scope.movies1.

You can view both methods in this Plunkr.

Lastly, remember to use ng-click on your buttons to select the movie. For example:

<button ng-click="selectMovie1(movie)">{{movie.name}}</button>

And in your controller:

$scope.selectMovie1 = function(movie) {
   $scope.movie1 = movie
 }

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

Mastering the use of gl Scissor is essential for effectively implementing popups in your

I am attempting to implement a pop-up view on top of the current webGL view. My strategy is as follows: Whenever I need to display a popup, I create a scissorRect and begin rendering the popup scene onto it. I was hoping that the content of the previous s ...

Ways to optimize the performance of my android application

Looking for a way to optimize my Android app, as I am currently using 5 APIs in a single class which slows down the performance. Here is a snippet of my code: @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceS ...

When running the command "npm start," an error occurs stating: Plugin/Preset files are prohibited from exporting objects and can only export functions

I recently started using reactJS and was following a tutorial. However, I encountered an error when trying to run "npm start". Here is the error message: ERROR in ./main.js Module build failed (from ./node_modules/babel-loader/lib/index.js): Error: Plugin ...

What benefits could you derive from utilizing an interface to generate a fresh Array? (Pulumi)

Just delving into the world of TypeScript and Pulumi/IaC. I'm trying to wrap my head around a code snippet where an array of key values is being created using an interface: import * as cPulumi from "@company/pulumi"; interface TestInterface ...

"Implement a feature that allows for infinite scrolling triggered by the height of

Looking for a unique solution to implement a load more or infinite scroll button that adjusts based on the height of a div. Imagine having a div with a height of 500px and content inside totaling 1000px. How can we display only the initial 500px of the div ...

Troubleshooting the JsonValueProvider malfunction in ASP.NET MVC3

I'm struggling to connect a ViewModel to JSON in MVC3. Here is my code... <asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server"> <% using (Html.BeginForm("Save", "Home")) {%> <p> Cat < ...

Retrieve data from a variable labeled as a string containing JSON

Looking to extract specific values from a string or JSON object? Here's an example: {"Artigo":{"NrReg":"81846","Cod":"XXX96000051","Desc_Web":"XX 296 00 BLACK","Desc_Agregadora":"XX 296","PVO":"69","NlDes":"3","Cat1_GrpArtigos":"\t2","Cat2_SegMa ...

Passing dynamic props to Vue mixin: a guide

Can we pass dynamic props to a Vue mixin from its parent component? Here's the scenario. This mixin is set up to receive an isActive prop. mixin.ts export default { props: { isActive: { type: Boolean, required: true } }, wa ...

Tips for automatically closing SweetAlert after an AJAX request finishes

I recently implemented Sweet-alert into my Angular project. function RetrieveDataFromAPI(url) { SweetAlert.swal( { title: "", text: "Please wait.", imageUrl: "../../app/app-img/loading_spinner.gif", showConfirmB ...

What is the proper way to utilize $location within a standard function?

I am working on an Angular app that consists of both AngularJS and plain JavaScript such as Ajax. I am trying to figure out how to use $location within a function without passing it as a parameter. function x() { $location.path('/error').repl ...

Tips for generating various series using dx-Chartjs

Trying to visualize ratings based on their type is proving to be difficult as I can't seem to figure out how to group the series according to types. The available chart options are: $scope.chartOptions = { dataSource: data, c ...

Interacting with server-side data using JQuery's $.ajax method and handling JSON

The JSON response returned from the request is not being recognized. request = $.ajax({ url: "form_handler.php", type: "post", dataType: "json", data: serializedData }); The PHP code within form_handler.php that generates ...

Supply mandatory argument along with varying arguments to the function

I have a function that requires one parameter and a dynamic set of additional parameters. I am passing an array of blobs to the function. Below is a simplified version of the function: function test(directory, blob0, blob1) { for (var argumentIndex = 1; ...

An offbeat symbol discovered when using conditional rendering

I encountered an unexpected token error while working on conditional rendering. Even though everything seems to be correct, I can't seem to pinpoint the issue. {isAdd===true? countries.map(item=>{ return( <Men ...

Combining arrays to append to an array already in place

I have implemented the rss2json service to fetch an rss feed without pagination support. Instead of a page parameter, I can utilize the count parameter in my request. With this setup, I am successfully able to retrieve and display the feed using a service ...

Sorting through an array of objects based on TypeScript's union types

My array consists of objects such as: array = [{name: 'something'}, {name: 'random'}, {name: 'bob'}] I have created a union type type NamesType = 'something' | 'bob' Can the array be filtered based on t ...

Updating a class within an AngularJS directive: A step-by-step guide

Is there a way to change the class (inside directive) upon clicking the directive element? The current code I have updates scope.myattr in the console but not reflected in the template or view: <test order="A">Test</test> .directive("test", ...

The integration between Mongoose and GraphQL does not support populating models

It seems like I have encountered a unique issue that none of the existing solutions have been able to resolve. I am running a backend server with Apollo Server + Mongoose on localhost. However, I am facing difficulties in populating or creating the collect ...

Extract JSON from the response data in the success callback of a JQuery.ajax

I've encountered an issue with retrieving the contents of a JSON object from a JQuery.ajax call. Here is my code: $('#Search').click(function () { var query = $('#query').valueOf(); $.ajax({ url: '/Products/Se ...

Vietnamese special characters are not supported in JSON on Windows Phone 8.1 when using IBM Mobile First

In my IBM mobile first application, I am facing an issue with JSON response containing Vietnamese characters (e.g. Tôi là một nhân vật đặc biệt) on Windows 8.1 Phone. The character encoding I am using is UTF-8. resourceRequest.send($scope.dat ...