directive angularjs does not recognize the value of attrs as undefined

I am utilizing the scope value to pass to a directive through attrs. Initially, I encounter an issue where the value of min is undefined upon first load, but it functions correctly with $watch. See this example.

link: function(scope, elm, attrs) {
  scope.$watch(function (){return attrs.min}, function (newValue, oldValue) {
    console.log('oldValue=' + oldValue);
    console.log('newValue=' + newValue);
     //do something
   });
   console.log(attrs.min);                       
 }

Answer №1

Have you considered utilizing $observe as an alternative approach?

app.directive('customDirective', function() {
    return {
      restrict: 'A',
      link: function(scope, element, attributes) {

        attributes.$observe('max', function(newVal) {
          console.log(newVal);
        });

    }
};

});

Answer №2

It appears that the value of {{message}} is not being evaluated prior to the directive's postlink phase.

An alternative approach would be to utilize a scope:

app.directive('exampleDirective1', function() {
    return {
        restrict: 'E',
        scope: {
            min: '='
        },
        link: function(scope, elm, attrs) {
             scope.$watch('min', function (newValue, oldValue) {
                console.log('oldValue=' + oldValue);
                console.log('newValue=' + newValue);
                //perform some action
            });
            console.log(scope.min);
            console.log(attrs.min);
        }
    };
});

Additionally,

With template: <example-directive1 min="message"></example-directive1>   

Answer №3

It's quite peculiar, I conducted a test using compile, prelink, and postlink along with extensive logging, and the results were unexpected:

function MyCtrl($scope) {
    $scope.message = 'hello';
    console.log('$scope.message set to hello');   
}

app.directive('exampleDirective1', function() {
    return {
        restrict: 'E',
        compile: function(tElement, tAttrs) {
          console.log('currently at compile, attrs.min = ', tAttrs.min);

            return {
              post: function postLink(scope, elm, attrs) {
                 scope.$watch(function (){return attrs.min}, function (newValue, oldValue) {
                    console.log('currently, attrs.min = ', attrs.min);  
                });
                console.log('currently at postlink, attrs.min = ', attrs.min);                       
              },
              pre: function prelink(scope,elm , attrs) {
                console.log('currently at prelink, attrs.min = ', attrs.min);  
              }
            };
        }
    };
});

http://jsfiddle.net/qdzLhpf9/

The value of scope is already assigned when prelink is executed. Nevertheless, it appears that the arguments are being evaluated between postlink and prelink.

EDIT: Upon further investigation, it seems that in your version of Angular, $compile initializes args as 'undefined'. You can check this out in https://code.angularjs.org/1.0.0/angular-1.0.0.js at line 4434.

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

jQuery scrollTop(0) leading to unusual scrolling patterns

Every time I click on a button, a modal window appears with a fading effect: $('.display-all-comments').fadeIn(300); $('.display-all-comments').scrollTop(0); If I remove the scrollTop(0), the scrolling works as usual. To better illust ...

Troubleshooting Problem with Asynchronous JavaScript Requests (Node.js, using the request-promise module)

I'm currently developing an application and encountering a challenge with processing a request from the client, forwarding it to my server, allowing the server to make the API call, and then returning the result back to the client. My development stac ...

How can I consistently align this sphere in the center whenever the window size is adjusted?

Here's the code snippet I'm working with: <script> var scene = new THREE.Scene(); var camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 0.1, 1000 ); var renderer = new THREE.WebGLRenderer(); renderer.setSiz ...

Is it possible to include multiple eventTypes in a single function call?

I have created a function in my service which looks like this: public refresh(area: string) { this.eventEmitter.emit({ area }); } The area parameter is used to update all child components when triggered by a click event in the parent. // Child Comp ...

Hover Effect with CSS Selector - JavaScript or jQuery Implementation

I have a similar code snippet: <article class="leading-0"> <h2> <a href="link">link title</a> </h2> <ul class="actions"> <li class="print-icon"> <a ...><img...>& ...

Retrieve JavaScript Variable Value when Button is Clicked via asp:HiddenField

Having limited experience with JavaScript and jQuery, I decided to make some modifications to a jQuery Slider for adjusting dates. You can check out what I've done so far here: http://jsfiddle.net/ryn_90/Tq7xK/6/. I managed to get the slider working ...

When saving a canvas as an image, it only results in a blank, transparent image

I have a situation where I am iterating through an array of image elements sourced from a local folder, attaching them to a canvas. However, when attempting to save the canvas as an image, it is not being saved correctly. The resulting image appears to mat ...

Tips for using jQuery to verify the most recent entry in a form

Struggling with this issue - I can't seem to get jquery to function the way I need it to: Essentially, when a user exits a text field, jquery is supposed to capture the input value and respond accordingly: for example, if the user types 'value& ...

Is there a simple method in JavaScript to combine, structure, and join numerous multi-dimensional arrays in a specific manner (from right to left)?

Looking for a simple solution to merge, flatten, and concatenate multiple multi-dimensional arrays in JavaScript in a specific manner (from right to left) # Example [['.class1', '.class2'], ['.class3', ['.class4', & ...

Zod vow denial: ZodError consistently delivers an empty array

My goal is to validate data received from the backend following a specific TypeScript structure. export interface Booking { locationId: string; bookingId: number; spotId: string; from: string; to: string; status: "pending" | "con ...

Acquire Content using jQuery and Navigate page horizontally

I am trying to achieve a unique effect by capturing content x and horizontally scrolling the page while the mouse is in motion, similar to swiping on a tablet. It seems simple enough.. Capture clientX on mousedown, ScrollLeft by ClientX while moving, Di ...

Sending an Ajax/JSON request to a PHP handling file

Currently, I am in the process of developing a phone application as part of my university degree. This app is being built using HTML5, AJAX, JSON, and PHP. It is essential for the app to interact with a MySQL database, so I am utilizing AJAX JSON to commun ...

Expandable Menu that slides up and down

Here is a link to an Accordion Menu I have created: https://jsfiddle.net/wfr57s57/ This piece of JQuery Code controls the functionality: $(".menu-item").click(function(e) { var allContents = $(".menu-content"); e.preventDefault(); if(allC ...

Achieving a consistent scroll value using RxJs

I have a block with a mat-table inside, which has an initial scroll value of 0. I am trying to achieve a scenario where the scroll value changes automatically to 2 or more when you reach a height of 0 and again changes back to 2 when scrolled to the final ...

Creating multiple countdowns in AngularJS using ng-repeat is a handy feature to have

Currently, I have a small AngularJS application that is designed to search for users and display their upcoming meetings. The data is retrieved from the server in JSON format, with time displayed in UTC for easier calculation to local times. While I have s ...

What is the process for converting a regular text input to a password input in Laravel?

Looking to update the text input in my Laravel project to a password input with asterisks for security. <div class="col-md-3"> <div class="form-group"> {{ Form::label('user-password','Password') ...

Guide on integrating a Jison generated parser within an Angular application

Using the Jison library, parsers can be created based on a specific grammar by running: $ jison calculator.jison This process is described in reference [1]. The above command generates a parser named calculator.js. Now the question arises - how to in ...

"Can you please share how to extract the values from a firebaseArray

Attempting to retrieve and log the information of each item in my firebaseArray using the following code: $scope.events = $firebaseArray(ref.child('event').orderByChild('uid').equalTo(Auth.$getAuth().uid)); $scope.events.$loaded( funct ...

Preventing the backspace or delete key from deleting text before the cursor

I need to prevent the cursor from deleting the word before it if the word before is "Hi Harry" in an input type text field. I want to restrict the deletion of text, so that when the user attempts to delete text and the text before it is "Hi Harry," the del ...

Display error page when unable to load ng-view template

Is there a way to display a standard error page or template if a certain template cannot be loaded using ngRoute in Angular? I've come across suggestions that subscribing to the $routeChangeError event might help, but I'm not sure what steps to ...