AngularJS: apply filter to ngStyle

Good day to all!

I have a problem understanding AngularJS. Can I use my own filter in the ngStyle directive? Why can't it change the opacity of the span tag at the same time when I change the value to the input (but it changes the value in the markup)? How can I implement this behavior without using the control area directly?

My source 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; }; }); })(); 

My code in JSFiddle: http://jsfiddle.net/zkdkLac3/

+5
source share
1 answer

Answering a general question, yes, you can usually use a user-created filter in common angular expressions. You may have problems with ng-attr due to a parsing error (probably an error in the angular parser). You can still use filters in ng-attr with

 <span ng-style="{ 'opacity': (slider | opacity) }">TEXT</span> 

ng-attr , although most useful for binding to style objects directly

 <span ng-style="sliderStyle">TEXT</span> 

You can also customize the style using

 <span style="opacity: {{slider|opacity}}">TEXT</span> 

with below filter :

 app.filter('opacity', function () { return function (input) { return 0.1 * input; }; }); 

Working jsfiddle

Depending on which solution is better, it mainly depends on where you plan to reuse things. Filters are available in all scope s, but this, in particular, may make sense only for this controller. Remember that reuse can be done using directives (which may have a controller).

+14
source

Source: https://habr.com/ru/post/1205381/


All Articles