2016-04-06 19 views
0

私はAngularJSで作業を始めましたが、わかりにくい小さな問題を発見しました。Gridster内のAngularJSに動的にディレクティブを追加します

私はAngularJS Gridsterをインポートしました。あなたのウェブページにダイナミックグリッドを追加する簡単な方法です。これですべてが機能し、要素がデータベースから正常にロードされ、Gridsterにインポートされましたが、今私は以下のことをしたいと思います。データベースから取得されたJSONには、 "directive"という属性もあります。今、すべてがロードされると、各Gridster要素にデータベースから返されるディレクティブを追加したいと思います。

<ul> 
    <li gridster-item="item" ng-repeat="item in gridsterItems"> 
     {{ item.directive }} // Returns <clock-widget></clock-widget> and print it to the screen, but it dont run the directive and doesn't display. 
    </li> 
</ul> 

は、今では正しい値を返し、画面上に文字列を表示が、私はそれを指示clockWidgetを実行したいです。

app.directive('clockWidget', function() { 
return { 
    replace: true, 
    template: 'Yups, I am the clockwidget', 
}; 
}); 

インターネット上では$ compileについて読んでいますが、私は見つけられません。あなたが覗いてくれたら助けてくれることを願っています。

ありがとうございます!

答えて

2

はい、$compileが必要です。 documentationを参照してください。

ライブサンプルのjsfiddleです。

angular.module('ExampleApp', []) 
 
    .controller('ExampleController', function($scope) { 
 
    $scope.directives = ["<directive-one></directive-one>", "<directive-two val='inputVal'></directive-two>"]; 
 
    }) 
 
    .directive('compileDirective', function($compile) { 
 
    return { 
 
     restrict: "E", 
 
     replace: true, 
 
     link: function(scope, element, attr) { 
 
     scope.$watch(function() { 
 
      return attr.directive; 
 
     }, function(val) { 
 
      element.html(""); 
 
      if (val) { 
 
      var directive = $compile(angular.element(val))(scope); 
 
      element.append(directive); 
 
      } 
 
     }); 
 
     } 
 
    }; 
 
    }) 
 
//Directives for example 
 
    .directive('directiveOne', function($compile) { 
 
    return { 
 
     replace: true, 
 
     template: "<div>i'm directive one</div>" 
 
    }; 
 
    }) 
 
    .directive('directiveTwo', function($compile) { 
 
    return { 
 
     replace: true, 
 
     scope:{val:"="}, 
 
     template: "<div>i'm directive two with val={{val}}</div>" 
 
    }; 
 
    }) 
 
    .directive('directiveThree', function($compile) { 
 
    return { 
 
     replace: true, 
 
     scope:{val:"="}, 
 
     template: "<div>i'm directive three</div>" 
 
    }; 
 
    });
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script> 
 
<div ng-app="ExampleApp"> 
 
    <div ng-controller="ExampleController"> 
 
    <select ng-model="selectDirective" ng-options="dir for dir in directives"> 
 
    </select> 
 
    <input ng-model="inputVal"> 
 
    <compile-directive directive="{{selectDirective}}"></compile-directive> 
 
    <compile-directive directive="<directive-three></directive-three>"></compile-directive> 
 
    </div> 
 
</div>

関連する問題