Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angularjs directive how to detect changes in the attributes

I use jquery ui and angularjs in my project. I have a directive like so.

app.directive('datepicker', function() {
    return {
         link: function (scope, element, attrs) {
          element.datepicker({
            altField: "#d" + attrs.fieldname + "_alt",
            altFormat: attrs.dateformat,
          });
        }
    };

I use it like.

<div fieldname="{{field.name}}" dateformat="{{field.dateformat}}" datepicker></div>

It works fine. But if the attrs changes, the changes are not reflected in datepicker. I was wondering if I could use something like this..

<div fielddata="field" datepicker></div>

And in the directive use scope{ data: "=fielddata"} and in my link function instead of attrs.fieldname use scope.data.fieldname

I appreciate any help

like image 694
Leah Collins Avatar asked May 21 '26 09:05

Leah Collins


1 Answers

You have to add watches to do what you want. Using the scope: {} as above does add watches under the hoods to synchronize the isolated scope of the directive with the external data. But since you are using jQueryUI, you need to take custom action on every change, so just add the watch yourself. E.g.:

app.directive('datepicker', function() {
    return {
        link: function (scope, element, attrs) {
            element.datepicker({
                altField: "#d" + attrs.fieldname + "_alt",
                altFormat: attrs.dateformat,
            });

            attrs.$observe('dateformat', function(newval) {
                element.datepicker('option', 'altFormat', newval);
            });

            // and so on for every attribute
        }
    };
});

attrs.$observe will work for interpolated attributes, i.e. attributes with {{...}} expressions. You may want to use $parse and scope.$watch if you want to pass complex objects to your directive.

like image 150
Nikos Paraskevopoulos Avatar answered May 22 '26 23:05

Nikos Paraskevopoulos