Using $watch to monitor the existence of a variable within the AngularJS scope

I'm working on a directive that displays alerts, and I want to set up a timeout function to run whenever the 'show' variable changes. How can I achieve this?

When I tried invoking the link function, all the variables - show, message, and type were undefined after the first time.

Here is the code for the directive:

 angular.module('pysFormWebApp')      
    .directive('alertDirective', 

    function  alertDirective ($timeout) {   
    return {
        restrict : 'E',
        scope : {
            message : "=",
            type : "=",
            show : "=",
            test : "="
        },
        controller : function ($scope) {

            $scope.closeAlert = function () {
                $scope.show = false;
                $scope.type = "alert alert-dismissable alert-";
                $scope.message = "";
            };

            $scope.getStrongMessage = function (type) {
                var strongMessage = "";
                if(type == "success"){
                    strongMessage = "\xC9xito ! ";
                } else if(type == "warning"){
                    strongMessage = "Cuidado ! ";
                return strongMessage;
            }
        },
        link: function(scope, element, attrs) {
            scope.$watch(scope.show, 
             function (newValue) {
             console.log(newValue); 
             },true);
        },
        templateUrl : "views/utilities/alert.html"
    };
});

Here is the HTML code for the directive:

<div ng-show="show">
    <div class="alert alert-dismissable alert-{{type}}">
        <button type="button" class="close" ng-click="closeAlert()">&times;</button>
        <strong>{{getStrongMessage(type)}}</strong> {{  message | translate }} 
    </div>
</div>

Example of using the directive in a controller:

  $scope.info.alert = {
    message: "EXPOTED-SUCCESS",
    type: "success",
    show : true
  };

HTML code snippet using the directive:

<alert-directive  message="info.alert.message" 
          type="info.alert.type" 
          show="info.alert.show">
</alert-directive>

Answer №1

When setting a watch on the scope variable, be sure to provide the correct parameters. The $watch function requires the first parameter to be a string or function that will be evaluated during each digest cycle, and the second parameter should be the callback function.

//changed from `scope.show` to `'show'` 
scope.$watch('show', function (newValue) {
   console.log(newValue); 
}, true);

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

Is there a way to verify if debugging information is enabled within an Angular application?

If you want to switch angular's debug information on or off, you can achieve this by using the following code: $compileProvider.debugInfoEnabled(debugInfoState); This should be included within the config method of your Angular application. Is there ...

Can a <Link> be customized with a specific condition?

On the webpage, there is a list of elements retrieved from a database. When clicking on the last displayed element, I want to link to '/upload' if it shows "Carica Referto", or link to '/consensi/{this.$state.item.hash_consenso}' if it ...

Each time the web animation is utilized, it gets faster and faster

As part of an assignment, I am working on creating an interactive book that can be controlled by the arrow keys and smoothly comes to a stop when no key is being pressed. However, I have noticed that with each arrow key press, the animation speeds up. Bel ...

What could be the reason for this JSON being considered "invalid"?

Despite passing validation on jsonlint, both Firefox and Chrome are rejecting this JSON: { "messages": [ { "subject": "One" }, { "subject": "Two" }, { "subject": "Three" ...

Utilizing AngularJS watchCollection to monitor changes in scope variables alongside an array

Within my controller, I have several scope variables: $scope.searchText = "abc"; $scope.currentPage ="1"; $scope.sortBy ="dateTime"; $scope.sortOrder="reverse"; $scope.columnSettings = [ {"name": "dateTime", ...

Issue with the iteration process while utilizing Async.waterfall in a for-loop

This snippet may seem simple, but it represents a real issue in my current code base. When attempting to log the index of a for-loop within an async.waterfall function, I am encountering a peculiar situation where the index value is 2 instead of expected ...

The specified type '{ state: any; dispatch: React.Dispatch<{ type: string; value: any; }>; }' is not compatible with the expected type

I've been working on a UI layout that includes checkboxes on the left, a data table on the right, and a drop zone box. The aim is to keep the table data updated whenever a new file is dropped, and also filter the data based on checkbox selection. I ma ...

Getting the id of a row from a v-data-table in VueJs

I am currently facing an issue with retrieving the id of a specific field from each row. I require this id as a parameter for a function that will be utilized in an action button to delete the row. Here is how my table template appears: <template ...

A guide to creating a synchronous AJAX call using vanilla JavaScript

I am trying to make multiple AJAX calls in a loop using the code below. for (var i = 0; i < 5; i++) { console.log(i); ajax_DatabaseAccessor.query("CheckInt", i, loadQuery); function loadQuery(data) { alert(DWRUtil.toDescriptiveString ...

Is it possible to export a constant from within a default function to a different file?

As a newcomer to React and React Native, I am looking to pass a const variable from within a function to another file. I attempted defining it outside of the function and allowing it to be modified inside the function, but encountered an invalid Hook Call ...

Efficiently organizing dates in the Vuetify date range picker

I am working with a vuetify date range picker component and have the following code: <v-menu ref="effectiveDateMenu" v-model="effectiveDateMenu" :close-on-content-cl ...

How can you preselect an item in Vuetify's item group?

When attempting to preselect an item from a vuetify item-group, I discovered that it works with strings but not with objects. The vuetify documentation shows using a string array as the item list for the item-group, which functions correctly. However, whe ...

Having trouble getting the group hover animation to function properly in Tailwind CSS

Just starting out with tailwind css and running into a little issue. The hover animation I'm trying to apply isn't working as expected in this case. Instead of seeing the desired animated background when hovering over the group, it seems the back ...

Developing several sliders and ensuring they operate independently of each other

I am currently in the process of developing multiple sliders for a website that I am building. As I reach the halfway point, I have encountered a problem that has stumped me. With several sliders involved, I have successfully obtained the length or count ...

Unable to import a text file using a semicolon as delimiter in d3

I'm just starting to learn JavaScript and the D3 library. I recently explored the "d3-fetch" module (available at https://github.com/d3/d3-fetch) and the d3.dsv command API (find it here: https://github.com/d3/d3-dsv). However, I am struggling to unde ...

Error: The OrbitControls function is not recognized in THREE.JS

const scene = new THREE.Scene(); const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000); const controls = new OrbitControls(camera); camera.position.set(200, 0, 0); controls.update(); const geometry = new THREE.S ...

Utilize Google Maps geocoding functionality to pinpoint a location and then

I've encountered this strange phenomenon, but first let's take a look at the code: HTML <div ng-app='maptesting'> <div ng-controller="MapCtrl"> <div id="map_canvas" ui-map="myMap" style ...

What is the process for importing a React component that relies on a dependency?

This is my first experience using React (with babel) and jsx, along with Webpack to create my bundle.js I have developed two React components - Header1.jsx and Header2.jsx. The logic I want to implement is as follows: If the date is before July 4th, 2016 ...

Issue with AngularJS: Unable to receive response from REST API call

I'm currently working on developing a basic login form using AngularJS and a RESTful web service. While I've been able to successfully call the RESTful web service, I am struggling to retrieve the response. 1) Login Form: <div class="col-md- ...

A TypeError was not captured when attempting to access information about Ionic1 through the angular.module

For the past 48 hours, I've been struggling with an issue that's really getting on my nerves. If anyone knows how to fix this, it would be greatly appreciated: I'm working on an Ionic 1 project and need to make some updates, but nothing I t ...