Directive not properly detecting changes in service's array variable

I am experiencing an issue with updating an array in a service and watching for changes. I have a function in a directive-based controller that updates the array in the service. However, the watch function is not being triggered in the link function of the second directive. I am trying to update the scope of a variable in the second directive so that it reflects the changes made by the first directive function in the service.

The Service

var productServices = angular.module('productServices', ['ngResource']);
productServices.factory('PlayerListS', [function() {
    var playerList = [];

    function getList() {
        console.log(playerList);
        return playerList;
    }
    function addToList(name) {
        playerList.push(name);
    }

    return {
        addToList :addToList,
        getList: getList
    }
}]);

The Directives

'use strict';

bands.directive("player",['PlayerListS', function (PlayerlistS) {
return {
    restrict: 'E',
    scope: {
        person:'@person',
        add:'&add'
    },
    replace: false,
    templateUrl: "partials/player.html",
    controller: function($scope, $element, $compile) {
        $scope.playerList = ["A", "B"];
        $scope.add = function(name) {
            PlayerlistS.addToList(name);
            PlayerlistS.getList();

        }

    },
    link: function(scope, el, attrs) {

    }

};
}]);
bands.directive("playerList", ['PlayerListS', function (PlayerlistS) {
return {
    restrict: 'E',
    replace: false,
    template: "<p>Test</p>",
     controller: function($scope, $element, $compile) {
    },
    link: function($scope, $el,$attrs) {
        console.log('added');
        var x = PlayerlistS.getList()

/*THIS IS WHERE THE WATCH IS HAPPENING*/
        $scope.$watch('x', function (newVal, oldVal) {
                console.log("CHANGED");
        }, true);
    }

};
}]);

The Controller

var bands = angular.module('bands', []);
bands.controller('ViewHousesCtrl',  ['$scope', '$element', '$routeParams', '$q',
function ViewHousesCtrl($scope, $element, $routeParams, $q) {

    $scope.playerLis = ["A","B","C"];

}]);

HTML

   <player ng-show="true" person="RandomName" add="add()"></player>
   <player-list ng-show="true" ng-repeat="a in playerLis"></player-list>

Answer №1

When your observer is attempting to monitor a variable named x in the directive scope, it is actually looking at a local variable called x. Since the variable x is not within the scope, the observer does not activate. Essentially, your observer function can be interpreted as follows:

$scope.$watch(function(scope){
    return scope['x'];
}, function (newVal, oldVal) {
    console.log("CHANGED");
}, true);

The reason why it is not functioning as expected is clear. There is no variable $scope.x to monitor. Instead, consider observing the service directly by specifying the watch function like this:

$scope.$watch(function(){
    return PlayerlistS.getList();
}, function (newVal, oldVal) {
    console.log("CHANGED");
}, true);

Answer №2

You made a slight error in your HTML code, the correct format is:

<player-list ng-show="true" ng-repeat="a in playerList"></player-list>

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

What could be causing the malfunction of the v-bind attribute?

I am in the process of developing a straight-forward To-Do List application with VueJS. <template> <div> <br/> <div id="centre"> <div id="myDIV" class="header"> <h2 style="margin:5px">M ...

What steps can I take to stop the browser from refreshing a POST route in Express?

Currently, I am using node along with stripe integration for managing payments. My application includes a /charge route that collects various parameters from the front end and generates a receipt. I am faced with a challenge on how to redirect from a POST ...

AngularJS - utilizing the directive $parsing to evaluate an expression and bind it to the scope object

I have set up my isolated directive to receive a string using the @ scope configuration. My goal is to convert this string into an object on the scope, so that I can manipulate its properties and values. Here's how it looks in HTML: <div directiv ...

Issue encountered while configuring 'innerHTML' in xmlHttp.onreadystatechange function

Trying to create a JavaScript function that changes the innerHTML of a paragraph within an xmlHttp.onreadystatechange function, I encountered an error in the Chrome Console: Uncaught TypeError: Cannot set property 'innerHTML' of null at XMLH ...

Sending information to a subpage through props using a query in the URL triggers a 431 Request Header Fields Too Large error

