简体   繁体   中英

How can I parse an attribute directive which has multiple values?

I'd like to implement a directive that lets me define a list of animals on an element. If the user likes all of those animals, I want to show the element; otherwise, I want to hide it. Ideally, I'd like it to look like this:

<div animals="cat dog horse"></div>

As you can see, the animals are space-separated, similar to how you can define an element's class with multiple values.

My proposed logic for the directive:

app.directive('animals ', function(userService) {
    return {
        restrict: 'A',
        link: function (scope, element, attrs) {
            // how to parse the attribute and get an array of animal strings?
            var animalsArray = ... ?

            if (userService.likesAllAnimals(animalsArray))
            {
              // show element
            }
            else
            {
              // hide element
            }
        }
    };
});

But I'm lost as to how to:

  1. Parse the animals attribute and derive animalsArray from it.
  2. Show and hide the element.

Help?

You can try this:

app.directive('animals', function(userService) {
  return {
    restrict: 'A',
    link: function (scope, element, attrs) {
      var animals = attrs.animals.split(' ');

      if (userService.likesAllAnimals(animals))
        element.css('display', 'block');
      else
        element.css('display', 'none');
    }
  };
});

Plunker here .

You can do this as well:

app.directive('animals', function(userService, $parse) {
  return {
    restrict: 'A',
    link: function (scope, element, attrs) {
      var animals = $parse(attrs.animals)(scope);

      if (userService.likesAllAnimals(animals))
        element.css('display', 'block');
      else
        element.css('display', 'none');
    }
  };
});

And now you can pass an actual array to the directive:

<div animals="['cat','dog','horse']">

or

<div ng-init="list=['cat','dog','horse']" animals="list">

Another Plunker here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM