You sir, deserve a gold medal for this, thanks you SO much!!
On Saturday, December 14, 2013 at 2:13:13 AM UTC+1, Daniel Tabuenca wrote:
>
> So here is how you could programatically add a directive in a relatively
> clean way:
>
> app.controller('MainCtrl', function($scope) {
> $scope.numbers=[1,2,3,4,5,6];
> });
>
> app.directive('myRepeat', function($compile){
> return {
> //High priority means it will execute first
> priority: 5000,
> //Terminal prevents compilation of any other directive on first pass
> terminal: true,
> compile: function(element, attrs){
> //Add ng-repeat to the dom
> attrs.$set('ngRepeat', attrs.myRepeat);
>
> //Now that we added ng-repeat to the element, proceed with compilation
> //but skip directives with priority 5000 or above to avoid infinite
> //recursion (we don't want to compile ourselves again)
> var compiled = $compile(element, null, 5000);
> return function(scope){
> //When linking just delegate to the link function returned by the new
> //compile
> compiled(scope);
> }
> }
> }
> })
>
> Used like this:
>
> <body ng-controller="MainCtrl">
> <ul>
> This list is generated by a "my-repeat" directive which just
> programatically adds
> the ""ng-repeat" to the li.
> <li my-repeat="number in numbers">{{number}}</li>
> </ul>
> </body>
>
> In this case this is just a simple use of the technique to illustrate how
> you could do it. I am just translating a “my-repeat” directive and adding
> an ‘ng-repeat’ directive dynamically with the same expression. You could
> obviously modify this example to suit your needs by adding different
> directive attributes depending on the values of certain conditions.
>
> The code above has the following benefits:
>
> - Nothing is recompiled (we simply pause compilation, alter dom and
> then continue where we left off
> - No crazy manipulation or cloning of dom (I’ve seen people attempt
> this where they use clone functions or transclude things weird, the dom
> here is untouched (other than adding attributes to it)
> - The original directive’s attribute remains in the dom so you can see
> it.
>
> I’ve tried to comment the code to explain what it’s doing, but there might
> be some advanced topics there that may not be familiar to you unless you
> are very experienced with directives.
>
> Let me know if you want me to explain
>
> Here is the plunkr to play with:
>
> <http://plnkr.co/edit/6jqeFiuaNhmk2YdJp2Sd?p=preview>
> http://plnkr.co/edit/6jqeFiuaNhmk2YdJp2Sd?p=preview
>
--
You received this message because you are subscribed to the Google Groups
"AngularJS" group.
To unsubscribe from this group and stop receiving emails from it, send an email
to [email protected].
To post to this group, send email to [email protected].
Visit this group at http://groups.google.com/group/angular.
For more options, visit https://groups.google.com/d/optout.