how to ensure a consistent property value across all scopes in AngularJS

Here is my perspective

  <div ng-if="isMultiChoiceQuestion()">
                <li class="displayAnswer" ng-repeat="choice in getMultiChoice() track by $index" ng-if="isNotEmpty(choice.text.length)">
                            <input type="checkbox" ng-checked="checkForSelection(choice.id)"
                            value="choice.text" disabled="true">
                      <span ng-class="getCSSClass($index, choice.id)">{{choice.text}}</span>
                </li>
              </div>

            <a class="weiter-link" ng-click="flipBack()">Zur Frage</a>

                <div ng-if="isMultiChoiceQuestion()">
                  <!--Changed ng-bind getScore() -> score -->
                      <h4>Bewertung speichern: <span ng-bind="getScore()"></span></h4>
                  <br />
                      <a class="weiter-link" ng-click="incrementOne()">Zur nächsten Frage</a>
                </div>
                  <div ng-if="!isMultiChoiceQuestion()">
                        <h3>Eigene Bewertung: {{score}}</h3>
                        <div class="ranger">
                          <input type="range" max="10" min="0" step="1" id="selfRanger" ng-model="score">
                        </div>
                        <a class="weiter-link" ng-click="submitScore(score)">Bewertung speichern</a>
                            <a class="weiter-link" ng-click="incrementOne()">Zur nächsten Frage</a>
            </div>

The above view creates three scopes. One for the controller, another for the first div, and the third for the second div. The issue lies with the property called "score" in the controller not being utilized in the second div.

How can we make the second div utilize the controller's property instead of automatically creating its own property?

JavaScript

