简体   繁体   English

如何有条件地向元素动态添加AngularJS指令?

[英]How do I dynamically add an AngularJS directive to an element conditionally?

So I can't really get this to work, I've got the following code 所以我真的不能使它正常工作,我有以下代码

HTML: HTML:

<!doctype html>
<html ng-app="plunker" >
<head>
  <meta charset="utf-8">
  <title>AngularJS Plunker</title>
  <link rel="stylesheet" href="style.css">
  <script>document.write("<base href=\"" + document.location + "\" />");</script>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.2/angular.js"></script>
  <script src="app.js"></script>
</head>
<body ng-controller="MainCtrl">
  {{vt.t}} 
  <div my-directive="{{vt.t}}"></div>
  {{vt.f}}
  <div my-directive="{{vt.f}}"></div>

  <hr />

  {{vt.t}} 
  <div ng-class="{'my-directive': vt.t}"></div>
  {{vt.f}}
  <div ng-class="{'my-directive': vt.f}"></div>

  <hr />

  <div class="my-directive"></div>
  <div class="nodirectiveclass"></div>

</body>
</html>

JavaScript: JavaScript的:

var app = angular.module('plunker', []);

app.controller('MainCtrl', function($scope) {
  $scope.vt = { t: true, f: false };
});

app.directive('myDirective', function($compile) {
  return {
    restrict: 'AC',
    template: '<div>Directive on</div>',
    replace: true
  };
});

Plunker: http://plnkr.co/edit/7cJKhIuNqnsk1CkczjoE?p=preview 柱塞: http ://plnkr.co/edit/7cJKhIuNqnsk1CkczjoE?p=preview

As you see the classes doesn't trigger the directive when added dynamically but works fine in my last "static" example. 如您所见,类在动态添加时不会触发指令,但在我上一个“静态”示例中可以正常工作。 I also tried setting the directive attribute to true or false but that didn't seem to help. 我还尝试将伪指令属性设置为true或false,但这似乎没有帮助。

I think you should use model variable in your directive. 我认为您应该在指令中使用模型变量。 Then you can access what ever the value you want easily. 然后,您可以轻松访问所需的价值。

Refer this Answer: AngularJS - Create a directive that uses ng-model 请参阅此答案: AngularJS-创建使用ng-model的指令

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM