acid
acid

Reputation: 2149

Angular - Passing variables to the directive scope

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? :)

Upvotes: 4

Views: 5792

Answers (2)

Mark Rajcok
Mark Rajcok

Reputation: 364677

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.

Upvotes: 4

karaxuna
karaxuna

Reputation: 26930

<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);
        }
   };
});

Upvotes: 0

Related Questions