AngularJS: Modifying directive according to service value update

In my current application, I have a basic sidebar that displays a list of names fetched from a JSON call to the server. When a user clicks on a name in the sidebar, it updates the 'nameService' with the selected name.

Once the 'nameService' is updated, I want the 'nameData' view to trigger another JSON call to the server for the corresponding JSON file based on the clicked name.

My AngularJS app consists of two controllers and a service:

app.js

var app = angular.module("myapp", ['ui.bootstrap']);

app.directive("sideBar",  ['$http', 'nameService', function($http, nameService) {
    return {
        restrict: 'E',
        templateUrl: "views/sidebar.html",
        controller: function($scope) {
            $scope.updateName = function(name) {
                nameService.setName(name);               
            }; 

            $http.get('../data/names.json').
                success(function(data, status, headers, config) {
                    $scope.names = data;
            });         
        }
    };
}]);

app.directive("nameData",  ['$http', 'nameService', function($http, nameService) {
    return {
        restrict: 'E',
        templateUrl: "views/name-data.html",        
        controller: function($scope) {
            $scope.service = nameService;

            var path = "../data/" + $scope.service.name + ".json";

            $http.get(path).success(function(response) {
                $scope.info= response.info;
            });
        }
    };  
}]);

app.service('nameService', ['$http', function($http) {
    this.name = "TestName";

    this.setName = function(name) {
        this.name = name;
    };

    this.getName = function() {
        return this.name;        
    };
}]);

I am struggling to update the 'nameData' view when the 'nameService.name' property changes due to a click event on the sidebar.

I attempted using a watch on $scope.service.name, but it did not work as expected.

Is there a way to leverage the power of Angular to dynamically fetch new JSON data whenever a new name is selected from the sidebar?

Answer №1

Perhaps using angular event broadcasts could be a solution?

To implement this, add rootScope to the service and broadcast an event when the name changes:

app.service('nameService', ['$http','$rootScope', function($http,$rootScope) {
  this.name = "TestName";

  this.setName = function(name) {
      this.name = name;
      $rootScope.$broadcast('nameService-nameChanged');
  };

  this.getName = function() {
      return this.name;        
  };
}]);

Then, in your directive controller scope, bind to that event:

app.directive("nameData",  ['$http', 'nameService', function($http, nameService) {
    return {
        restrict: 'E',
        templateUrl: "views/name-data.html",        
        controller: function($scope) {
            $scope.service = nameService;

            //Converted your loading mechanism into a function
            $scope.loadNameData = function(){
               var path = "../data/" + $scope.service.name + ".json";

               $http.get(path).success(function(response) {
                  $scope.info= response.info;
               });
           }
           //Initial load
           $scope.loadNameData();

           //Subscribe to the broadcast event, triggering $scope.loadNameData when 'nameService-nameChanged' is broadcast
           $scope.$on('nameService-nameChanged',$scope.loadNameData); 

        }
    };  
}]);

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

Tips for sending multiple values in a data object using jQuery AJAX

I am currently working on a form that contains two input fields, with the possibility of more being added later. The first input is a text field and the second is a checkbox. I want to be able to send these inputs using $.ajax. To accomplish this, I have ...

Setting an Alias for AVA Tests: A Step-by-Step Guide

I need to set up global aliases in my project without using Webpack or Babel. Currently, I am testing with AVA. The npm package module-alias allows me to define aliases in my package.json file. However, when I try to create a basic example following the d ...

Modify every audio mixer for Windows

Currently working on developing software for Windows using typescript. Looking to modify the audio being played on Windows by utilizing the mixer for individual applications similar to the built-in Windows audio mixer. Came across a plugin called win-audi ...

Enhance the appearance of the jQuery document.ready function

I'm attempting to customize the jQuery document.ready function <html> <head> <script src="http://code.jquery.com/jquery-1.11.0.min.js"></script> <script type="text/javascript> $(function() { c ...

Guide on parsing and totaling a string of numbers separated by commas

