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

时间:2013-09-05 13:33:47

标签: javascript angularjs angularjs-directive

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

<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. 显示和隐藏元素。
  3. 帮助?

1 个答案:

答案 0 :(得分:1)

你可以试试这个:

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

您也可以这样做:

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

另一个Plunker here