Identifying the hashKey and selected option in a dropdown menu

My attempt to set the selected option for the select menu is not working because the data in the ng-model that I am sending has a different $$hashKey compared to the data in the select menu, and the $$hashKey holds the values.

<select class="form-control" ng-model="selManga" ng-options="manga.seri for manga in mangalar"> 
<option value="">Select Manga</option> 
</select>
<select ng-change="selPage = 0" ng-model="selChapter" ng-options="selManga.randomword.indexOf(chapter) as chapter.klasor for chapter in selManga.randomword"> 
<option value="">Chapter</option> 
</select>
<select ng-model="selPage" ng-options="selManga.randomword[selChapter].yol.indexOf(page) as selManga.randomword[selChapter].yol.indexOf(page) + 1 for page in selManga.randomword[selChapter].yol">
</select>

After researching, people suggest using track by to solve this issue, but I have to use as. Is there another way to work around it?

The selected value for the first select menu works fine, but the second one does not. Here is the Plunker example: http://plnkr.co/edit/3V8JSF2AU01ZZNPfLECd?p=info

.controller('nbgCtrl',function  ($scope, MMG, $stateParams) {
var milo = $stateParams.serix;
var musti = $stateParams.klasor;
MMG.adlar.success(function(loHemen) {
    var i, miloMangaInArray;
    for (i=0; i<loHemen.length; i++) {
        if (loHemen[i].seri===milo) {
            miloMangaInArray = loHemen[i];
            break;
        }
    };
    var a;
    for (a=0; a<miloMangaInArray.randomword.length; a++) {
        if(miloMangaInArray.randomword[a].klasor===musti) {
            break;

        }
    }
$scope.mangalar = loHemen; //JSON Data
$scope.selManga = $scope.mangalar[i]; // The ng-model for the first select menu is working.
$scope.selChapter = $scope.mangalar[i].randomword[a]; // The ng-model for the second select menu is not working due to mismatch with JSON data.
});

$scope.next = function (manga, chapter, page) {
    var nextPage = page + 1;
    if (angular.isDefined(manga.randomword[chapter].yol[nextPage])) {
        $scope.selPage = nextPage;
    } else if (angular.isDefined(manga.randomword[chapter + 1])) {
        $scope.selChapter = chapter + 1;
        $scope.selPage = 0;
    }};

})

https://i.stack.imgur.com/YvvkV.png

Answer №1

Hey there, check out this awesome js fiddle I put together for the solution http://jsfiddle.net/abc123xyz/5/

In this scenario, I utilized the indexOf method to retrieve the index of the page in the array for the last select element only.

However, please note that this may not be the most efficient solution as it will need to apply indexOf every time the digest loop runs. There are several alternative solutions that could be considered:

1- Extracting the id of the page from the name of the image itself

2- Mapping the pages array to a list of objects with the following format:

[{"index":1,"img":"00.jpg"},{"index":2,"img":"01.jpg"},{"index":3,"img":"02.jpg"}]

You can achieve the second option with the following code snippet:

pages.map(function(d,i){return {"index":i,"img":d};});

coder123

Answer №2

I strongly recommend adopting the AngularJS approach to managing models and bindings. Rather than manually tracking various indexes in your view code, utilize the power of ng-select to automatically assign references to sections of your model using ng-model. By making some minor adjustments to both the HTML and controller, you can streamline your code and achieve successful results.

To begin, establish a shared $scope.model = {…} object within the $scope. Then update the HTML as follows:

<select ng-model="model.selManga" ng-options="manga.seri for manga in mangalar">
  <option value="">Select Manga</option>
</select>

<select ng-model="model.selChapter" ng-options="chapter.klasor for chapter in model.selManga.randomword" ng-change="model.selPage = model.selChapter.yol[0]">
  <option value="">Chapter</option>
</select>

<select ng-model="model.selPage" ng-options="page as model.selChapter.yol.indexOf(page) + 1 for page in model.selChapter.yol">
</select>
<img class="picture" ng-src="http://baskimerkeziankara.com/{{model.selPage}}" ng-click="next(model.selPage)">

Next, adjust the controller accordingly:

.controller('nbgCtrl', function($scope, MMG, $stateParams) {
    var model = {
      selManga: undefined,
      selChapter: undefined,
      selPage: undefined
    };
    $scope.model = model;

    MMG.adlar.success(function _init(loHemen) {
      for (var i = 0; i < loHemen.length; i++) {
        if (loHemen[i].seri === $stateParams.serix) {
          model.selManga = loHemen[i];
          break;
        }
      }

      for (var a = 0; a < model.selManga.randomword.length; a++) {
        if (model.selManga.randomword[a].klasor === $stateParams.klasor) {
          model.selChapter = model.selManga.randomword[a];
          break;
        }
      }

      model.selPage = model.selChapter.yol[0];

      $scope.mangalar = loHemen;
    });

    $scope.next = function _next(page) {
      var pageIndex = model.selChapter.yol.indexOf(page);

      if (angular.isDefined(model.selChapter.yol[pageIndex + 1])) {
        model.selPage = model.selChapter.yol[pageIndex + 1];
      } else {
        var chapterIndex = model.selManga.randomword.indexOf(model.selChapter);

        if (angular.isDefined(model.selManga.randomword[chapterIndex])) {
          pageIndex = 0;

          model.selChapter = model.selManga.randomword[chapterIndex + 1];
          model.selPage = model.selChapter.yol[pageIndex];
        }
      }
      console.log('manga', model.selManga.seri, 
                  'chapter', model.selChapter.klasor,
                  'selPage', pageIndex + 1);
    };
  })

