简体   繁体   English

在角度指令中实现关闭按钮

[英]implement close button in angular directive

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. 我希望可以做到这一点,在此先感谢您提供任何提示。

You can add a controller to your directive as well where you can add the close method to the scope. 您可以在指令中添加控制器,也可以在范围内添加close方法。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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