0

In this plunk I'm trying to obtain in a directive an array with values entered in a list of <li> within the directive declaration.

Given this directive declaration:

<directive>
  <ul>
    <li id="0">xxx 0</li>        
    <li id="1">xxx 1</li>        
    <li id="2">xxx 2</li>        
  </ul>
</directive>

The array should return something like this:

scope.array = [ {id:0, name: "xxx 0"}, {id:1, name: "xxx 1"}, {id:2, name: "xxx 2"} ];

This is my attempt (that doesn't work):

angular.module('app', []);

angular.module('app')
.directive('directive', function() {
    var directive = {};
    directive.restrict = 'AE';
    directive.template = "<div>{{array}}</div>";
    directive.scope = true;
    directive.link = function(scope, element, attrs) {
        scope.array = element.find("ul")[0].children;
    };
    return directive;

});
1
  • You're just setting the array to the list of li elements. You'll need to go through each one and pull out the id attribute and the content, create the object, and push it to the array. I must say this is a strange thing to write a directive for, but hey, party on. Commented Nov 3, 2016 at 22:49

1 Answer 1

1

here is the updated plnkr http://plnkr.co/edit/QtNkOGvLMdu3w6BS3tlB?p=preview

You can see the expected array in the template.

Required JS code:

angular.module('app', []);

angular.module('app')
.directive('directive', function() {
    var directive = {};
    directive.restrict = 'AE';
    directive.scope = true;
    directive.link = function(scope, element, attrs) {
      var newArray = [];
      angular.forEach(element.find('ul')[0].children, function(val) {
        newArray.push({id: val.id, name: val.innerHTML});
      });
      scope.array = newArray;
    };
    directive.template = "<div><pre>{{array|json}}</pre><span ng-transclude></span></div>";
    directive.transclude = true;
    return directive;

});
Sign up to request clarification or add additional context in comments.

3 Comments

you should't change the directive.template, it should only show the array, not the list
Since the occurence of some html tags inside directive, your template '<div>{{array}}</div>' replaces '<ul><li id="0">xxx 0</li><li id="1">xxx 1</li><li id="2">xxx 2</li></ul>' unless you are not using 'transclude = true' and '<span ng-transclude></span>' in your directive.
If you want only the array then you can add display: none to the span tag '<span style='display:none' ng-transclude></span>'. Because ul, li tag should be there to form array

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.