0

I'm writing a custom directive. I want the directive to add an ng-click attribute to the element attrs.$set('ng-click','clicked()'); I have tried adding the ng-click directive in compile function, and pre and post link functions. The attribute is added but doesn't work. I appreciate any insights. Thanks!

.directive('myDir', function () {
        return{
            compile: function (tElement, tAttrs, transclude) {

                //tAttrs.$set('ng-click','clicked()');

                return {
                    pre: function (scope, element, attrs) {
                       //attrs.$set('ng-click','clicked()');
                    },
                    post: function (scope, element, attrs) {
                      //attrs.$set('ng-click','clicked()');  

                        scope.clicked = function(){
                            console.log('clicked!!!');
                        };
                    }
                };
            }
        };
    });

1 Answers1

1

You've added the attribute via jQuery so Angular doesn't know about it. The quick answer is to wrap the call in a scope.$apply:

scope.$apply(function() {
  tAttrs.$set('ng-click','clicked()');
});

So Angular knows you changed it.

But for other approaches that might work more cleanly with Angular look at What is the best way to conditionally apply attributes in Angular?

Community
  • 1
  • 1
KayakDave
  • 24,636
  • 3
  • 65
  • 68