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

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

本文关键字:属性 指令 何解析      更新时间:2023-09-26

>我想实现一个指令,让我在一个元素上定义一个动物列表。如果用户喜欢所有这些动物,我想显示元素;否则,我想隐藏它。理想情况下,我希望它看起来像这样:

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

如您所见,动物是空格分隔的,类似于如何定义具有多个值的元素类。

我为指令提出的逻辑:

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
            }
        }
    };
});

但是我不知道如何:

  1. 分析 animals 属性并从中派生animalsArray
  2. 显示和隐藏元素。

帮助?

你可以试试这个:

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');
    }
  };
});

在这里普朗克。

您也可以这样做:

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');
    }
  };
});

现在你可以将一个实际的数组传递给指令:

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

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

另一个普伦克在这里。