【问题标题】:Adding an angularJS directive based on a parameter value根据参数值添加 angularJS 指令
【发布时间】:2014-07-01 16:35:59
【问题描述】:

TL;DR: 有没有办法根据参数值动态设置指令?类似于 ng-class 的东西用于设置 css 元素,但是一种基于作用域中的值设置指令的方法。我会在范围内有值,所以我可以调用:

<div class="data.directiveType"></div>

什么时候

data.directiveType = "my-directive"

div 会变成

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

myDirective 会被调用吗?

详细问题:

我想要做的是允许用户向 Web 应用程序添加元素,并且我希望根据用户点击的内容添加每个元素的指令。

我有以下指令:

app.directive("mySuperman", function(){
    //directive logic
});

app.directive("myBatman", function(){
    //directive logic
});

app.directive("myWonderWoman", function(){
    //directive logic
});

我有以下控制器

app.controller("ParentCtrl", function($scope){
    $scope.superHeros = [];

    var superman = {directiveType: "my-superman"};
    var batman = {directiveType: "my-batman"};
    var wonderWoman = {directiveType: "my-wonder-woman"}

    $scope.addBatman = function()
    {
        var batmanInstance = {}
        angular.copy(batman, batmanInstance);
        $scope.superHeros.push(batmanInstance);
    }

    $scope.addSuperman = function()
    {
        var supermanInstance = {}
        angular.copy(superman, supermanInstance);
        $scope.superHeros.push(supermanInstance);
    }

    $scope.addWonderWoman = function()
    {
        var wonderwomanInstance = {}
        angular.copy(wonderWoman, wonderwomanInstance);
        $scope.superHeros.push(wonderwomanInstance);
    }

});

在 index.html 我有

<body ng-controller="ParentCtrl>
    <a ng-click="addBatman()">Add Batman</a>
    <a ng-click="addSuperman()">Add Superman</a>
    <a ng-click="addWonderWoman()">Add WonderWoman</a>

    <div ng-repeat="hero in superHeros">
        <!-- The following doesn't work, but it is the functionality I am trying to achieve -->
        <div class={{hero.directiveType}}></div>
    <div>
</body>

我想到的另一种方法是在 ng-repeat 中使用 ng-include 并将模板 url 添加到 hero 对象而不是指令类型,但我希望有一种更简洁的方法可以更好地利用数据绑定,而不必为了调用另一个指令而调用ng-include

【问题讨论】:

    标签: html angularjs data-binding angularjs-directive


    【解决方案1】:

    您可以创建一个指令,将要添加的指令作为参数,将其添加到元素并编译它。然后像这样使用它:

    <div ng-repeat="hero in superHeros">
      <div add-directive="hero.directiveType"></div>
    </div>
    

    这是一个基本的例子:

    app.directive('addDirective', function($parse, $compile) {
    
      return {
        compile: function compile(tElement, tAttrs) {
    
          var directiveGetter = $parse(tAttrs.addDirective);
    
          return function postLink(scope, element) {
    
            element.removeAttr('add-directive');
    
            var directive = directiveGetter(scope);
            element.attr(directive, '');
    
            $compile(element)(scope);
          };
        }
      };
    });
    

    演示: http://plnkr.co/edit/N4WMe8IEg3LVxYkdjgAu?p=preview

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-03-23
      • 2016-09-28
      • 1970-01-01
      • 2014-09-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多