在 angular 指令中传递 ng-class 条件

pass ng-class condition in angular directive

我有一个指令:

angular.module("App").directive('myDirective', function () {
    return {
        restrict: "E",
        },            
        templateUrl: "MyDirective.html"
    }
});

模板:

<input Value = "Test" ng-class="{{ngclass}}"/>

HTML:

<my-Directive ng-class="{'ng-invalid': param === false }"/>

是否可以将 ng-class 条件传递到指令中?

谢谢

我不确定你是否可以通过表达式传递作用域变量...

angular.module("App").directive('myDirective', function () {
    return {
        restrict: "E",        
        templateUrl: "MyDirective.html",
        scope: { invalid: '=' }
    }
});

<my-Directive invalid="param === false"/>

<input Value="Test" ng-class="{'ng-invalid': invalid}"/>

您可以使用 scope option,例如:

angular.module('myApp', [])
.controller('MyCtrl', ['$scope', '$timeout', function MyCtrl($scope, $timeout) {
    var ctrl = this;
    
    ctrl.testTrue = true;
    ctrl.testFalse = false;
    
    $timeout(function(){
      ctrl.testFalse = true;
    }, 3000);
    
    return ctrl;
}])
.directive('myDirective', [function () {
        var myDirective = {
            restrict: 'E',
            scope: {
              ngClass: '='
            },
            template: "<input Value = 'Test' ng-class='ngClass'/>"
        }
        return myDirective;
}]);
.ng-test-false {
    border: 1px solid red;
}
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="//code.angularjs.org/1.6.2/angular.js"></script>

<div ng-app="myApp">
  <div ng-controller="MyCtrl as $ctrl">

      <my-Directive ng-class="{'ng-invalid': true, 'ng-test-true':  $ctrl.testTrue, 'ng-test-false': $ctrl.testFalse}"/>
  
  </div>
</div>