如何在AngularJs指令中读取html数据值

xcitsw88  于 2022-10-31  发布在  Angular
关注(0)|答案(1)|浏览(199)

我是非常新的Angular 。我试图读取/传递一些数据到我的Angular 指令从模板。

<div class="col-md-6" approver-picker="partner.approverPlan.data" data-pickerType="PLAN"></div>

我在我的Angular 模板中有这个,我在不同的地方有这个。所以我想知道在我的Angular 代码中,哪个选择器被点击了。
我想在我的指令中读取data-pickerType值。(我可以在jQuery中读取此值,但不知道如何在Angular中读取)
这是我的指令代码。

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

如何读取指令中的data-pickerType值?是否有更好的方法?

r1zhe5dt

r1zhe5dt1#

通过在链接函数中传递attrs变量,可以在Angular指令中访问数据属性。

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);

        }
      };
   }
]);

相关问题