Issue with $scope.$watch function inconsistency

In my sign-in form, I am facing an issue with handling errors. The form slides in from the left using a custom directive. However, when I try to slide it out of sight, I need the current error to disappear as well. I have tried using a $watch function to monitor changes in the sharedInfo.getError() service function. Unfortunately, the $watch function only runs once when the controller loads and then stops listening for further changes. I have used similar methods successfully in the past, so I am struggling to figure out why it is not working now. Any help in identifying the problem would be greatly appreciated.

Here is the code for the controller:

forumApp.controller('signinCtrl', ['$scope', 'fbRef', 'validation', 'userLogic', 'sharedInfo', function($scope, fbRef, validation, userLogic, sharedInfo) {

    $scope.$watch('sharedInfo.getError()', function(newValue, oldValue) {
        console.log(oldValue);
        console.log(newValue);
        $scope.error = newValue;
    });

    $scope.user = {
        email: '',
        password: ''
    }

    $scope.validate = function() {

        $scope.error = validation.validateSignin($scope.user, $scope.error);

        if ($scope.error) {
            return false;
        }
        else {
            userLogic.signinUser($scope.user).then(function(authData) {
                sharedInfo.setAuthState(authData);
            }).catch(function(error) {

                switch (error.code) {

                    case 'INVALID_USER': 
                        $scope.error = 'Invalid email';
                        sharedInfo.setError($scope.error);
                        break;

                    case 'INVALID_EMAIL': 
                        $scope.error = 'Invalid email format';
                        sharedInfo.setError($scope.error);
                        break;    

                    case 'INVALID_PASSWORD': 
                        $scope.error = 'Invalid password';
                        sharedInfo.setError($scope.error);
                        break;
                }
            });
        }
    }
}]);

The sharedInfo service which manages shared information across controllers:

forumApp.service('sharedInfo', [function() {

    var authState;
    var error;

    return {
        getAuthState: function() {
            return authState;
        },
        setAuthState: function(authData) {
            authState = authData;
        },
        getError: function() {
            return error;
        },
        setError: function(newError) {
            error = newError;
        }
    }
}]);

The directive responsible for sliding the form in and out:

forumApp.directive('mySigninSlide', ['sharedInfo', function(sharedInfo) {
    return {
        restrict: 'A',
        link: function($scope, element, attrs) {

            element.on('click', function() {

                var sidebar = $('#signin-wrapper');

                if ($scope.isAnimated === undefined || 
                    $scope.isAnimated === false) {

                    sidebar.stop().animate({left: '340px'});
                    $scope.isAnimated = true;
                }
                else {
                    sidebar.stop().animate({left: '-606px'});
                    $scope.isAnimated = false;
                    sharedInfo.setError('');
                }
            });
        }
    };
}]);

Answer №1

One alternative could be to assign sharedInfo to the scope.

$scope.sharedInfo = sharedInfo;
$scope.$watch('sharedInfo.getError()', function(newValue, oldValue) {
  ...
});

Answer №2

In order to truly watch something, you must engage with and understand its value.

$scope.$watch(sharedInfo.getError(), function(newValue, oldValue) {
        console.log(oldValue);
        console.log(newValue);
        $scope.error = newValue;
    });

Alternatively

$scope.$watch(function () { return sharedInfo.getError(); }, 
  function(newValue, oldValue) {
    console.log(oldValue);
    console.log(newValue);
    $scope.error = newValue;
});

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

Include IE-specific stylesheet code in your Angular application (version 1.2)

I would like to implement conditional IE CSS for IE8 and IE9 in my Angular application. The approach I took was to add the specific CSS files directly in the index file as shown below: <!-- Application main stylesheet --> <link href="styles/them ...

What is the best way to save NeDB objects in a database?

I am looking to leverage NeDB as a database for a straightforward ExpressJS application. My goal is to store collections of objects in a separate file, with each collection residing in its own file (e.g., orders.json). However, the issue I am facing is tha ...

What is the best way to execute a code once another has successfully completed its run?

Within milliseconds, I am required to update a JSON file with new data and then fetch that updated information. However, after posting the data into the JSON file, it appears that when attempting to retrieve it, the old data is returned instead of the newl ...

Modify the table row and column background when hovered over

New to using angularJS. I have a bootstrap table filled with data using ng-repeat. The layout is like a matrix, with both row and column headers. How can I highlight the entire td row and column when hovering over a specific table cell? Currently, I have ...

