[英]Conditional ngClass inside a custom directive
I am trying to learn about isolated scope. 我正在尝试了解隔离范围。
Lets say, I have a simple directive: 可以说,我有一个简单的指令:
HTML: HTML:
<my-directive options = "data"></my-directive>
JS: 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;
}
}
}
It works. 有用。 Now I want to add ng-class: 现在我要添加ng-class:
<my-directive ng-class = "{'enabled': data.status == 'enabled'}" options = "data"></my-directive>
I tried: 我试过了:
scope : {
options: '=options',
ngClass: "="
}
scope.$watch("ngClass", function(value) {
scope.class += value;
}
It puts "{'enabled': data.status == 'enabled'}" into class. 它将“ {'enabled':data.status =='enabled'}”放入类。 Do i need to compile it or how do i make it to eval ng class everytime data is updated? 每当数据更新时,我需要编译它还是如何使其成为评估类?
On browser I see 在浏览器上,我看到了
<a href = "{{href}}" class = "class "{'enabled': data.status == 'enabled'}""></a>
I want to see 我想看看
<a href = "{{href}}" class = "class enabled"></a>
Pass ng-class from myDirective to your template using a template function: 使用模板函数将ng-class从myDirective传递到模板:
<my-directive ng-class = "{'enabled': data.status == 'enabled'}" options = "data">
</my-directive>
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;
}
}
}
Alternatively, you can use $eval to convert the ngClass expression to an object and then bind it to a scope variable within your directive's isolated scope so that it can be used within your template: 或者,您可以使用$ eval将ngClass表达式转换为对象,然后将其绑定到指令的隔离范围内的作用域变量,以便可以在模板中使用它:
HTML HTML
<my-directive ng-class = "{'enabled': data.status == 'enabled'}" options = "data">
</my-directive>
Directive 指示
angular.module('myapp.directive').
directive('myDirective', function() {
return {
template: function(element, attr) {
return '<a href = "{{href}}" class = "class" ng-class="modelClass"></a>'
},
controller: function($scope, $element, $attrs) {
$scope.modelClass = $scope.$eval($attrs.ngClass);
},
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;
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.