JS无法改变className

时间:2018-01-12 14:48:15

标签: javascript angularjs class

我正在尝试更新div#programmation

的第一个孩子的类
<div id="programmationEtat">
   <div class="tab-pane ng-scope">...</div>
   <div class="tab-pane ng-scope">...</div>
   <div class="tab-pane ng-scope">...</div>
   ...
</div>

我试过了:

var children = document.getElementById("programmationEtat").children;
console.log(children);
children[0].className = 'active';
console.log(children);

第一个控制台日志说:

  

tab-pane ng-scope

第二说:

  

活性

但没有改变,当我看到HTML(chrome调试器)时,我仍然有

<div class="tab-pane ng-scope"> 

我做错了什么?! 提前谢谢!

修改 我发现了问题: 我在包含这个div的范围上使用动态指令:

   app.directive('dynamic', ['$compile', function ($compile) {
  return {
    restrict: 'A',
    replace: true,
    link: function (scope, ele, attrs) {
      scope.$watch(attrs.dynamic, function (html) {
        ele.html(html);
        $compile(ele.contents())(scope);
      });
    }
  };
}]);

我有

$scope.programmation='...<div id="programmationEtat">
       <div class="tab-pane ng-scope">...</div>
       <div class="tab-pane ng-scope">...</div>
       <div class="tab-pane ng-scope">...</div>
       ...
    </div>...'

HTML:

<div dynamic="programmation" id="programmationEtat">
    ... 
</div>

对于$ scope.programmation中包含的内容,看起来无法使用document.getElementById(...)进行更新,必须直接在$ scope.programmation上进行更新。

为了解决我的问题,我使用了替换函数($ scope.programmation.replace(...))!

1 个答案:

答案 0 :(得分:2)

使用ng-class:

<div id="programmationEtat">
   <div ng-class="className"class="tab-pane ng-scope">...</div>
   <div class="tab-pane ng-scope">...</div>
   <div class="tab-pane ng-scope">...</div>
</div>

$scope.className = 'active';

OR:

<div id="programmationEtat">
   <div ng-class="{ 'active': activated }"class="tab-pane ng-scope">...</div>
   <div class="tab-pane ng-scope">...</div>
   <div class="tab-pane ng-scope">...</div>
</div>

$scope.activated = true;