Exploring the seamless integration of AngularJs databinding with JSON for dynamic content

I have a question that seems simple, but I can't seem to find the answer anywhere.

My goal is to load JSON data from my server into the client using AngularJS.

How can I display all three slides in my view with AngularJS? Currently, with this code, only one slide is being displayed.

VIEW:

          <div ng-app="app">
            <div ng-controller="CarouselDemoCtrl" id="slides_control">
              <carousel interval="myInterval">
                <slide ng-repeat="slide in slides" active="slide.active">
                  <div class="slide"><h2 class="slide-text">{{slide.Carousel[0]}}</h2></div>
                </slide>
              </carousel>
            </div>
            </div>

CONTROLLER:

angular.module('app')

.controller('CarouselDemoCtrl', function($scope, dataService) {

$scope.addSlide = function() {
    var newSlide = {"Carousel": $scope.values}
    $scope.slides.push(newSlide);
};

$scope.myInterval = 3000;

dataService.getSlides(function(response) {
        console.log(response.data);
        $scope.slides = response.data;
    });

})

SERVICE:

angular.module('app')

.service('dataService', function($http) {

this.getSlides = function(callback) { 
    $http.get('json/be-creative.json')
    .then(callback)
}

});

JSON:

[
{"AboutUs": "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularized in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum."},
{"Carousel": ["Slide 1", "Slide 2", "Slide 3"]}
]

Answer №1

You have mistakenly bound the object on the incorrect level.

If you want to use slide for your carousel representation, make sure to bind it properly like this

dataService.getSlides(function(response) {
    console.log(response.data);
    $scope.aboutUs = response.data.AboutUs;
    $scope.slides = response.data.Carousel;
});

<slide ng-repeat="slide in slides" active="slide.active">
    <div class="slide"><h2 class="slide-text">{{slide}}</h2></div>
</slide>

Hint: ng-repeat should be applied on arrays


Edit: After further examination, it appears there is an extra layer of object, so 'find' is used to locate the target object.

If possible, consider changing the JSON format to

{
    "AboutUs": "...",
    "Carousel": ["Slide 1", "Slide 2", "Slide 3"]
}

angular.module('app', [])

  .controller('CarouselDemoCtrl', function($scope, dataService) {

    $scope.addSlide = function() {
      var newSlide = {}
      $scope.slides.push(newSlide);
    };

    $scope.myInterval = 3000;

    dataService.getSlides(function(response) {
      // console.log(response.data);
      $scope.aboutUs = response.data.find(function(d) { return d.AboutUs; }).AboutUs;
      $scope.slides = response.data.find(function(d) { return d.Carousel; }).Carousel;
    });

  })

  .service('dataService', function($http) {

    this.getSlides = function(callback) {
      //$http.get('json/be-creative.json')
      //  .then(callback)
      
      var json = [
{"AboutUs": "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularized in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum."},
{"Carousel": ["Slide 1", "Slide 2", "Slide 3"]}]

      callback({data: json});
    }

  });
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.min.js"></script>
<div ng-app="app">
  <div ng-controller="CarouselDemoCtrl" id="slides_control">
    <carousel interval="myInterval">
      <slide ng-repeat="slide in slides" active="slide.active">
        <div class="slide">
          <h2 class="slide-text">{{slide}}</h2>
        </div>
      </slide>
    </carousel>
  </div>
</div>

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

Preventing a sprite from going beyond the boundaries of a canvas with pure JavaScript - here's how!

I am in the process of developing a game using native JavaScript, HTML, and a touch of CSS. I have two blocks called Sprites that tend to keep moving off the canvas edges when they reach them. Question: How can I utilize native JS to prevent the sprites fr ...

Issue with Quantity Box not displaying values in Shopify store

I am currently seeking assistance with resolving an issue I have encountered on a Shopify theme that I recently customized. The problem lies within the quantity box on the live site where despite being able to adjust the quantity using the buttons, the act ...

Using client-side navigation within an integrated Shopify application

Seeking assistance in implementing client-side routing with react-router within a Shopify app that is embedded. Following the guidelines provided by Shopify on this page, but unsure about what needs to be included in a ./Routes file. Attempted to find rela ...

Struggling to achieve the expected results when trying to convert a PHP array into JSON

When I receive names and links of files from an external website, I use the following code to convert them into a JSON string: <?php include('simple_html_dom.php'); $f = $_GET['f']; $w = "www.something.com"; $dom = file_get_html($w ...

Incorporating a custom object into two dropdown menus using JavaScript

As a novice in the world of JavaScript, I am attempting to dynamically add values from a text box to two select boxes. Upon entering a value (node name), my goal is to include that name in both select boxes srcNodes and targetNodes. However, I'm enco ...

Issue with controller being undefined when testing directive with controllers in Jasmine with AngularJS

I'm having trouble testing the controller that my directive is using because I can't reference the controller. directive.js (function () { 'use strict'; angular .module('myModule') .directive('c ...

What is the best way to trigger a function after the v-model has been updated

When attempting to filter an array of objects in Vue using input, I encountered issues with Salvattore not functioning correctly for building a grid of the filtered elements. It seems that calling the rescanMediaQueries() function after changes to my v-mod ...

What alternative methods can be used to render a React component without relying on the ReactDOM.render

Can a React component be rendered simply by referencing it with its name? For example: <div> <MyComponent/> </div> In all the tutorials and examples I've seen, ReactDOM.render function is used to render the component onto the ta ...

Library for handling JSON in ASP applications

Currently, I am using JSON2.asp to provide classic ASP support for parsing JSON data. The server is sending a string that looks like this: {'title':['aaa',0,'1',''],'columns':['aaa','bbb&apo ...

Should I keep my Mobx stores in a dedicated file or include them directly in the React component?

There are a couple of ways to define observable properties and actions in MobX. One way is to include them directly in the component like this: // App.js class App extends Component { @observable a = 'something' @action change() { this. ...

Obtaining a String from a nested Array within an Array using Swift

When trying to extract a String from an Array by iterating through it, I am encountering an issue. let parsed = try NSJSONSerialization.JSONObjectWithData(jsonData, options: NSJSONReadingOptions.AllowFragments) for item in parsed as! [Dictionary& ...

What is the best way to ensure that an iframe adjusts its height to fit the content within a tabbed container?

Is there a way to dynamically set the height of an iframe to match the content inside it when clicking on a tabbed plane? Initially, I used a fixed height of 1000px. How can this be achieved? <div class="container-fluid text-center"> <div ...

Utilizing Angular's $resource, extract the object returned by the POST method

I have a Web API Controller with the following POST method: [HttpPost] public async Task<IHttpActionResult> Post(Hotspot hotspot) { try { int id = await SomeMethod(); re ...

Step-by-step guide on how to activate a colorbox using a targeted Id or class

Below is the code I'm currently working with: <div class="hidden"> <div id="deletePopContent" class="c-popup"> <h2 class="c-popup-header">Delete Practice Sheet</h2> <div class="c-content"> <h3 ...

Is it necessary for a component to disconnect from the socket io server upon unmounting?

Is it best practice for a React component to automatically disconnect from a socket.io server when it unmounts using the useEffect hook? If so, could you provide an example of the syntax for disconnecting a React component from a socket.io server? ...

The bodyparser in Express seems to be malfunctioning

When configuring my body parser, I implement the following code: const express = require('express') const app = express(); const bodyParser = require('body-parser'); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extend ...

The supported browser is unable to import ES6 modules

Attempting to incorporate moment.js as an es6 module. The most recent version of Chrome is being utilized. Referring to the conversation here, I experimented with the src path (es6) import * as moment from './node_modules/moment/src/moment' A ...

Comparison between UI Router and ngRoute for building single page applications

Embarking on a new Angular project, a single page app with anticipated complex views such as dialogs, wizards, popups, and loaders. The specific requirements are yet to be clarified. Should I embrace ui.router from the start? Or begin with ngRoute and tra ...

Oops! Next JS encountered an unhandled runtime error while trying to render the route. The

I keep receiving the error message Unhandled Runtime Error Error: Cancel rendering route Within my navBar, I have implemented the following function: const userData={ id:1, email: "", name: "", lastName: "", ...

Creating asynchronous JavaScript constructors using a static method called "create" presents challenges when dealing with TypeScript types

I've been diving into the world of asynchronous constructors and have successfully implemented them in JavaScript. However, I'm facing a challenge with TypeScript types. Here's how it should ideally work: const a: AnyClass = await AnyClass. ...