Changes to an object's properties will not be reflected in Angular

Looking at my object, it appears as follows:

$scope.user = {key: 'j16er48', name: 'Foo', title: 'Bar'}

The template being used is:

<div ng-if="user.key">{{user.name}}</div>

If I directly change the value of the key> property to null or false, the div does not display. However, if I replace the entire object with this:

$scope.user = {key: false, name: 'Foo', title: 'Bar'}

Nothing seems to happen. It appears that Angular continues to monitor the original object and the initial value of the key property.

I attempted using $scope.$apply() after setting a new object for user, but it had no effect.

Is there something I am overlooking?

== UPDATE ==

After numerous tests, I came across an unusual occurrence within the Angular scope. The problem arises from an unintended reference assignment (or possibly a two-way binding).

I have an object named defaultUser defined as:

{key: false, name: 'Foo', title: 'Bar'}
. Consider the following:

var defaultUser = {key: false, name: null, title: null};

$scope.user = defaultUser;

// modifying a property of $scope.user
$scope.user.key = 'j16er48';

$scope.resetUser = function(){
    // At this point, defaultUser.key now equals 'j16er48'
    alert(defaultUser.key);

    // This line has no effect because of the above
    $scope.user = defaultUser;
}

Hence, when attempting to assign defaultUser back to the user object, it seemed like a reset, however, defaultUser had been altered and was now equivalent to user.

Is this behavior normal? Does Angular assume all assignments are by reference? Could this be due to a two-way binding mechanism? Am I missing something here?

https://jsfiddle.net/amraei/g1b5xomz/3/

Answer №1

It appears that you may be working with an outdated version of Angular.