I am facing an issue with reading data from a JSON file. Here is the code snippet from my controller: myApp.controller("abcdctrl", ['$scope', 'orderByFilter', '$http', function ($scope, orderBy, $http) { console.log('abc ...

Issue with cross-origin in Salesforce reply (Access-Control-Allow-Origin)

While attempting to retrieve records from Salesforce using external local files via JS, I encountered an issue. Although I can see a response in the network tab, the console displayed the following error message: "XMLHttpRequest cannot load . No 'A ...

Removing cookies after sending a beacon during the window unload event in Chrome

Here's the situation: I need to make sure that when the browser is closed or the tab is closed, the following steps are taken: Send a reliable post request to my server every time. After sending the request, delete the cookies using my synchronous fu ...

An issue with the image filter function in JavaScript

I am currently working on a simple application that applies image filters to images. Below is the code I have written for this purpose. class ImageUtil { static getCanvas(width, height) { var canvas = document.querySelector("canvas"); canvas.widt ...

Encountering a Blank Area at the Top of a Printed AngularJS Screen

Currently, I am tackling an issue in AngularJS while working on the Print Invoice Page. The problem I am encountering is a blank space at the top of the printed screen. Check out the image here Below is my code: HTML <div id="invoice" class="compact ...

Explore a personalized color scheme within MUI themes to enhance your design

I'm looking to customize the colors in my theme for specific categories within my application. I set up a theme and am utilizing it in my component like this: theme.tsx import { createTheme, Theme } from '@mui/material/styles' import { red ...

Can JavaScript be used to modify the headers of an HTTP request?

Can JavaScript be used to modify or establish HTTP request headers? ...

Tips for defining header and parameters when using route.get in Node.js

Looking to add custom headers and parameters when using route.get in Node.js? I am trying to set a specific value for the header and pass parameter values in the API URL. router.get("/getdata", async (req, res) => { // Set custom header re ...

Guide to creating dynamic borders around your PHPexcel output

Looking for assistance on adding borders around output arrays in an Excel report using PHPexcel. I reviewed the documentation, but the examples are static, requiring a predefined number to set. My goal is to have all arrays transferred to Excel with bord ...

Enhancing user privacy in Angular application with Web API integration and ASP.NET Identity

Currently, I have an AngularJS application that is connected to an ASP.NET Web API backend with OWIN/token-based authentication. The backend utilizes ASP.NET Identity for user registration and login functionalities. Both the frontend and backend are inte ...

Trouble with scrolling on Kendo chart while using mobile device

I am facing an issue with multiple kendo charts on my website. These charts have panning and zooming enabled, but in the mobile view, they take up 100% of the width which causes touch events to not work properly for scrolling. I attempted to attach an even ...

What is the best way to retrieve information from a JSON string?

I am currently receiving a JSON object from the backend and I only need the "result" array in my Angular application template variable. { "result":[ {"name":"Sunil Sahu", "mobile":"1234567890", "emai ...

Vue.js error: Reaching maximum call stack size due to failed data passing from parent to child component

I'm having trouble passing data from a parent component to a child component. I tried using props and returning data, but with no success. The parent component is a panel component that contains the data, while the child component is a panelBody. Thi ...

Error Unhandled in Node.js Application

I have encountered an issue in my NodeJS application where I have unhandled code in the data layer connecting to the database. I deliberately generate an error in the code but do not catch it. Here is an example: AdminRoleData.prototype.getRoleByRoleId = ...

Handling routerLink exceptions in Angular 2, 4, and 5

In my app, I am working on catching routing exceptions. There are three ways in which a user can navigate: If the user types the address directly - this can be caught easily by using { path: '**', redirectTo: 'errorPage'} in the route ...

Retrieve items from an array using a series of nested map operations

When I execute the query below, it transforms the json data into objects - 1st level being a map (This works fine as expected) const customerOptions = () => { return customersQuery.edges.map(({ node: { id, name } }) => { return { key: id, text ...