Trying out the Deezer app and receiving the message: "Please provide a valid redirect URI."

While testing an application using the Deezer JavaScript SDK, I encountered an issue when trying to login as it prompted me with a "You must enter a valid redirect uri" message. Here is the setup: DZ.init({ appId: '000000', channelUrl: ...

Uploading files with node.js and express

Currently, I am following the steps outlined in this tutorial: I have successfully followed the instructions until the section where they set up the routes without actually creating any views. The tutorial states: That's it, we have completed sett ...

Connecting a Tailored Event to an Angular Component

Attempting to implement a collapsible component, I would like to bind a custom toggle event to the HTML element. <button class="btn btn-primary" (click)="content.toggle()">Toggle Content</button> <div #content appCollapse ...

What is the method to make a file download using JavaScript?

In my jQuery ajax form, a user inputs their email and upon submission, they should receive an automatic download of a file. Here is the structure of the form: $(".email-form").submit(function(event) { event.preventDefault(); var $form = $(this), ...

Transfer an array into data using the POST method

When making a REST API call in CodeIgniter, I encountered an issue with the array format being sent to the server: [{"PMcolor":"Azul tostado","PMpartes":"Un poquito de las orjeas y un bigote a lo Dali, quizas le alegre la cara","PMcosteTotal":"445"}]: Th ...

Updating the user interface in react-apollo following a delete mutation

After successfully executing a delete mutation in my React Apollo component, the UI of my app did not update as expected. Here is the code snippet for reference: const deleteRoom = async (roomId, client = apolloClient) => { const user = await getUser ...

Obtaining the Current Component Instance in SolidJS

Is it possible to retrieve the Component that is currently active in SolidJS, along with its props, signals, internal state, effects, etc.? I'm searching for a solution similar to React's __SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCu ...

Is there a way to extract the text that lies between two closed HTML

Looking for a solution using jQuery. <pre><marker id="markerStart"></marker> aaaaa <span style='font-family:monospace;background-color:#a0a0a0;'>bbb</span>bb cc<marker id="markerEnd"></marker>ccc </pr ...

Does embedding an Iframe for external files from your server enhance the loading speed of the current page compared to directly loading it on the page?

I'm facing an issue with the loading time of a Facebook post on my webpage index.php. The current method of using the embedded post provided by Facebook is taking too long to load. My solution is to create a separate page, post.php, where only the Fac ...

Create a customizable Tree structure that includes checkboxes for each item and features drag

I am currently working on incorporating a Tree view with checkboxes and drag & drop functionality in Vue. However, I am unsure of where to begin. While I have successfully implemented checkboxes, I am struggling to figure out how to enable the feature whe ...

Dynamic addition of CSS classes to HTML elements using PHP

I'm working on developing an application that includes multiple courses. Each course is completed over a certain number of days, such as 14 days or 20 days. To visually track progress, I've implemented a step progress bar that looks like this:htt ...

When the document exists, the findOne() method returns null

Running locally, but accessing an atlas MongoDb DB online, I have builder's data like this: [ { "_id": "5ec63e97516541c07c2b26d3", "name": "Bob" }, { "_id": "5ec64261b9be7b08cb8d7ba9", "name": "builder post test" } ] Although s ...

Using AngularJS to apply conditional ngStyle

Can I achieve a similar effect to this using the following code: <span data-ng-style="vm.myFlag ? 'background-color:{{myObject.color}};padding:2px;border-radius:2px;' : ''"> The if-else statement in the above code does not work ...

Easily transform your Twitter Bootstrap menu dropdown to appear on hover instead of click with this simple solution

Is there a way to make the toggle dropdown button display the dropdown menu when hovering over it instead of clicking? I tried using the Bootstrap method $().dropdown('show'). What are your thoughts on this approach? $(document).on("mouseenter ...

Having issues with jQuery when trying to select only a single checkbox?

I have created a table with four rows and eight columns, each containing a checkbox. My goal is to allow only one checkbox to be checked per row. I am attempting to achieve this using jQuery. While it works in jsfiddle, I am experiencing difficulties in ge ...

JavaScript for Loading and Moving Ads in IE8

On my website at , I have placed my AdSense ads at the top of the page. However, I encountered an issue with Internet Explorer 8 where the Javascript code I used to move the ads to a different position on the page doesn't seem to work: <!-- POSI ...