Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Optional expression attribute in AngularJS directive

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

In my main controller:

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

});

In my directive:

.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>'

    }

});

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) || ...">
like image 336
boyceofreason Avatar asked Mar 05 '13 14:03

boyceofreason


People also ask

Which directive can be used to write AngularJS Expressions?

Answer: C is the correct option. The ng-app directive is used to initialize the AngularJS application.

What is Ngmodeloptions in Angular?

The ng-model-options directive is used to control the binding of an HTML form element and a variable in the scope. You can specify that the binding should wait for a specific event to occur, or wait a specific number of milliseconds, and more, see the legal values listed in the parameter values below.

What is ngInit?

The ngInit directive allows you to evaluate an expression in the current scope. This directive can be abused to add unnecessary amounts of logic into your templates. There are only a few appropriate uses of ngInit : aliasing special properties of ngRepeat , as seen in the demo below.

What is custom directive in AngularJS?

What is Custom Directive? A Custom Directive in AngularJS is a user-defined directive that provides users to use desired functions to extend HTML functionality. It can be defined by using the “directive” function, and it replaces the element for which it is used.


1 Answers

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

scope.$parent.$eval(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();
}

Fiddle.

like image 152
Mark Rajcok Avatar answered Sep 28 '22 06:09

Mark Rajcok