角元素指令如何获取属性值

角元素指令如何获取属性值

问题描述:

我正在使用Angular元素指令为给定项目生成一定数量的星级(评级)。角元素指令如何获取属性值

我创建了一个名为'generateStars'的指令,我在视图中像这样使用它。

<generate-stars amount="3"></generate-stars> 

我不想指令依赖于当前的范围,所以我在想,如果我可以采取在“量”属性,并让我的指示功能中的价值。

这里是一个函数:

angular.module('myapp.directives', []) 

.directive('generateStars', function() { 
    var html = '<i class="fa fa-star"></i>'; 

    return { 
     restrict: 'E', 
     template: html, 
     replace: true 
    }; 
}); 

我找不到任何明显的文档,让我得到我的指示功能里面“量”的值。

任何帮助将不胜感激。谢谢。

我很感谢帮助家伙,但这些解决方案都没能解决我的问题。这就是我最终做的。

angular.module('myApp.directives', []) 

.directive('generateStars', function() { 
    var html = '<i class="fa fa-star" ng-repeat="n in [] | range:roundedAmount"></i>'; 

    return { 
     restrict: 'E', 
     scope: { 
      amount: '=' 
     }, 
     link: function(scope, element, attrs) { 
      scope.roundedAmount = parseInt(scope.amount); 
     }, 
     replace: true, 
     template: html 
    }; 
}) 

.filter('range', function() { 
    return function(input, total) { 
     total = parseInt(total); 
     for (var i=0; i<total; i++) 
      input.push(i); 

     return input; 
    }; 
}); 

您可以使用隔离范围并使用amount值可以作为属性传递,因为您正在这样做。

标记

<generate-stars amount="{{amount}}"></generate-stars> 

控制器

$scope.amount = 3; //passing it through the scope. 

指令

angular.module('myapp.directives', []) 

.directive('generateStars', function() { 
    var html = '<i ng-repeat="i in [1, 2, 3, 4, 5]" class="fa fa-star" ng-if="i>=amount"></i>'; 

    return { 
     restrict: 'E', 
     template: html, 
     replace: true, 
     scope: { 
      amount: '@' //`@` for one way binding. 
     } 
    }; 
}); 

这可以是无隔离范围。基本上你需要在你的指令模板中创建类fa-3x

angular.module('myapp.directives', []) 

.directive('generateStars', function() { 
     return '<i ng-repeat="i in [1, 2, 3, 4, 5]" class="fa fa-star" ng-if="i>='+ attrs.amount +' "></i>' 
    }; 

    return { 
     restrict: 'E', 
     template: html, 
     replace: true 
    }; 
}); 
+0

'fa-3x'用于字体大小,不适用于图标的数量。 – yvesmancera

+0

@ yvesmancera那是我的坏..我更新了我的答案.. –

+0

感谢您的回复。此代码示例不允许我接受HTML元素提供的值,并在我的指令中使用它。我想避免完全使用'范围'。我只想从自定义指令元素的HTML属性中获取值。 – Dan

您可以利用现有的attrs对象在你的指令定义对象的link功能。

angular.module('myapp.directives', []) 
.directive('generateStars', function() { 
    var html = '<i class="fa fa-star"></i>'; 

    return { 
     restrict: 'E', 
     template: html, 
     replace: true, 
     link: function(scope, element, attrs) { 
      /*all attributes passed to directive are available as properties 
       on attrs object*/ 
      console.log(attrs.amount); 
     } 
    }; 
}); 

HTML

<generate-stars amount="3"></generate-stars> 

条件是,当你的指令被渲染,打印在控制台中值3。

+0

我试图在return语句之前使用指令中的“amount”变量。在这种情况下,我需要知道数量等于3,然后生成3个HTML元素返回。 – Dan

+0

我认为你对return语句感到困惑。你基本上返回一个定义对象,同时用角度注册你的自定义指令。它是在将自定义指令代码翻译成浏览器中的html(由'template'引用)之前调用的'link'函数 – Arkantos