【问题标题】:How do I dynamically add an AngularJS directive to an element conditionally?如何有条件地向元素动态添加 AngularJS 指令?
【发布时间】:2014-07-30 20:07:18
【问题描述】:

所以我真的不能让它工作,我有以下代码

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:

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

如您所见,类在动态添加时不会触发指令,但在我上一个“静态”示例中可以正常工作。我也尝试将指令属性设置为 true 或 false,但这似乎没有帮助。

【问题讨论】:

  • 这是因为ng-class在编译过程之后设置了类,这里解释一下:stackoverflow.com/a/18599528/1062711
  • 解决方法取决于指令的作用。可能可以使用ng-ifng-switch,或者可能需要根据使用情况在指令中添加更多逻辑

标签: javascript html angularjs web angularjs-directive


【解决方案1】:

我认为您应该在指令中使用模型变量。然后,您可以轻松访问所需的任何值。

参考这个答案: AngularJS - Create a directive that uses ng-model

【讨论】:

    猜你喜欢
    • 2016-05-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-23
    • 1970-01-01
    相关资源
    最近更新 更多