Updating Angular.js scope after a variable has been modified

On my website, I have implemented a search bar that communicates with a controller receiving JSON responses from the server.

The response is stored in a global variable called assetResult. It works as expected initially; however, subsequent searches do not update the $scope of the searchResultController.

SEARCH BAR CONTROLLER


mwm3.controller('searchBarCtrl', function($scope, $location, $timeout, AssetService) {
    $scope.radioValue = 'id';
    AssetService.connect();
    AssetService.subscribe(function(message) {
        var obj;
        try {
            obj = eval("(function(){return " + message + ";})()");
            AssetResult = obj;
            console.log(message);

            $location.url('/searchResult');
        } catch (e) {
            obj = eval("(function(){return " + message + ";})()");
            alert(obj.Error);
        }
    });

    $scope.send = function() {
        AssetService.send($scope.radioValue + '=' + $scope.searchKey);
    };

});

SEARCH RESULT CONTROLLER


mwm3.controller('searchResultCtrl', function($scope, $location, AssetDetailService) {
    $scope.$apply(function() {
        $scope.asm = AssetResult;
    });

    if (!AssetResult) {
        $location.url('/login');
    }
});

In my searchResultController, I've tried using $scope.apply to refresh the associated view, but it doesn't seem to work. What could be causing this issue?

Any insights would be greatly appreciated. Thank you in advance!

Answer №1

Upon my observation, it seems that the communication from the AssetService is not triggering a fresh angular digest cycle. To address this issue in your searchBarCtrl, consider the following adjustment:

Update AssetResult with the provided obj;
Invoke $scope.$apply();

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

Efficient method invocation for objects within an array using functional programming techniques

Is there a way to execute a method that doesn't require arguments and doesn't return anything on each object within an array of objects that are all the same type? I've been trying to find a solution without resorting to using a traditional ...

Jest-Native encountered an error: "SyntaxError: Unable to use import statement outside of a module"

Trying to perform unit testing using https://github.com/callstack/react-native-testing-library along with https://github.com/testing-library/jest-native. I am able to test plain JavaScript files without any issues, but I am facing an error when testing com ...

Managing a secure login page with Protractor

Our team is currently exploring how to implement AngularJs and Polymer components in a new web application. I am tasked with creating a UI automation suite for this project. After conducting extensive research, it seems that Protractor could be the right t ...

JS: The for loop will keep iterating even if the condition becomes false

Can anyone help me understand why my for loop is continuing even after the conditions are met? Unfortunately I can't share the entire file due to its size, but here is a snippet of the loops: for (var j = 0; j < depKeyArr.length; j++) { var di ...

Injecting dependencies in AngularJS when utilizing the controller-as syntax: A how-to guide

As I dive into the controller-as feature outlined in the documentation, I'm refining one of my controllers to align with their recommended syntax. However, I'm facing a challenge when it comes to injecting the $http service into my search() funct ...

Generating new objects from API request in React and aggregating them into a single, comprehensive object

I have developed a program that utilizes Axios to fetch data through API calls. I aim to save the fetched result as an object within my this.state.matrixDictionary variable. However, each time I make another API call, the previous object gets replaced. My ...

Get a file from a distinct internal server than the one where the website is operating

I am trying to download a file from an internal server that is separate from the one where the website is hosted. I have attempted various methods such as... <a href="javascript:Start('file://servername/path/filename.txt')> <a href="// ...

What is the reason for adding CSS styles to a JavaScript file without importing them?

/Navbar.js/ import './navbar.scss'; import {FaBars, FaSearch} from "react-icons/fa"; import { useState } from 'react'; function Navbar(){ const [hide,sethide] = useState(true); const barIcon = document.querySelectorAl ...

AngularJS: Issue with scope not updating across several views

Having one controller and two views presents a challenge. ClustersController angular.module('app.controllers').controller('ClustersController', [ '$scope', 'ClustersService', function($scope, ClustersService) { ...

Converting JSON to JavaScript Date using UTC time

I am struggling with formatting the dates in a JSON object to work with highcharts. The JSON looks like this: [ [ "26-Sep-14", 10 ], [ "29-Sep-14", 75 ] ] Highcharts requires dates to be in the format Date. ...

Attempting to modify the state within a nested object located in an array by using json data

My objective is to retrieve data from the Google Books API, which returns JSON data in a similar format to what my state displays. I aim to update the title with the title string provided by the JSON data. Currently, I am encountering a "failed to compile" ...

Adjust the size of an image within a canvas while maintaining its resolution

My current project involves using a canvas to resize images client-side before uploading to the server. maxWidth = 500; maxHeight = 500; //handle resizing if (image.width >= image.height) { var ratio = 1 / (image.width / maxWidth); } else { var ...

The issue with Angular's ngDialog not displaying the model data within the $scope

Experiencing persistent troubles with ng-dialog accurately displaying model data. My application involves the use of two separate ng-dialog instances: one for adding data related to a League, and another for editing existing data. Both dialogs utilize the ...

Revamping status and backend systems

Seeking advice on the most effective method to execute a HTTP PUT request within my react application. A Post component is responsible for fetching data from https://jsonplaceholder.typicode.com/posts/1 and displaying it. There's another component na ...

Encountering a problem in a NextJS application where an error occurs stating "cannot read property of undefined (reading setState)" within

In an attempt to resolve the issue, I have linked the method to this inside the constructor. Additionally, I have utilized the arrow function technique to address the problem at hand. Despite these efforts, I continue to encounter the following error: Unha ...

Tips for utilizing express in your typescript projects

I'm curious about the transition of definition files from tsd to typings, and now to @types. How can I incorporate @types in a node/express project? What is currently preferred and what's the reason for moving from tsd to typing and finally to @t ...

Does writing JavaScript code that is easier to understand make it run slower?

While browsing the web, I stumbled upon this neat JavaScript program (found on Khan Academy) created by another user: /*vars*/ frameRate(0); var Sz=100; var particles=1000; scale(400/Sz); var points=[[floor(Sz/2),floor(Sz/2),false]]; for(var i=0;i<part ...

Utilize AngularJS to interact with JSON data

Greetings, I trust you are doing well. I have successfully created an API using PHP to fetch data from SQL and convert it into JSON. However, I am facing a challenge in manipulating the PHP code to retrieve the JSON data as per my requirements. I believe ...

Modify a property within an object and then emit the entire object as an Observable

I currently have an object structured in the following way: const obj: SomeType = { images: {imageOrder1: imageLink, imageOrder2: imageLink}, imageOrder: [imageOrder1, imageOrder2] } The task at hand is to update each image within the obj.images array ...

How can we efficiently iterate through an array in Node.js while making asynchronous calls?

I need to iterate through an array, pushing a new Thing to a list in the process. The Thing itself performs asynchronous calls. However, I am facing an issue where my for loop is synchronous but the new Things are asynchronous, causing the callback to be c ...