简体   繁体   中英

how to apply a filter for an attribute?

Please help solve the problem.

I write custom filter for text. in first case i output myText and apply filter, result is OK

html:

<div ng-app="main4">
  <md-content ng-controller="main4Ctrl">
    <h2 class="md-display-1 ng-binding">Главная страница 3</h2>

    <sapn id="firstCase">{{myText | transform}}</sapn> - it worked
    <hr>
    <span id="secondCase" ng-bind-html="myText"/>      - but it not worked
  </md-content>
</div> 

js:

angular.module('main4', [])
.controller('main4Ctrl', ['$rootScope', '$scope', '$timeout',
  function($rootScope, $scope, $timeout) {
    $scope.myText = 'qWeRtYuIoP';
  }
]).filter('transform',[function(){
  return function(text){
    return transformTetx = text.toLowerCase();
  }
}]);

I need apply this filter for second case

JSFILLDE

You'll need angular sanitize in order to use ng-bind-html

angular.module('main4', ['ngSanitize'])
.controller('main4Ctrl', ['$rootScope', '$scope', '$timeout',
  function($rootScope, $scope, $timeout) {
    $scope.myText = 'qWeRtYuIoP';
  }
]).filter('transform',[function(){
  return function(text){
    return transformTetx = text.toLowerCase();
  }
}]);

<span id="secondCase" ng-bind-html="myText | transform"></span>

I have updated your FIDDLE

Make sure that you use the same version of angular-sanitize.js as of the angular.js . This is very important

If you want to apply your filter from your controller, you can do the following:

Inject the $filter service and call it by using

var transformedData = $filter('transform')(dataToTransform);

or

You can inject transformFilter into your controller and directly use it.

var transformedData2 = transformFilter(dataToTransform);

Angular will automatically recognize that transform is a filter.

You should use ng-bind on the span element instead. Here's the working fiddle

 <div ng-app="main4">
   <md-content ng-controller="main4Ctrl">
   <span id="firstCase">{{myText | transform}}</span> - it worked
   <hr>
   <span id="secondCase" ng-bind="myText | transform"></span>     - but it not worked
</div>

var app = angular.module('main4', []);
app.controller('main4Ctrl', ['$rootScope', '$scope', '$timeout',
   function($rootScope, $scope, $timeout) {
     $scope.myText = 'qWeRtYuIoP';
   }
])
app.filter('transform',[function(){
    return function(text){
        return transformTetx = text.toLowerCase();
    }
}]);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM