简体   繁体   English

Angular - 将变量传递给指令范围

[英]Angular - Passing variables to the directive scope

I would like to pass an object to the directive scope: 我想将一个对象传递给指令范围:

JS: JS:

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

HTML 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. 其中priceValid是来自控制器范围的布尔值, {'disabled': 'disabled'}只是一个普通对象。 I expect my attrs.validatePrice to return eg: 我希望我的attrs.validatePrice能够返回,例如:

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

Yet it returns string. 然而它返回字符串。 How do I do that? 我怎么做? :) :)

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 . priceValid将被JavaScript解释为对象键 - 它不会被解释为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): 无论如何, $ parse$ eval是你需要用来将一个对象传递给一个指令(如果你没有使用一个独立的范围):

<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. 如果需要更改对象,请使用$ parse。 See https://stackoverflow.com/a/15725402/215945 for an example of that. 有关示例,请参阅https://stackoverflow.com/a/15725402/215945

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM