Modifying $rootScope variable in AngularJS does not update the initial selected option in ng-model

There is a particular issue that I just can't figure out.

Within my html code, I have the following:

<select ng-model="$parent.product"  ng-options="i.id_product as i.product for i in productsServer">
   <option>Select</option>
 </select>

And in my controllers:

  $rootScope.product = '1';

Upon the initial page load, the first option is automatically selected. However, if I change $rootScope.product = '1'; to $rootScope.product = '3';, the third option is displayed.

Now, when a different value is selected, it is stored in $rootScope.product. But later on, in a certain function, I attempt to reset $rootScope.product back to '1' and it doesn't seem to work.

What am I overlooking here?

P.S. Without $parent.product, the select component does not update the $rootScope.product value.

EDIT: Here is the additional function:

$rootScope.inputData = function() {
      setTimeout(function () {
      $rootScope.product = '1';
      $scope.$apply();
       }, 2000);
      $state.go('app.grid_settings', {}, {
        reload: true
      });

The inputData function is triggered by clicking a button.

Answer №1

When using ng-model='$parent.proizvod', it is not always guaranteed to update $rootScope.

Many new AngularJS developers are unaware that directives such as ng-repeat, ng-switch, ng-view, ng-include, and ng-if create child scopes, which can lead to issues when working with them.

AngularJS Wiki - Understanding Scopes

When ng-model sets a value in a child scope, it creates a new property that hides or shadows the parent property with the same name. This behavior is due to JavaScript prototypal inheritance, not AngularJS. Refer to the Wiki for more information.

This raises the question of whether to use $parent.$parent.proizvod or even $parent.$parent.$parent.proizvod. Is trial and error the best method?

A more reliable approach is to utilize the ng-change directive to update the variable.

<select ng-model="vm.proizvod" ng-change="vm.update()"
        ng-options="i.id_proizvod as i.proizvod for i in proizvodiServer">
   <option>Select</option>
</select>
vm.update = function () {
    $rootScope.proizvod = vm.proizvod;
    console.log($rootScope.proizvod);
});

Instead of relying on $rootScope, consider creating a custom service to store variables.

$rootScope can be used for good or evil

In AngularJS, scopes form a hierarchy by inheriting from a root scope at the top. Usually, this can be overlooked as most views have their own controllers and scopes.

There are instances where certain data needs to be globally accessible across the app. In such cases, values can be set on $rootScope just like any other scope. However, it is advised to use $rootScope sparingly and only for data, not functions.

— AngularJS FAQ


Opt for $timeout over window.setTimeout

$rootScope.upisPodataka = function() {
      $timeout(function () {
         $rootScope.proizvod = '1';
      }, 2000);
      $state.go('app.podesenost_grilla', {}, {
        reload: true
      });
};

The $timeout service is recommended over window.setTimeout as it integrates smoothly with AngularJS and avoids the need for $apply().

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

Customize CSS to target the first and last elements in a row using flexbox styling

I am facing a challenge in selecting the last element of the first row and the first element of the last row within a flex container. The setup involves a flex-wrap: wrap; for my flex container where all elements have flex: auto; with different sizes. Thi ...

Synchronizing timers among different elements

Just a little context: I'm diving into the world of React and currently working on a small app using next.js (with a template from a tutorial I followed some time ago). Lately, I've encountered a challenge where I need to synchronize a timer betw ...

React.js TypeScript Error: Property 'toLowerCase' cannot be used on type 'never'

In my ReactJS project with TSX, I encountered an issue while trying to filter data using multiple key values. The main component Cards.tsx is the parent, and the child component is ShipmentCard.tsx. The error message I'm receiving is 'Property &a ...

Challenges with managing VueJS methods and understanding the component lifecycle

I'm facing an issue with my code. The function retrieveTutorials() is not transferring the information to baseDeDatosVias as expected. I've attempted to change the function to a different lifecycle, but it hasn't resolved the problem. The so ...