To demonstrate the differences, I have prepared two Fiddles. The first one utilizes Angular 1.1.1 (https://jsfiddle.net/dcg74epp/) and the second showcases Angular 1.2.1 (https://jsfiddle.net/6vy4jn6q/).

Both examples feature a simple controller without adhering to any specific style guidelines, but should help illustrate the main points.

app.controller('TestController', function ($scope) {
  $scope.user = {key: 'j16er48', name: 'Foo', title: 'Bar'};
  var secondUser = {key: false, name: 'Foo', title: 'Bar'};
  var tmp;

  $scope.changeUser = function () {
    tmp = $scope.user;
    $scope.user = secondUser;
    secondUser = tmp;
  };
});

If it is feasible for you to upgrade to a newer Angular version, I recommend doing so.

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

CORS headers present but AJAX request still fails

A request sent via AJAX from a locally hosted page to a remote server is encountering errors, despite the presence of CORS headers. The JavaScript code for this request is as follows: $.ajax({url: 'http://prox.tum.lt/420663719182/test-upload?Action=S ...

Executing HTML code from an AJAX response is a common task when working with web

I am integrating the MyPos payment gateway for debit card purchases. However, I have encountered a strange issue with their SDK. When initiating the payment process, the SDK attempts to output HTML code with a form that will auto-submit to their checkout p ...

Simple way to retrieve the first and last date of the current month using Node.js

I need help with retrieving the first and last date of the current month using the code below:- let currentDate = new Date(); let month = currentDate.getMonth() + 1; console.log(month); let firstDate = new Date(currentDate.getFullYear(), currentDate.getMon ...

I need help fixing the alignment of the lengthmenu and export buttons in Bootstrap Datatables Javascript. They are too close together and I want to create a line break between

I'm currently working on a searchable table that requires users to export their results and choose the number of entries they want to see. However, everything appears too congested. I am looking to create some spacing by adding line breaks, paragraphs ...

The system encountered an error while trying to access the file "/box/main.c" because it does not exist in the directory

Currently, I am working on a project that requires the use of judge0 API. Initially, everything was running smoothly when I utilized it with RapidAPI. However, I made the decision to switch to a self-hosted setup using a docker-compose.yml file. While my ...

Unable to conduct search as search button is malfunctioning

I am experiencing an issue with an input field on my results page. I have implemented the following event: onkeypress="if (event.keyCode == 13) {document.getElementById('results-search').click()}" However, when I try to perform a search, nothin ...

Alpha-Beta Pruning Minimax Algorithm Fails to Determine the Best Move in Tic-Tac-Toe Artificial Intelligence

I have been developing a Tic-Tac-Toe AI system that uses the Alpha-Beta Pruning Minimax algorithm to determine the best move for the AI player (X) on the game board. Unfortunately, I am running into an issue where the algorithm is not returning the correct ...

Challenges with arrays that occur asynchronously

At the end of this code snippet where console.log(authors) is called, I noticed that the array seems to be constantly overwriting itself. Typically, in a loop like this, the async part should be outside the loop. To solve the issue of getting an array full ...

What is the best way to call a function within another function only when a certain div is not clicked?

Throughout my code, I am utilizing the campusInfo(id) function. This particular function, in turn, calls another function named campusInfo_2(HouseID). One scenario where I am invoking campusInfo(id) is when a specific div is clicked. In this instance, I ...

Having trouble retrieving a value from a .JSON file (likely related to a path issue)

My React component is connected to an API that returns data: class Item extends Component { constructor(props) { super(props); this.state = { output: {} } } componentDidMount() { fetch('http://localhost:3005/products/157963') ...

Error message: The provider NavbarController is not recognized - generated by the yeoman

I recently created a project using Generator Angular Fullstack v3.0.2. The server is up and running smoothly, but I encountered an issue on the client side where I received this error in the console: [$injector:unpr] Unknown provider: $locationAuthProvi ...

How can I delay the loading of a link until the pop-up is closed?

I have successfully implemented a pop-up on my website, but I am facing an issue where I need to prevent any linked pages from loading until the visitor clicks on the accept button. However, I am struggling to make it function as intended. Below is the sn ...

Increase the jQuery level and utilize the .find() method

Currently, I am delving into the realm of jquery and facing a minor hiccup with selectors. Below is the structure of my DOM: <li> <header class="title"> <span>Text</span> <a href="#work-1">My trigger</a> ...

the ever-changing dimensions of a PDF document

I'm attempting to display a PDF using an iframe, but I want the height of the viewer to match the document's height, meaning that all 3 pages should be visible without scrolling. How can I achieve this? Here's a simple example I created on ...

Encountering issues with Office.context.document.getFileAsync function

I am experiencing a strange issue where, on the third attempt to extract a word document as a compressed file for processing in my MS Word Task Pane MVC app, it crashes. Here is the snippet of code: Office.context.document.getFileAsync(Office.FileType.Co ...

Iterating over a collection of nested arrays using ng-repeat

I have a data structure that I need to format into a list: public class Topic { [Key] public int ID { get; set; } [Required] public string Name { get; set; } public virtual ICollection<FAQ> FAQs { get; set; } } public class F ...

Efficiently managing desktop and mobile pages while implementing lazy loading in Angular

I am aiming to differentiate the desktop and mobile pages. The rationale is that the user experience flow for the desktop page involves "scrolling to section", while for the mobile page it entails "navigating to the next section." The issue at hand: Desk ...

Developing a large-scale project with compatibility for iPads

Seeking information here. We have a long-standing, sizable product and we're looking to ensure it's compatible with iPads to keep our customers satisfied. The layout appears fine on iPad, but the issue lies with gestures such as scrollable divs. ...

It appears that the .fadeOut() function is not working properly when applied to an image

I want my input text box to automatically submit the form and display a checkmark image after the user has been idle from typing. I tried implementing a fadeout function for the image but it doesn't seem to be working. var timer = null; $('.form ...

What is the best way to reset the size of an element in webkit back to its original dimensions?

I am having an issue with an element that changes to display absolute and covers its parent element on focus via javascript. However, when it goes back to its default state on blur, it does not return to its original position. This problem seems to only o ...