4

I would like to pass an object to the directive scope:

JS:

app.directive('validatePrice', function() {
    return {
        link: function(scope, el, attrs){
            console.log(attrs.validatePrice);
        }
    };
});

HTML

<button validate-price="{priceValid: {'disabled': 'disabled'}}">Checkout</button>

where priceValid is a boolean from the controller scope and {'disabled': 'disabled'} is just a plain object. I expect my attrs.validatePrice to return eg:

{
    true: {'disabled': 'disabled'}
}

Yet it returns string. How do I do that? :)

Eduard Gamonal
  • 8,023
  • 5
  • 41
  • 46
acid
  • 2,099
  • 4
  • 28
  • 41

2 Answers2

4

I don't think what you want is possible. priceValid will be interpreted as an object key by JavaScript – it will not be interpreted as true.

Anyway, $parse or $eval is what you need to use to pass an object to a directive (if you are not using an isolated scope):

<button validate-price="{priceValid: {'disabled': 'disabled'}}">Checkout</button>

app.directive('validatePrice', function($parse) {
    return {
        link: function(scope, el, attrs){
            var model = $parse(attrs.validatePrice);
            console.log(model(scope));
            console.log(scope.$eval(attrs.validatePrice));
        }
    };
});

fiddle

Use $parse if you need to alter the object. See https://stackoverflow.com/a/15725402/215945 for an example of that.

Community
  • 1
  • 1
Mark Rajcok
  • 362,217
  • 114
  • 495
  • 492
0
<validate-price-dir validate-price="{priceValid: {'disabled': 'disabled'}}">Checkout</validate-price-dir>    

app.directive('validatePriceDir', function() {
    return {
        restrict: 'E',
        scope: { validatePrice: '=validatePrice' },
        link: function(scope, el, attrs){
            console.log(scope.validatePrice);
        }
   };
});
karaxuna
  • 26,752
  • 13
  • 82
  • 117
  • 1
    Not only it returns string, but it also throws `Error: 10 $digest() iterations reached. Aborting!`. – acid Jul 17 '13 at 11:15
  • 2
    by default directives are restricted to type A (attributes). you have an attribute with the same name as the directive: infinite loop – Eduard Gamonal Jul 17 '13 at 11:18