I have a page called campaigns, and I am facing an issue on the index page where I want to pass data to my dynamic page [campaignId].tsx. Although I can see the data on my dynamic page, the URL links are becoming too long, leading to an HTTP Status code 4 ...

Unable to retrieve iFrame window due to an error

My challenge lies in obtaining the window of an iFrame using this particular code: var frameWindow = document.getElementById("loginframe"); var iWindow = frameWindow.contentWindow; However, I am consistently encountering this error message: Property ...

How can we determine the nL and nH values using an ESC/POS command?

Looking to adjust the printer's head position using ESC / pos commands: ESC $ command sets the absolute horizontal position ESC $ nL nH Trying to figure out how to calculate the values for nL and nH? ...

Having trouble retrieving the full HTML code with the execute_script function in Python while web scraping

Currently, I am in need of HTML code to perform web scraping using Python. The particular website I am working with is that of a real estate agency. Prior to executing the onclick event for a button that changes pages, it is crucial for me to first obtain ...

Creating individual product pages from an array of objects: A step-by-step guide

Is there a way in Next.js to create individual pages for each object in an array with unique URLs? Here is the input array: Input Array const products = [ { url: "item-1", id: 1, name: "Item 1", description: "lor ...

Achieving repetitive progress bar filling determined by the variable's value

JSFiddle Here's a code snippet for an HTML progress bar that fills up when the "battle" button is clicked. I'm trying to assign a value to a variable so that the progress bar fills up and battles the monster multiple times based on that value. ...

Encountering both a CORS error and data in Angular 7

My application is using Angular 7 for the front end and Node.js (express) for the backend. The cors module in the Node.js server.js file is implemented like this: var cors = require('cors') app.use(cors()); When making an API call from the fro ...

Alter and send back an object from within an asynchronous function

I'm struggling to access the updated fields of an object (userTracker) within asynchronous JavaScript code. Even after modifying the object inside a function (fetchUsers), it still returns as undefined. How can I successfully achieve this? This is wh ...

Dot/Bracket Notation: flexible key assignments

I have an item that contains various image URLs accessed through data[index].gallery.first.mobile/tablet/desktop "gallery": { "first": { "mobile": "./assets/product-xx99-mark-two-headphones/mobile/image-gallery-1.j ...

Transitioning to TypeScript: Why won't my function get identified?

I am in the process of transitioning a functional JavaScript project to TypeScript. The project incorporates nightwatch.js Below is my primary test class: declare function require(path: string): any; import * as dotenv from "dotenv"; import signinPage = ...

Utilizing X-editable in an ASP MVC View: navigating the form POST action to the controller

I have been utilizing the X-Editable Plugin to collect user input and perform server submissions. However, I am encountering an error during submission. What adjustments should I make in order to ensure that the x-editable data functions properly with the ...

Struggling to find a solution for your operating system issue?

We are currently attempting to utilize the markdown-yaml-metadata-parser package for our project. You can find more information about the package here. Within the package, it imports 'os' using the following syntax: const os = require('os ...

Using Javascript to Pass Variables to Ajax with getElementById

Struggling to figure out how to effectively pass a Javascript Variable to Ajax and then post it to PHP? While both the Javascript and PHP code are functioning as expected, the challenge lies in transferring the Javascript Variable to Ajax for subsequent ...

When attempting to log an AJAX/JSON request, the console.log statement is displaying 'undefined'

Being new to AJAX, I have encountered an issue that I believe others may have faced as well. Despite numerous attempts and extensive research, I am unable to find a solution to this error. I am confident that it is something simple. Any help would be gre ...

PHP does not receive the uploaded image

I have encountered an issue while trying to create a form for editing a product. Whenever I upload an image, my PHP code is unable to locate the image and throws the following error: Notice: Undefined index: image in C:\xampp\htdocs\pages&bs ...

Vue Dev Tools is not updating data in Ionic Vue 3

There seems to be an issue with the updating of Reactive and Ref data in Vue Dev Tools when changes are made in an input field bound with v-model within a form. The updated data is only visible when I interact with another component and then return to the ...