Próbuję dowiedzieć się o odosobnionym zakresie.
Powiemy, że mam prostą dyrektywę:
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;
}
}
}
To działa. Teraz chcę dodać klasę NG:
<my-directive ng-class = "{'enabled': data.status == 'enabled'}" options = "data"></my-directive>
Próbowałem:
scope : {
options: '=options',
ngClass: "="
}
scope.$watch("ngClass", function(value) {
scope.class += value;
}
Stawia "{'Enabled": Data.status ==' Enabled '} " w klasie. Czy muszę go skompilować lub jak mogę przejść do eval Ng Class Data są aktualizowane?
W przeglądarce widzę
<a href = "{{href}}" class = "class "{'enabled': data.status == 'enabled'}""></a>
Chcę zobaczyć
<a href = "{{href}}" class = "class enabled"></a>
1
WhatisSober
15 sierpień 2014, 11:07
2 odpowiedzi
Najlepsza odpowiedź
Alternatywnie można użyć $ Eval, aby przekonwertować wyrażenie NgClass do obiektu, a następnie wiązać go do zmiennej zakresu w odosobnionym zakresie dyrektywy, dzięki czemu można go użyć w szablonie:
HTML
<my-directive ng-class = "{'enabled': data.status == 'enabled'}" options = "data">
</my-directive>
Dyrektywa
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;
}
}
}
0
pixelbits
15 sierpień 2014, 07:31
Przełóż klasa NG z MYDIRECTION do szablonu za pomocą funkcji szablonu:
<my-directive ng-class = "{'enabled': data.status == 'enabled'}" options = "data">
</my-directive>
Dyrektywa
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;
}
}
}
1
pixelbits
15 sierpień 2014, 07:17