AngularJS:为ngStyle应用过滤器 [英] AngularJS: apply filter for ngStyle
问题描述
大家好!
我在了解AngularJS时遇到问题.我可以在ngStyle指令中使用自定义过滤器吗?为什么当我更改输入中的值时它不能同时更改span标签的不透明度(但它会更改标记中的值)?如何在不直接使用控制器作用域的情况下实现此行为?
I have a problem with understanding AngularJS. Can I use my custom filter within ngStyle directive? Why it can't change opacity of span tag at the same time when I change value in input (but it change value in markup)? How I can realize this behaviour without direct using controller scope?
我的原始代码:HTML:
My raw code: HTML:
<div ng-app="app">
<div ng-controller="AppCtrl">
<input type="number" ng-model="slider" max="10" min="1">
<span ng-style="{'opacity': '{{slider | filter}}'}">TEXT</span>
</div>
</div>
JS:
(function () {
angular
.module('app', [])
.controller('AppCtrl', ['$scope', function ($scope) {
$scope.slider = 6;
}])
.filter('filter', function () {
return function (input) {
return 0.1 * input;
};
});
})();
我在JSFiddle上的代码: http://jsfiddle.net/zkdkLac3/
My code at JSFiddle: http://jsfiddle.net/zkdkLac3/
推荐答案
回答一般问题,是的,通常可以在通用角度表达式中使用用户创建的 filter
.您可能由于解析错误(可能是角度解析器中的错误)而导致 ng-attr
出现问题.您仍然可以在 ng-attr
中将过滤器与
Answering the general question, yes, generally you can use an user created filter
in generic angular expressions. You might be having issues with ng-attr
due to a parsing error (probably a bug in the angular parser). You can still use filters in ng-attr
with
<span ng-style="{ 'opacity': (slider | opacity) }">TEXT</span>
尽管
ng-attr
对于直接绑定样式对象最有用
ng-attr
though is most beneficial for binding to style objects directly
<span ng-style="sliderStyle">TEXT</span>
您还可以通过直接使用
<span style="opacity: {{slider|opacity}}">TEXT</span>
使用以下 filter
:
app.filter('opacity', function () {
return function (input) {
return 0.1 * input;
};
});
哪种解决方案更好,主要取决于您打算在哪里重用事物.过滤器可用于所有 scope
,但是特别是对于给定的控制器而言,这一过滤器尤其有意义.不要忘记,重用也可以通过指令(可以有一个控制器)来完成.
Whichever solution is better mainly depends on where you plan to re-use things. Filters are available across all scope
s, but this one in particular might only make sense for a given controller. Don't forget that reuse can be accomplished with directives (which can have a controller) as well.
这篇关于AngularJS:为ngStyle应用过滤器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!