【问题标题】:handling interaction between angular directives for authentication处理角度指令之间的交互以进行身份​​验证
【发布时间】:2014-11-03 08:09:08
【问题描述】:

我有两个指令,为了简单起见,我将问题简化为以下内容:

指令 01:处理身份验证

它负责打开模态/窗口并获得用户身份验证。

angular
.module('app.directives')
.directive('requiresLogin', function(){       
     return {
         restrict : 'A',
         link : function() { //..}
     }
})

指令 02:执行特定操作

angular
.module('app.directives')
.directive('like', function(){

     return {
         restrict : 'A',
         link : function() { //..}
     }
})

指令 01 和 02 都绑定点击事件。

我对两个指令的设计有点困惑。

我可以使第二个指令成为第一个指令的子指令并得到 指令之间的通信,这在某种程度上是有意义的 因为每个指令的单一责任都在维护下 这种模式。但是,我未来需要的所有指令 身份验证将是第一个指令的子级。

我的问题是:

如何根据第一个“身份验证”指令的结果来防止第二个指令(实际操作)?有没有其他方法可以在不建立“父子”关系的情况下做到这一点?

【问题讨论】:

  • 抱歉,我的回答对您有帮助吗?

标签: angularjs angularjs-directive


【解决方案1】:

您可以在下面的帖子中明确地使用“require”:

How to require a controller in an angularjs directive

在您的上下文中,您可以这样做:

.directive('requirelogin', function() {
    return {
        scope: true,
        controller: function() {
            var isLogged = false;

            this.isLogged = function() {
                if(isLogged) return isLogged; 
                alert("You are not logged!");
            };

            this.login = function(){
                isLogged = true;            
            };
        }
    };
})

.directive('like', function() {
    return {
        scope: true,
        require: '^requirelogin',
        link: function(scope, element, attrs, loginCtrl) {
            scope.loginCtrl = loginCtrl;
            scope.sayILike = function(){
                if(scope.loginCtrl.isLogged()){
                    alert('I like');
                }
            };

            scope.login = function(){
                scope.loginCtrl.login();
            };
        }
    };
});

工作:http://jsfiddle.net/bennekrouf/nq9g33Lt/25/

【讨论】:

  • 好的......这个downvote有什么解释吗?在 2 个指令之间共享一个控制器对于说依赖于另一个指令很有用。
  • 您能否进一步完善您的答案?
  • 谢谢!现在好多了。
【解决方案2】:

只添加“action”指令并向其注入身份验证服务:

http://jsfiddle.net/coma/dby686ab/

逻辑

app.factory('user', function() {

    var roles = ['user'];

    return {
        hasRole: function(role) {

            return !role || roles.indexOf(role) > -1;
        }
    };
});

app.directive('like', function(user) {

    return {
        restrict: 'A',
        link    : function(scope, element, attrs) {

            element.on('click', function () {

                if (user.hasRole(attrs.authRole)) {

                    element.addClass('liked');
                    element.off('click');

                } else {

                    alert('Unauthorized.');
                }
            });
        }
    };
});

查看

<a like="">Dogs</a>
<a like="" auth-role="user">Birds</a>
<a like="" auth-role="admin">Whales</a>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-18
    • 1970-01-01
    • 1970-01-01
    • 2013-07-10
    • 2017-02-14
    • 2018-01-18
    相关资源
    最近更新 更多