Optional expression attribute in AngularJS directive

17,935

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.

Share:
17,935

Related videos on Youtube

boyceofreason
Author by

boyceofreason

Updated on June 13, 2022

Comments

  • boyceofreason
    boyceofreason about 2 years

    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) || ...">
    
  • Rajkamal Subramanian
    Rajkamal Subramanian over 11 years
    Sorry, i accidentally pressed ctrl+s.. the fiddle got updated with my changes. Could you please update the fiddle link. Sorry once again.
  • Mark Rajcok
    Mark Rajcok over 11 years
    @rajkamal, the link above to the fiddle should still take people to the original version, even if you saved a new one. You would have also have had to click the "Base" button to cause people to see your version, so no harm done.
  • boyceofreason
    boyceofreason over 11 years
    This was exactly what I needed. Thanks!
  • Dana Cartwright
    Dana Cartwright over 10 years
    Wow, seeing the scope.disable(); call really helped me. I didn't grasp the full power of '&' until I saw that.