An example demonstrating this implementation is available on Plunker at: http://plnkr.co/edit/2aqCUAFUwwXuGQHpuooj

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

Rendering json data in jquery

Is there a way to load a .json file from the assets folder into a jquery script within a grails application? Below is the jquery code snippet I have written to handle this: let dropdown = $('#banks'); dropdown.empty(); dropdown.append(' ...

Ways to filter out specific fields when returning query results using Mongoose

I was wondering about the code snippet below: Post.create(req.body) .then(post => res.status(201).json(post)) .catch(err => res.status(500).json(err)) While this code works perfectly, I am curious about excluding a specific field, such as the __v fi ...

Implementing subscriber addition on Mailchimp 3.0 using Node.js and HTTPS

Here's the content of my app.js file: const express = require("express"); const bodyParser = require("body-parser"); const request = require("request"); const https = require("https"); const app = express(); app.use(express.static("public")); app.u ...

The Nextjs application folder does not contain the getStaticPaths method

I encountered a problem with the latest nextjs app router when I tried to utilize SSG pages for my stapi blog, but kept receiving this error during the build process app/blog/[slug]/page.tsx Type error: Page "app/blog/[slug]/page.tsx" does not m ...

Create reactivity in output by utilizing global functions in Vue

I've recently dived into Vue, along with vue-cli and Single File Components. I'm facing a challenge where I need to have a global function that provides formatted text to components throughout my application. This text should be based on the curr ...

Is it possible for a popup to appear without any user interaction

Do you ever wonder how certain websites are able to trigger pop-ups without being blocked by Chrome's pop-up blocker? I had always thought that pop-up blockers only allowed window.open if it was initiated by a user action. However, the situation seem ...

jQuery Typeahead implementation malfunctioning when text matches either the first or last character

It seems like there is a problem with the .split() method, especially when the characters match the beginning or end of a name. To see the issue in action, visit this JSFiddle link: http://jsfiddle.net/5uebxvex/ I'm working with the Employees tabl ...

Python: Traversing through a multi-tiered dictionary

Having an issue with a JSON output structured as a dictionary. When iterating through it, the values are not being retrieved. What could be the missing piece here? Displayed below is a sample JSON output of dict type. The data consists of two levels and o ...

Unable to retrieve field values from Firestore if they are numeric rather than strings

I need to display this information in a list format: li.setAttribute('data-id', updatesArgument.id);//'id' here unique id Example 1 name.textContent = updatesArgument.data().count;// Works if String Example 2 let i=1; nam ...

AngularJS: monitoring changes in an array property

For the problem at hand, take a look at this link: http://plnkr.co/edit/ZphAKvZeoVtuGFSEmOKg?p=preview Imagine you have an array structured like this: var arr = [ { 'a': "123", 'b': "654" }, { 'a': "456", &apo ...

extract data from text node using selenium

Currently, I am working on a web application and testing it with Selenium. Within my code, there is a specific node that I am trying to extract data from. <span>Profile Run <span class="current">23</span> of 29</span> My main obje ...

Having difficulty utilizing the $.each() function to assign properties to an object

I have an object called habits that contains some values. var habits={ "Drinking":"No", "Smoking":"No" } I want to add the values from this variable into another variable in the following format: var NewHabits = new Object(); Ne ...

Concealing a block from top to bottom

I currently have a filter that is hidden when clicked, with a transition effect that moves it from the bottom to the top. I have recorded my screen to demonstrate this behavior: . However, I now need the filter to hide from top to bottom instead, essenti ...

Utilizing External Libraries Added Through <script> Tags in React

My goal is to develop a Facebook Instant HTML5 application in React. Following their Quick Start guide, Facebook requires the installation of their SDK using a script tag: <script src="https://connect.facebook.net/en_US/fbinstant.6.3.js"></scrip ...

Ways to confirm the presence of specific keys in a JSON:

After successfully converting an excel sheet's content into a JSON format, my next task is to perform some validation on it. The requirement is to ensure that the jsonData variable contains specific keys in a particular order: Breakfast, Lunch, Snack ...

Switching on and off a class in Next.js

I'm a beginner with Next.js and React framework. My question is regarding toggling a class. Here's my attempt in plain JS: function toggleNav() { var element = document.getElementById("nav"); element.classList.toggle("hidde ...

Tips on retrieving information from a CURL post output

Currently, I am utilizing CURL to post data and receiving output based on that information. Now, my main objective is to extract and parse the received output. The output I am currently obtaining is as follows: a:3:{s:6:"status";s:1:"1";s:3:"msg";s:32:"T ...

Sorting through arrays in JavaScript/React

My search functionality works well, but I'm facing an issue when the item is not found in the array. I attempted using objects.Keys to handle this situation, but it's displaying on render instead of when the book is not found as expected. Should ...

Using Angular's ngBlur directive on multiple input fields

My current task involves capturing and saving all content on a webpage after it has been edited. For example, when a user clicks into an input field, enters data, and then clicks elsewhere, I would like to trigger a function to collect all the model data a ...

Vue.js 2: Keep an eye on changes, but wait until after the initial data fetch

I recently entered the Vueverse (using Vue.js 2) and I'm encountering some challenges with the watch feature. When the component is mounted, I fetch data from an API and use it to set the value of a radio button. Essentially, I have two radio buttons ...