[英]ng-class access element text
I have this situation in a AngularJS app. 我在AngularJS应用中遇到这种情况。
$scope.current = 'my elem';
<div ng-class="{active: THIS ELEMENT TEXT === current}">my elem<div>
Can I access div.text() inside the ng-class
directive? 我可以在ng-class
指令中访问div.text()吗?
I am not sure of what you are asking, please find bellow a snippet of how to use ng-class
to apply a conditional CSS class based on string comparision. 我不确定您要问的是什么,请在下面找到如何使用ng-class
来基于字符串比较应用条件CSS类的代码段。
If you type 'red' in the input box, the text become red 如果在输入框中键入“红色”,则文本变为红色
var app = angular.module('App', []); app.controller('Ctrl', function($scope) { $scope.content = ["blue", "red", "green"]; });
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.5/angular.min.js"></script> <style> .red_text_class { color: red; } .blue_text_class { color: blue; } .green_text_class { color: green; } </style> <body ng-app="App" ng-controller="Ctrl"> <div ng-repeat="value in content"> <div ng-class="{red_text_class: value=='red',blue_text_class: value=='blue',green_text_class: value=='green'}">{{value}}</div> </div> <input ng-model="myText" />{{myText}} </body>
You can check against the text in the div by using the $element service: 您可以使用$ element服务在div中检查文本:
html: 的HTML:
<body ng-app="test" ng-controller="Ctrl">
<div ng-class="{active: innerText === current}">my element</div>
</body>
controller: 控制器:
angular.module('test', [])
.controller('Ctrl', Ctrl);
Ctrl.$inject = ['$scope', '$element'];
function Ctrl($scope, $element) {
$scope.current = 'my element';
$scope.innerText = $element.find('div').text();
}
To do that you should probably add dynamically your text in your div like this: 为此,您可能应该在div中动态添加文本,如下所示:
var app = angular.module('App', []); app.controller('Ctrl', function($scope) { $scope.current = 'my elem'; $scope.text1 = 'my elem'; $scope.text2 = 'my other elem'; });
.active { color: red; }
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> <body ng-app="App" ng-controller="Ctrl"> <div ng-class="{active: text1 == current}" ng-bind="text1"></div> <div ng-class="{active: text2 == current}" ng-bind="text2"></div> </body>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.