简体   繁体   English

如何解析具有多个值的属性指令?

[英]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. 解析animals属性并从中派生animalsArray
  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 . 这里的另一个柱塞。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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