0

In jQuery I could create a web component like so:

jQuery

<script>
$(document).on('click', 'm-button[alert]', function(e){
    alert($(this).attr('data-message');
});
</script>

HTML

<m-button alert data-message="Hello World!">Say Hello</m-button>
<m-button alert data-message="Goodbye World!">Say Bye</m-button>

When I click any of the above button I will get an alert with the text defined inside data-message attribute.

What is the best practice to do this in Angular? One way would be to assign ng-click to every <m-button>, is there any better and more efficient way?

0

1 Answer 1

1

Angular uses directives. When you use a directive it can be created/used as HTML Attributes, Element or Clases.

Here is an example with directive being used as an attribute:

<div ng-controller="MyController">
    <button alert data-message="Hello World!">Click Me</button>
</div>

//... angular app previously declared and created
app.directive('alert', function() {
    return {
        link: function(scope, element, attrs) {
          element.click(function(){
            alert(attrs.message);
          }); 
        }
    }
});
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! After fiddling around a bit I got it working perfectly

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.