Implementing dynamic image insertion on click using a knockout observable

I'm utilizing an API to retrieve images, and I need it to initially load 10 images. When a button is clicked, it should add another 10 images. This is how I set it up:

Defining the observable for the image amount:

public imageAmount: KnockoutObservable<number> = ko.observable(10);

In this section, I slice the array based on the imageAmount variable, which functions properly.

var images = response.data.slice(0, this.imageAmount()).map((data: IImageData) =>
        {
            return {
                big: 'http://d1ftcqzt8gr3o4.cloudfront.net/'+ data.big,
                thumb: 'http://d1ftcqzt8gr3o4.cloudfront.net/'+ data.thumb
            }
        });

Subsequently, when the button is clicked, I update the imageAmount observable by adding 10 more images.

public moreImages(): void
{
    this.viewModel.imageAmount(this.viewModel.imageAmount() + 10);

}

Although the count increases, the additional images are not being added. How can I resolve this?

HTML code:

View HTML format on pastebin as it couldn't be displayed correctly here

Answer №1

If you want to dynamically bind attributes, you can achieve this using attribute bindings:

data-bind="attr:{href: $data.url}"

Sample Usage

Demo Link

var DataModel = function(title, link) {
  this.links_arr = ko.observableArray([{
    id: 1,
    url: "https://www.example1.com/image.jpg"
  }, {
    id: 2,
    url: "https://www.example2.com/logo.png"
  }, {
    id: 3,
    url: "https://www.example3.com/icon.png"
  }])
};

ko.applyBindings(new DataModel("Page", "Link Page")); 
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.1.0/knockout-min.js"></script>
<div class='sampleExample' data-bind="foreach:links_arr">
  <p data-bind="text:$data.id"></p>
  <img data-bind="attr:{src: $data.url}" alt="">
</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

Unable to append item to JavaScript Map

Currently, I am attempting to insert an item into a Map (similar to a dictionary) using JavaScript within a React Native environment. import React, { Component } from 'react'; import { AppRegistry, View, Button, } from 'react-native& ...

What is the process for overriding the module declaration for `*.svg` in Next.js?

The recent modification in Next.js (v11.0.x) has introduced new type definitions: For next-env.d.ts (regenerated at every build and not modifiable): /// <reference types="next" /> /// <reference types="next/types/global" /> ...

Validating numbers in React JS input fields component

I need assistance with implementing number validation for 3 Textfields in my application. Currently, the code displays an error message if a Textfield is empty, but I am stuck on validating whether the input is text or numbers. import React from 'rea ...

Having trouble with rendering prop values in Vue.js?

Struggling to develop an ajax form component in vuejs within a Laravel 5.3 application. It seems I am facing some challenges with displaying the form fields. Can someone lend me a hand? Here is the front end code for rendering the form: <ajax-form ...

Updating a one-to-one relationship in TypeORM with Node.js and TypeScript can be achieved by following these steps

I am working with two entities, one is called Filter and the other is Dataset. They have a one-to-one relationship. I need help in updating the Filter entity based on Dataset using Repository with promises. The code is written in a file named node.ts. Th ...

What are the recommended TypeScript tsconfig configurations for running Node.js 10?

Can someone provide information on the necessary target/libs for enabling Node.js v10.x to utilize async/await without generators? I have found plenty of resources for node 8 but not as much for node 10. ...

"An unexpected compilation error (800A03EA) has occurred in the JavaScript syntax during

My computer is facing a frustrating compilation issue with JScript and node. Despite trying various solutions found online, the problem persists. After navigating to CD>PROJECT: npm init successful npm install -g globally and locally installed correct ...

When selecting the "Open Link in New Tab" option in Chrome, the Angular app's routing will automatically redirect to the login page

I am facing a peculiar issue in my Angular 2 application that I need help troubleshooting. Currently, the routing within my app functions as intended when I click on links to navigate between different components. Here is an example of how the routing path ...

How can I turn off the draggable feature for a specific element in react-beautiful-dnd?

Currently, I am implementing a drag and drop functionality using TypeScript with react-beautiful-dnd. The goal is to allow users to move items between two containers - one containing user names and the other labeled "Unassigned". Here is a snapshot of the ...

Utilizing Service within Express Router

My journey into the world of NodeJS is just beginning, coming from a .NET background with a love for dependency injection, inversion of control, and microservices. I am now venturing into TypeScript to create services based on my past experiences. Using ex ...

Convert the Date FR and Date US formats to ISO date format

There is a function in my code that accepts dates in different formats. It can handle two formats: 2022-06-04 or 04/06/2022 I want all dates to be in the format: 2022-06-04 For instance: public getMaxduration(data: object[]): number { data.forEach((l ...

Is Valums Ajax file Upload capable of handling the uploaded file?

Currently, I am utilizing the Valums Ajax Fileupload script found at These are the settings I have configured: function createUploader(){ var uploader = new qq.FileUploader({ element: document.getElementById('file-uploader-de ...

The image slider script I've built is functioning perfectly in Codepen, but unfortunately, it's not working as

My image slider called Orbit is functioning properly on Codepen.io, however when I try to run the exact same code on Plunker, it doesn't work at all. <ul class="slider" data-orbit> <li> <img src="http://foundation.zurb.com/docs/a ...

JavaScript form button press tracker

Hello! I've been tackling a challenge involving a JavaScript function to count button clicks. The catch is, the button type is set to submit, causing the page to reload every time I click it. Below is the snippet of code that contains the problemati ...

"Enhancing User Experience with Angular 2: Customizing Component Selection and Sty

I am currently working on an Angular application that fetches a configuration file in .json format. My goal is to dynamically choose components and apply inline styles to them. Below is an example of the structure of the configuration data obtained from a ...

Prevent repeating the same table header multiple times when generated dynamically with jQuery

I have an array called groups which contains name and regid. I want to display the name key as the column header of a table. To achieve this, I implemented the following code: var Name = v.name; var regId = v.regid; var rowStr = '<th d ...

Encountering a router issue when trying to export using Express middleware

New to this and encountering a router error when trying to export in Express. How can I resolve this issue for both the router and the mongo model? Hoping for a successful export process in both the router and the mongo model. ...

What steps should I take to pinpoint the fundamental mistake in my webpage dedicated to clocks?

Exploring an intriguing clock project that utilizes ancient timekeeping methods found at . Recently encountered a puzzling error in Chrome, where it claims to be unable to call a method on undefined. Strangely enough, the error message is not located near ...

Making a quick stop in Istanbul and NYC to collect a few important files

Setting up Istanbul/Nyc/Mocha for test coverage in my project has been a bit of a challenge. While I was successful in running Nyc, I noticed that not all the .ts files in my project were being picked up for test coverage. When I execute npm run coverag ...

Transforming an interactive HTML webpage into React/JSX

Imagine a scenario where I have two files: example.html <!DOCTYPE html> <html lang="en" xmlns="http://www.w3.org/1999/xhtml"> <head> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta charset="u ...