What is preventing $scope.$watch from functioning in AngularJS?

I'm struggling to get a $watch function to monitor changes in $scope.data. Here's the code I've been working with:

[http://jsbin.com/biqesojaqu/1/edit?html,js,console,output][1]

app.html

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js"></script>
  <meta charset="utf-8">
  <title>JS Bin</title>
</head>
<body ng-app="App" ng-controller="TestController">
<div>
  <ul>
    <li ng-repeat="item in data"> {{ item.name }}--{{ item.status }}</li>
    <button ng-click="addOnePerson()">ADD</button>
  </ul>
</div>
</body>
</html>

app.js

var App = angular.module("App", []);

App.controller('TestController', function ($scope) {
  $scope.data = [
    {name: 'cc', status: true},
    {name: 'bob', status: false}
  ];
  $scope.name = 'nataila';
  $scope.addOnePerson = function () {
    var personCount = $scope.data.length;
    personCount += 1;
    $scope.data.unshift({name: 'cc'+personCount, status: true});
  };
  $scope.$watch('data', function (){
    console.log('has changed');
  });
});

After clicking the button, I expected the console to output has chenged, but nothing happens. Can anyone explain why this is the case? Your help on JSbin would be greatly appreciated.

Answer №1

Utilize the $watchCollection method when working with an array or object

$scope.$watchCollection('data', function (){
  console.log('change detected');
});

JSBin link

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

Working with three.js: Implementing an external texture in a glTF file

In my quest to apply a texture file to a 3D model using three.js, I've hit a roadblock. Despite days of research and numerous attempts, I just can't seem to get it right. Here is the method I've been using to set the current object in the sc ...

What is the method for running code once the $digest cycle has finished?

I have created a sortable list in my Angular Controller that gets populated with data. This list includes an extra element with controls that can also be dragged. My goal is to ensure that the extra element remains in place after the $digest cycle runs, s ...

Organizing Results into Divs Based on Column Value Using AngularJs

I've been racking my brain trying to figure out the best way to organize and display my results in separate divs, specifically using Bootstrap col-md-4's. This is for a chat messaging app that I'm in the process of developing. I have rooms a ...

Checking the status of an object using a Jasmine spy call in an Ajax method

Currently, I am unit testing an Angular controller that relies on a Rails Resource factory to manage data exchange with a Rails application. Specifically, POST requests are handled by calling a method on the model, like so: $scope.resource.update().then(s ...

PHP issues caused by Ajax form compatibility

I'm currently working on developing an upload website and I've encountered some challenges while trying to implement an upload progress bar. The Ajax form in my scripts seems to be causing issues with the PHP code, preventing the file from being ...

Placing a dropdown menu on top of an image

I currently have a slightly rotated menu bar with two buttons as an example: https://i.stack.imgur.com/0sI2P.jpg Due to the rotation, normal HTML handling is not feasible. I am considering using a <map> element to create hyperlinks over the menu it ...

Toggle between bold and original font styles with Javascript buttons

I am looking to create a button that toggles the text in a text area between bold and its previous state. This button should be able to switch back and forth with one click. function toggleTextBold() { var isBold = false; if (isBold) { // Code t ...

What is the process for switching a button on and off?

I am attempting to add a data to an array when a button is pressed, and then remove it from the array when the button is pressed again (while also changing the button's class). <button *ngFor="#color of colors" [class.selected]="color = ...

The data in the viewmodel remarkably aligns with the data stored in $sessionStorage

I have a scenario where I store a list of objects in the $sessionStorage. In one of my controllers, I retrieve this list and display it on the page, allowing the user to delete items from it. The issue arises when an item is deleted from the view model as ...

React encountered an abrupt end of JSON input unexpectedly

As I embark on my coding journey, I am delving into the world of React. However, as I try to create a new app, I encounter an error message stating "unexpected end of JSON input." While installing packages and waiting patiently, the console throws an err ...

Incorporating an external TypeScript script into JavaScript

If I have a TypeScript file named test.ts containing the code below: private method(){ //some operations } How can I access the "method" function within a JavaScript file? ...

Encountered an error while trying to load a resource: the server returned a 404 (Not Found) status code while attempting to edit a form using

I am facing an issue with navigating to the correct path after editing a form in React. Following the update, the web page refreshes and unexpectedly logs me out of the site even though there are no errors detected during the process. The console displays ...

Encountering an Error with "Access-Control-Allow-Origin" Request While Trying to Access the API

I'm currently facing an issue with fetching data from the Rescue Time API. My request is made in a JavaScript file using the jQuery get() method. Below is the snippet of JavaScript code related to the API GET request: $.get('https://www.rescueti ...

AngularJS or Angular 2: Reorganize the JSON data once the 'http' response is received

Updated: [{ "name": "b1", "category": "X1", "amount": 15 }, { "name": "b3", "category": "X1", "amount": 35 }, { "name": "b2", "category": "X1", "amount": 25 }, { "name": "b1", "category": "X2", "amount": 150 }, { "name": "b6" ...

Ways to ensure certain code is executed every time a promise is resolved in Angular.js

Within my Angular.js application, I am executing an asynchronous operation. To ensure a smooth user experience, I cover the application with a modal div before initiating the operation. Once the operation is complete, regardless of its outcome, I need to r ...

Encountering an error message stating "Unable to read property 'map' of undefined while attempting to create drag and drop cards

I have incorporated the library available at: https://github.com/clauderic/react-sortable-hoc The desired effect that I am aiming for can be seen in this example: https://i.stack.imgur.com/WGQfT.jpg You can view a demo of my implementation here: https:// ...

Modify the second dropdown list using Jquery when the first dropdown list changes

I have encountered an issue with using two dropdown lists. Specifically, I am trying to implement a feature where if the user selects the option "2" in the first dropdown list, a script should be executed. Here is the script: $('select[name="servic ...

Transforming a massive JSON object into a Blob concerns directly converting it into an ArrayBuffer or Blob to prevent exceeding the maximum string length error

Situation: Within my application, I am encountering the following code: let blob = new Blob([JSON.stringify(json)], {type: "application/json"}); This code sometimes fails because the maximum string length allowed in Chrome is approximately 500M ...

Angular: Design dependent on attributes

Can I customize the styling of a div in accordance with a boolean property called "isActive" on my controller using Angular? <div class="col-md-3" (click)="isActive = !isActive"> <div class="center"> <i class="fa fa-calendar"& ...

Creating distinctive ng-form tags within a form using ng-repeat in Angular

I need help with creating a form that includes a table looping over a list of objects. Each object should have checkboxes for the user to check/uncheck attributes. The issue I am facing is setting the ng-model attribute on the checkboxes. This is what my ...