ng-class访问元素文本

时间:2015-10-30 12:30:30

标签: javascript angularjs

我在 AngularJS 应用中遇到了这种情况。

$scope.current = 'my elem';

<div ng-class="{active: THIS ELEMENT TEXT === current}">my elem<div>

我可以在ng-class指令中访问div.text()吗?

3 个答案:

答案 0 :(得分:1)

我不确定您的要求,请在下面找到如何使用ng-class基于字符串比较应用条件CSS类的摘要。

如果您输入红色&#39;在输入框中,文本变为红色

&#13;
&#13;
var app = angular.module('App', []);
app.controller('Ctrl', function($scope) {
  $scope.content = ["blue", "red", "green"];
});
&#13;
<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>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

您可以使用$ element service检查div中的文本:

html:

<body ng-app="test" ng-controller="Ctrl">
    <div ng-class="{active: innerText === current}">my element</div>
</body>

控制器:

angular.module('test', [])
  .controller('Ctrl', Ctrl);

Ctrl.$inject = ['$scope', '$element'];

function Ctrl($scope, $element) {
  $scope.current = 'my element';

  $scope.innerText = $element.find('div').text();
}

plunker here

答案 2 :(得分:0)

要做到这一点,你应该在你的div中动态添加你的文字,如下所示:

&#13;
&#13;
var app = angular.module('App', []);
app.controller('Ctrl', function($scope) {
  $scope.current = 'my elem';
  
  $scope.text1 = 'my elem';
  $scope.text2 = 'my other elem';
});
&#13;
.active {
  color: red;
}
&#13;
<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>
&#13;
&#13;
&#13;