app.controller("QuizController", ['total', '$scope', '$rootScope',  'quizDataService',  'QAPointerChange', 'QAScoreList', function (total, $scope, $rootScope, quizDataService, QAPointerChange, QAScoreList) {

  $scope.getScore = function()
      {
          // Makes a call to getCurrentScore and returns a value
          $scope.getCurrentScore();
          return QAScoreList.getSpecificItemScore(QAPointerChange.getQAPointer());
      }
$scope.score = 0;

    $scope.submitScore = function (newScore)
    {
        QAScoreList.setSpecificItemScore(QAPointerChange.getQAPointer(), Number(newScore));
    }


      $scope.getCurrentScore = function()
      {
            $scope.score = QAScoreList.getSpecificItemScore(QAPointerChange.getQAPointer());
      }


}

This is not a complete JS file. The controller has all services responsible for making calls to fetch scores and other data from services.

Answer №1

If you want to utilize nested scopes, there are two methods:

Dot Notation

Avoid using a single variable like $scope.score, but instead use $scope.data.score (your variable is within an object which is inside the scope).

Controller as Syntax

Do not assign variables to the scope, but to the controller (at the beginning of the controller):

var self = this;
self.score = 5;

In the HTML:

<div ng-controller="QuizController as ctrl">

And then use it like this:

{{ctrl.score}}

Update on Slider Issue

The issue with the slider getting stuck: You have ng-bind="getScore()" in your HTML so getScore is executed every $digest cycle. This occurs when the HTML needs to be redrawn, such as when a scope variable changes. So:

  1. When you adjust the slider, $scope.current.score changes
  2. As a result, the $digest cycle begins
  3. getScore is executed
  4. $scope.current.score is updated with the value from QAScoreList in the getCurrentScore function
  5. The slider reverts back to that value

It worked without dot notation because both $scope.score and ng-model="score" were not the same variable (they existed in different scopes)

Therefore, it would be advisable to do the following (assuming that in "Bewertung speichern" you want to display the same value as selected in the range, if not, you must use a different variable name):

  1. Replace ng-bind="getScore()" with ng-bind="current.score"
  2. Execute $scope.getScore() at the start of the controller to retrieve the current value from the service QAScoreList

Answer №2

By using the ng-if directive to call a function, the function will only be executed when the specified condition is met. To ensure that the getScore() function is not skipped for the third div, you can use the ng-init='getScore()' attribute in the third div as well.

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

Issues with retrieving a result object from a MySQL query in NodeJS

I've been working on creating a logging system in NodeJS with a MySQL database. To establish the connection, I use the following code: const con = mysql.createConnection({ host : 'localhost', user : 'dbuser', passwor ...

Tips for dynamically updating an HTML value with Javascript

Summary of My Issue: This involves PHP, JS, Smarty, and HTML <form name="todaydeal" method="post"> <span id="fix_addonval"></span> <input type="radio" name="offer" id="offer_{$smarty.section.mem.index+1}" value="{$display_offe ...

Error: CSRF token is required for security purposes. Django and AngularJs integration requires proper CSRF token handling

Encountering an error when attempting to render my second page in the Django framework. It seems like there may be an issue with the URL and views.py files, but I'm at a standstill trying to diagnose the problem. Forbidden (CSRF token missing or inco ...

Retrieve data attributes to obtain details about the slider before and after

My task is to create a slider with information about the previous and next slides. For example, in the slider, there are left < and right > arrows. Behind these arrows, there are circles. When you hover over any arrow to change the next or previous ...

Tips for comparing props in the ComponentDidUpdate method when dealing with a complex data structure that is connected to Redux

I have been experimenting with the new lifecycles of React v16. It works perfectly fine when comparing single keys. However, when dealing with large data structures like Arrays of objects, performing deep comparison can be quite expensive. My specific sce ...

Filling form fields with array data (AngularJS)

Although I'm new to AngularJS, I'm struggling to figure out how to handle a list of arrays returned from the searchAll function. console 0: {mobile: "12345678", lastname: "last01", firstname: "first01"} 1: {mobile: "87654321", lastname: ...

Exploring the Benefits of jQuery History Plugin, Optimizing with Google Sitemap and

Despite searching online, I have yet to find a precise solution to my query. On my index.php page, there are two specific DIV's: #post-title and #post-content, whose content is dynamically loaded through a jQuery function triggered by clicking a link ...

Tips for sending information to an Express API through AJAX

While working on a website using Express and EJS, I encountered an issue with calling an API via AJAX. The problem arises when passing two values to the AJAX data upon button click, resulting in errors. Despite trying various solutions, I'm still stru ...

Change a text file into JSON by using key-value pairs or headers along with CSV in Python, JavaScript, or PHP

I have a text file with the following format. I would like to convert it to CSV with headers like in or as JSON key-value pairs. Any guidance would be greatly appreciated. ...

How can one achieve the equivalent of Flask Safe when making an ajax call?

Having trouble replicating equivalent functions in my Ajax call as I can in regular Javascript on my main HTML page. Using Python/Flask at the back-end. Any similar methods to use the {{ variable | safe }} syntax in AJAX for similar results? My code snipp ...

Using JQuery to extract information from a JSON file

Here is the code I am working on, where I pass input username and password values. The function I have written checks if the input matches the data in a JSON file. If there is a match, an alert saying "login correct" will be displayed, otherwise it will di ...

Guide on organizing items into rows with 3 columns through iteration

Click on the provided JSFiddle link to view a dropdown menu that filters items into categories. Each item is stored as an object in an array for its respective category. Currently, all items are displayed in one column and I want to divide them into three ...

leveraging insertAdjacentHTML within a React Component

I've been working on a project to replicate the Github contribution grid using React. My approach involves using insertAdjacentHTML to fill the grid container with several divs that I can then customize with styles. Unfortunately, I'm encounter ...

The OrderBy feature may not apply to the initial items being displayed in an ng-repeat loop

Curiously, when attempting to sort by name on an object array, the first 10 or so objects appear random before the orderBy function works correctly. Any suggestions on how to address this issue? Appreciate any assistance! ...

Tips for implementing a document ready function on a nested page within a larger full-page website

I am currently working on a website that utilizes fullpage.js, but the same principle applies to all single-page websites. I am trying to figure out how to implement the $(document).ready() function on a 'nested' page within the site. Since every ...

Save Scope in JSON format

Currently, I am developing a web application that dynamically displays specific prompts based on the field in focus. There are several different texts stored as scripts that I want to showcase at these different points. My goal is to incorporate scope dat ...

Is there a way to access specific methods within a JavaScript file?

Within my javascript assets folder, I have a file named jstester.js that looks like this: function hehe() { alert("wedsdsd"); } document.write("fdygsdfysdgf"); Then in the main index.html file in the public directory, I include the following code: & ...

Upon loading the React Login page, the focus immediately shifts to the 'password' field rather than the 'username' field

I am currently in the process of building a login page using React. The code below is from my input.jsx file where I have imported Bootstrap components. import React from "react"; const Input = ({ name, label, value, onChange, error }) => { ...

Is it necessary for the Jquery Component to return false?

I'm currently working on developing a jQuery module using BDD (Behavior-driven development). Below is the code snippet for my component: (function($) { function MyModule(element){ return false; } $.fn.myModule = function ...

What could be the reason for the initial response appearing blank?

How can I retrieve all the comments of a post using expressjs with mongodb? I am facing an issue where the first response is always empty. Below is the code snippet: const Post = require("../models/posts"), Comment= require("../model ...