Trigger a drop-down list in React when typing a specific character, like {{ or @, in an input field

Is there a way in React.js to display a list or dropdown when a user types a certain character like '@' or '{{ }}' in the input text area? The user should be able to select an option from this list and have it inserted into the text are ...

Adequate dynamic object arrangement

In my pursuit using JavaScript, I am striving to fit a group of objects of set sizes into a container with a specified horizontal width, all while preserving their approximate initial order. While whitespace is not a major concern, the goal is to keep it t ...

The Bcrypt hashed password does not match the password hash stored in Mongodb

When I use bcrypt.hash to encrypt a password, the hash generated is normal. However, when I save this hashed password in MongoDB using Mongoose, it appears to be different from the original hash. For example: Password hash: $2b$10$bUY/7mrZd3rp1S7NwaZko.S ...

Embed fashion and graph elements into a CSV document (generated from <script>)

Encountering an issue with my code. I am looking to export an HTML table to a CSV file (specifically Libre Office Calc, regardless of csv, xls or xlsx format, as long as it runs on a Linux Server). Found a script online that works well after some modificat ...

What is the Best Way to Retain My Firefox Settings While Handling a JavaScript Alert?

I'm encountering an issue when trying to download a file by clicking on a link. I have set my Firefox preferences to save the file in a specific location. However, upon clicking on this particular link, a popup appears that I must accept before the do ...

Using JavaScript to manage form input values in React

I am currently coding a basic application using NextJS and bulma CSS. The snippet below shows the form I am working on: const MyPage = () =>{ const [firstName, setFirstName] = useState('') const [secondName, setSecondName] = useState('&ap ...

Exploring the depths of deep populating in Mongo and Node.js

I am currently struggling with a complex data population issue. var commentSchema = mongoose.Schema({ name: String }); var userSchema = mongoose.Schema({ userId: { type: String, default: '' }, comments: [subSchema] }); var soci ...

Issue: In an Angular electron app, a ReferenceError is thrown indicating that 'cv' is

I have been working on a face detection app using OpenCv.js within an Angular electron application. To implement this, I decided to utilize the ng-open-cv module from npm modules. However, when attempting to inject the NgOpenCVService into the constructor ...

Utilizing an array as a child component in conditional rendering with vue.js

I have a Laravel API and the front end is built with Vue.js + Laravel. I am fetching data from the API and passing it to the view. Now, I want to implement conditional rendering based on certain criteria. Here's what my array looks like: "data" =&g ...

Challenges in developing complex single-page applications

Currently, I am in the process of developing an extensive single-page web/javascript application that is going to be quite large. The technologies I am utilizing include ASP.NET MVC4, jquery, knockout.js, and amplify.js. One obstacle I am encountering is ...

Safari's cross-site tracking feature is preventing the transmission of cookies from the Express session

After developing an app that utilizes passport and express session for authentication, I encountered an issue when deploying it. Safari was not allowing express session to work until I disabled 'cross site tracking' in the browser's settings ...

When resizing the window in IE8, the function DIV offsetWidth/Width/innerWidth returns a value of zero

My page is filled with many elements, one of which is the following DIV: <div id="root"> .................. <div id="child1"> ............. </div> <div id="child2"> ............... </div> & ...

Show me a way to use jQuery to show the number of images of a particular type that are on a

My webpage features 6 different images, including 4 of various balls such as basketball and baseball. One image is of a truck, while the last one is random. On the page, there is a form with two radio buttons allowing users to select which type of image c ...

unable to establish a secure connection to the specified URL within my application

I am facing an issue with my form that includes hidden values which need to be sent to a URL upon submission. The URL is for secure card payment purposes, and when I try to process it through my app by opening the URL and sending the hidden values, the con ...

Utilizing a self-invoking function to incorporate JavaScript

In my role, I am responsible for managing a Content Management System (CMS) used by developers to create content that involves JavaScript. In the past, we placed the content in an iFrame for containment purposes; now, it operates as a single-page client-si ...

What are some strategies for creating a recursive function in JavaScript that avoids exceeding the maximum call stack size error?

I need assistance creating a walking robot function in JavaScript, but I am encountering a call stack size error. function walk(meter) { if(meter < 0) { count = 0; } else if(meter <= 2) { count = meter; ...