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

Wavy CSS Animation

For assistance with my spinning image, please check out this fiddle: https://jsfiddle.net/dricardo1/9a8p6srb/ Hello! I'm struggling with a spinning image that has a noticeable wobble when rotating. I can't seem to find a solution to make the rot ...

Preserve file sequence with jquery file upload

I recently came across an interesting upload script at the following link: This script utilizes jquery file upload to allow for uploading multiple files simultaneously. I'm curious about how to transmit the order in which the files were selected to t ...

Angular model fails to sync with localStorage despite using onChange or ng-change events

So I must admit, I might be making a silly mistake here, but here it goes. I decided to store the gender of my users in localStorage using a $localstorage api with set() and get() methods. In the UI, I implemented an angular range slider just because it l ...

Is it possible to compile TypeScript modules directly into native code within the JavaScript data file?

I am seeking a way to break down an app in a TypeScript development environment into separate function files, where each file contains only one function. I want to achieve this using TS modules, but I do not want these modules to be imported at runtime in ...

Obtain additional information to address concerns related to onZoom and onPan issues on the line

Attempting to enhance my Chart.js line chart by fetching more data or utilizing cached backup data during onZoom/onPan events has proven quite challenging. The original code base is too intricate to share entirely, but I will outline the approaches I have ...

Steps for activating chromedriver logging using the selenium webdriver

Is there a way to activate the chromedriver's extensive logging features from within the selenium webdriver? Despite discovering the appropriate methods loggingTo and enableVerboseLogging, I am struggling to apply them correctly: require('chrom ...

Get data from a JSON file using JavaScript

Dealing with a rather intricate and detailed JSON structure, I have a specific extraction task at hand. The goal is to retrieve information (text) from the JSON only if the resource-id includes the text "com.shazam.android:id/" and certain prope ...

Angular: Displaying the unique identifiers of a single MongoDB record

I am facing an issue with the code snippet in my HTML file: <li ng-repeat="friend in friends"> <span ng-repeat="(key, value) in friend"> <input type="text" ng-model="friend[key]"> </span> ...

Looking to maintain the value of a toggle button in a specific state depending on certain condition checks

I have a situation where I need to keep a toggle button set to "off" if my collection object is empty. Previously, I was using v-model to update the value of the toggle button. However, now I am attempting to use :value and input events, but I am strugglin ...

Trouble initiating a jquery function in componentDidMount in a React component

I have encountered an issue with my ReactJS application. The $(document).ready(function(){}); function stops working after I switch paths using React Router Dom. In order to find a solution, I turned to Google and came across this helpful article: React- ...

The ng-click event for the reset button is limited to a single use

There seems to be a problem with the reset button functionality on my webpage. Although it initially works, it only works once and then requires a reload of the page to function again. Here is the JS code: var ctrl = this; var original_device = angular.c ...

Hiding validation messages upon clicking in a textbox in ASP.NET MVC: a tutorial

When attempting to hide the validation message on click of the textbox, it remains visible. Can someone please provide assistance? <div class="col-md-10"> @Html.TextBoxFor(m => m.Email, new { @class = "form-control", @autoco ...

Tips for validating Enum Strings using the newest version of Joi?

Is there a way to validate Enum String? In the past, I followed this advice from: https://github.com/hapijs/joi/issues/1449 enum UserRole { Admin = 'admin', Staff = 'staff' } const validator = { create: Joi.object().keys({ ...

Issue with Angularjs where changes to the view value are not reflected in the display

I have added an input directive for users to be able to undo actions. When the Enter key is pressed, the value is saved using a specific function, and pressing Esc should cancel edits and revert to the last saved value. However, I'm encountering an ...

What is the best way to generate an error message in AJAX?

It seems that I am facing an issue with throwing an error message to indicate whether an email exists in my user table. I have realized that due to the asynchronous nature of AJAX, try and catch error messages cannot be used within the complete function. E ...

What is the process for accessing a particular field in the data returned by the collection.find method in Expressjs and mongodb

I've been attempting to access a specific field returned from the mongodb collection.find method without success. The console.log is not displaying anything. router.get('/buildings', function(req, res, next) { var db = req.db; var collectio ...

What is the best way to extract the event time when a user clicks on an event in fullcalendar?

Is there a way to extract only the time from an eventclick event in fullcalendar? Currently, I am receiving details about the event including date and time. How can I specifically retrieve just the time (e.g. 6:00:00 am)? You can find the code snippet tha ...

Ways to recycle the output of the three.js fragment shader

Recently delving into GLSL shaders in three.js, I am currently experimenting with creating a simple and efficient blur effect on a mesh texture. Below is the fragment shader code I have been working on: void blurh(in vec4 inh, out vec4 outh, int r) { ...

Access the values within an array located inside a data object by utilizing ng Repeat function

Attempting to utilize ng repeat for extracting values from an array. Below is the HTML code: <ion-list ng-repeat="item in locationresult"> <ion-item > <ion-checkbox ng-repeat="innerItem in item.loc[$index]"> ...

I am looking to incorporate a new "ID" column into my mui data grid table in ReactJS that will incrementally count from 0 to the total number of rows

When displaying data from an API in a datagrid table component with multiple columns, it is necessary to include a column for the ID which should have values ranging from 0 to the number of rows. Currently, the Object_id is being displayed in this cell. T ...