implement close button in angular directive
-
21-12-2019 - |
Question
I am trying to make an alert message and the layout looks like this
<div class="alert">
<p>Some alert content!</p>
</div>
So far so good, now I want to make a directive to add a close button to this alert and I want to hide the alert when i press the button.
I created this directive
myApp.directive('alert', function() {
return {
restrict: 'C',
link: function(scope, elem, attrs) {
elem.prepend('<a class="alert-close" ng-click="close()"></a>');
}
}
});
Now this directive adds the close button, but I don't know how to implement this button to hide the alert which is inside.
I hope this can be done, thank you in advance for any tips on how to do this.
La solution
You can add a controller to your directive as well where you can add the close method to the scope.
myApp.directive('alert', function() {
return {
restrict: 'C',
link: function(scope, elem, attrs) {
elem.prepend('<a class="alert-close" ng-click="close(this)"></a>');
},
controller: function ($scope) {
$scope.close = function (obj) {
// manipulate obj (the anchor link) or traverse up the dom etc.
};
}
}
});
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow