Home > Mobile >  How to read a html data value in AngularJs directive
How to read a html data value in AngularJs directive

Time:08-24

I am very new to Angular. I am trying to read/pass some data to my angular directive from the template.

<div  approver-picker="partner.approverPlan.data" data-pickerType="PLAN"></div>

I have this in my angular template and I have this in different places. So I want to know in my Angular code, which picker is being clicked.

I am thinking to read the data-pickerType value in my directive.(I am able to read this in jQuery but do not know how to in Angular)

This is my directive code.

Partner.Editor.App.directive('approverPicker', [
'$compile', function ($compile) {
    return {
        scope: {
            "approvers": "=approverPicker"
        },
        templateUrl: '/template/assets/directive/ApproverPicker.html',
        restrict: 'EA',
        link: function ($scope, element) {
              ...........
        }
    };
  }
]);

How can I read the data-pickerType value in the directive or is there a better way of doing this?

CodePudding user response:

The data attributes can be accessed in Angular directive by passing attrs variable in the link function.

Partner.Editor.App.directive('approverPicker', [
  '$compile', function ($compile) {
      return {
        scope: {
          "approvers": "=approverPicker"
        },
        templateUrl: '/template/assets/directive/ApproverPicker.html',
        restrict: 'EA',
        link: function ($scope, element, attrs) { //passing attrs variable to the function
          
            //accessing the data values
            console.log(attrs.pickertype);

            //you can access any html attribute value for the element
            console.log(attrs.class);

        }
      };
   }
]);
  • Related