gpt4 book ai didi

javascript - 自定义指令内的条件 ngClass

转载 作者:行者123 更新时间:2023-11-28 01:03:43 26 4
gpt4 key购买 nike

我正在尝试了解隔离范围。

可以说,我有一个简单的指令:

HTML:

<my-directive options = "data"></my-directive>

JS:

angular.module('myapp.directive').
directive('myDirective', function() {
return {
template: '<a href = "{{href}}" class = "class"></a>',
restrict: 'E',
replace: 'true',
scope: {
options = "=options"
},
link: function(scope, element, attrs) {
scope.$watch('options', function(data) {
scope.class = data.class;
scope.href = data.href;
}
}

}

它有效。现在我想添加 ng-class:

<my-directive ng-class = "{'enabled': data.status == 'enabled'}" options = "data"></my-directive>

我尝试过:

scope : {
options: '=options',
ngClass: "="
}

scope.$watch("ngClass", function(value) {
scope.class += value;
}

它将“{'enabled':data.status == 'enabled'}”放入类中。我是否需要编译它,或者如何在每次更新数据时将其设置为 eval ng 类?

在浏览器上我看到

<a href = "{{href}}" class = "class "{'enabled': data.status == 'enabled'}""></a>

我想看看

<a href = "{{href}}" class = "class enabled"></a>

最佳答案

使用模板函数将 ng-class 从 myDirective 传递到您的模板:

<my-directive ng-class = "{'enabled': data.status == 'enabled'}" options = "data">
</my-directive>

指令

angular.module('myapp.directive').
directive('myDirective', function() {
return {
template: function(element, attr) {
return '<a href = "{{href}}" class = "class" ng-class="' + attr.ngClass + '"></a>'
},
restrict: 'E',
replace: 'true',
scope: {
options = "=options"
},
link: function(scope, element, attrs) {
scope.$watch('options', function(data) {
scope.class = data.class;
scope.href = data.href;
}
}

}

关于javascript - 自定义指令内的条件 ngClass,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25322501/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com