简体   繁体   中英

AngularJS Attach Scope Function in Directive

I have an AngularJS Directive that attaches jQuery Tooltipster to elements in a ng-repeat like so:

View:

div.chat-wrapper
    ul.chat-messages
        li(ng-repeat='chat in chatmessages' chat-tooltip) 

Directive:

angular.module('app')
    .directive('chatTooltip',
        function() {
            return {
                restrict: 'A',
                link: function(scope, el, attrs) {
                    scope.mute = function() {
                        console.log('hello world');
                    };

                    $(el).tooltipster({
                        content: $('<button ng-click="mute()" class="btn">Mute</button>'),
                        position: 'left',
                        positionTracker: true,
                        trigger: 'hover',
                        interactive: true,
                        autoClose: false
                    });
                }
            };
        }
);

I want to call the mute() function defined in the scope or $scope - ? Since the plugin adds the HTML content in the directive - I'm not sure what I need to do?

I can try to guess.

The problem here is that your html is parsed by jQuery. And not by angular's parser.

So until you provide any customization and are calling predefined method I advise you to create an element for content:

var button $(....);

Then pass this value to the content option and subscibe to button's click event imperatively with button.on('click') method.

please, take a look on this question/answer:

How to replace a html content with jsf reRender or ajax load, and rebind the new DOM with AngularJS?

It's show how to "rebind" angularjs after a jquery change, and how to call a angularjs function from jQuery.

But, to be short, you can call a angularjs function from scope with a code like this (identifying your controller by an id):

$('#idFromMyController').scope().myFunction();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM