处理角度指令之间的交互以进行身份​​验证

时间:2014-09-09 19:49:11

标签: angularjs angularjs-directive

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

指令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都绑定了点击事件。

我对两个指令的设计感到困惑。

  

我可以让第二个指令成为第一个指令的子节点并获得   指令之间的沟通,这在某种程度上是有道理的   因为每项指令的单一责任都在维持   这种模式。但是我所有未来的指令都需要   身份验证将是第一个指令的子级。

我的问题是:

如何根据第一个"验证"的结果来阻止第二个指令(实际操作)?指令?有没有其他方法可以做到这一点,而不是做一个父母和孩子的#34;他们之间的关系?

2 个答案:

答案 0 :(得分:2)

您可以使用"要求"在以下文章中明确地解释了:

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/

答案 1 :(得分:0)

仅添加"操作"指令并为其注入一个auth服务:

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>