ng-class不会触发自定义指令

时间:2018-01-03 15:50:17

标签: javascript angularjs angular-directive

我创建了一个AngularJS指令,该指令将在 classname .collapse的所有元素上触发。

但是当我使用Angular' ng-class指令添加此时,不会触发自定义collapse指令。

演示我的问题



var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
    $scope.welcome = "model";
    
    $scope.isTrue = function() {
      return true;
    }
});

app.directive("directive", function($compile) {
  return {
    restrict: 'C',
    scope: {
      model: '@'
    },
    link: function(scope, elem, attrs) {
      elem.css("background-color", "blue");
    }
  }
});

.directive {
  background-color: red;
  color: white;
  padding: 10px;
  margin-bottom: 10px;
}

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl">
  <p>Simple Angular app</p>
  <div class="directive">Make my background color blue using the directive</div>
  <div ng-class="isTrue() ? 'directive' : ''">Make my background color blue using the directive</div>
</div>
&#13;
&#13;
&#13;

如何使用directive添加上的ng-class触发器?

1 个答案:

答案 0 :(得分:-2)

我相信这是answered already here

基本上,ng-class设置类太晚了 - 在DOM加载之后。在指令中应用条件可以在指令本身内完成以避免这个问题。在该链接中有使用属性而不是类的指令,然后在指令中进行检查。希望有所帮助。以下示例显示了这一点:

<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.6.0/underscore.js" type="text/javascript"></script>

<script>
var app = angular.module('myApp', []);
    app.controller('myCtrl', function($scope) {
        $scope.welcome = "model";

        $scope.isTrue = function() {
          return true;
        }
    });

    app.directive("directive", function($compile) {
      return {
            restrict: 'A',
            scope: {
                'condition': '='
            },
            link: function (scope, elem, attrs) {
            scope.$watch('condition', function(condition){
                if(condition){
                    elem.css("background-color", "blue");
                }
            });
        }
      }
    });
</script>

<style>
.directive {
  background-color: red;
  color: white;
  padding: 10px;
  margin-bottom: 10px;
}
</style>
</head>

<body>
<div ng-app="myApp" ng-controller="myCtrl">
  <p>Simple Angular app</p>
      <div class="directive" directive condition="true">Make my background color blue using the directive</div>
      <div class="directive" directive condition="false">DO NOT make the background blue because the condition is false</div>
      <div directive condition="isTrue();">Make my background color blue using a function for the the directive</div>
</div>
</body>