如何解析具有多个值的属性指令
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
}
}
};
});
但是我不知道如何:
- 分析
animals
属性并从中派生animalsArray
。 - 显示和隐藏元素。
帮助?
你可以试试这个:
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">
另一个普伦克在这里。
相关文章:
- 与ng attr myCustomAttribute匹配的自定义属性指令
- 角度属性指令值
- 在angular中的指令中添加属性指令
- AngularJS - 包含嵌套属性指令的内容
- AngularJs 属性指令 2 路绑定
- 防损层,从角度元素指令传递属性指令
- AngularJS :使用角度属性指令将元素包装到自定义模板中
- 角度:在元素指令上添加属性指令
- 如何在 AngularJS 中使用属性本身将可写参数传递给属性指令
- 刷新 Angular 中自定义属性指令的元素
- 使用嵌入时,元素和属性指令之间是否有区别
- AngularJS - 有条件地使用属性指令
- 如何解析具有多个值的属性指令
- AngularJS中多属性指令的编译和链接顺序
- 可能的Angular属性指令错误
- 在ng-repeat中调用angularjs的属性指令
- 在ng-repeat中有条件地添加属性指令
- 如何在自定义属性指令中访问父范围
- 聚合物属性指令
- 将属性指令传递给元素指令