AngularJS指令中的可选表达式属性 [英] Optional expression attribute in AngularJS directive

查看:84
本文介绍了AngularJS指令中的可选表达式属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个自定义导航指令需要一个可选的禁用属性,我不确定它是否可能。

I have a custom navigation directive that needs an optional "disable" attribute, and I'm not sure if it's even possible.

在我的主控制器中:

.controller('NavCtrl', ['UserResource','RoleResource'], function(UserResource,RoleResource){
      var user = UserResource.getUser();
      var roles = RoleResource.getRoles();
      UserService.init(user, roles); //????

});

在我的指令中:

.directive('navItem', function(){
    return{
        restrict: 'A',
        scope: {
            text: '@',
            href: '@',
            id: '@',
            disable: '&'

        },
        controller: function($scope, $element, $attrs){
            $scope.disabled = ''; //Not sure I even need a controller here
        },
        replace: true,
        link: function(scope, element, attrs){
            scope.$eval(attrs.disable);
        },
        template: '<li class="{{disabled}}"><a href="{{href}}" id="{{id}}">{{text}}</a></li>'

    }

});

在我的HTML中,我想做这样的事情:

In my HTML, I want to do something like this:

<div data-nav-item text="My Text" href="/mytemplate.html" id="idx"
     disable="UserService.hasRole('ADMIN,BILLING') && someOtherFn(xxx) || ...">


推荐答案

你可以通过chaning $ $来赚取你的工作eval调用

You could make what you have work by chaning your $eval call to

scope.$parent.$eval(attrs.disable);

因为您需要评估 attrs.disable 在父范围内,而不是指令的隔离范围。但是,由于您使用的是'&'语法,因此它将自动评估父作用域中的表达式。所以只需执行以下操作:

because you need to evaluate the expression contained in attrs.disable in the parent scope, not the directive's isolate scope. However, since you are using the '&' syntax, it will evaluate the expression in the parent scope automatically. So just do the following instead:

if(angular.isDefined(attrs.disable)) {
    scope.disable();
}

小提琴

这篇关于AngularJS指令中的可选表达式属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