繁体   English   中英

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

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

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

<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">

这里的另一个柱塞。

暂无
暂无

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

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