AngularJS output preprocessing

I want to add a preprocessing step in AngularJS before it updates any HTML. For simplicity, let him select all the instances hello.

That is, if we allow $scope.text = "hello world!", we want to somehow have

{{ text }}

evaluate over a cycle $digestin

<b>hello</b> world!

If $scope.textchanged, this will naturally be updated as needed.

How to do it? Preferably, it will be a directive, so any expressions inside will be processed <div boldhello></div>.

+4
source share
1 answer

datasage - . , , hello , :

(function(angular) {
  'use strict';
  angular.module('myFilterApp', [])
    .filter('boldHello', function($sce) {
      return function(input) {
        input = input || '';
        var out = input.replace(/hello/gi, function(text) {
          return '<b>' + text + '</b>';
        });
        return out;
      };
    })
    .controller('MyController', ['$scope', function($scope) {
      $scope.greeting = 'Oh, hello, my friend.';
    }]);
})(window.angular);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<body ng-app="myFilterApp">
  <div ng-controller="MyController">
    <input ng-model="greeting" type="text"><br>
    No filter: {{greeting}}<br>
    Bold: {{greeting | boldHello}}<br>
  </div>
</body>
Hide result

, , ! , Angular HTML ( script), . trustAsHtml, ng-bind-html.

(function(angular) {
  'use strict';
  angular.module('myFilterApp', [])
    .filter('boldHello', function($sce) {
      return function(input) {
        input = input || '';
        var out = input.replace(/hello/gi, function(text) {
          return '<b>' + text + '</b>';
        });
        return $sce.trustAsHtml(out);
      };
    })
    .controller('MyController', ['$scope', function($scope) {
      $scope.greeting = 'Oh, hello, my friend.';
    }]);
})(window.angular);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<body ng-app="myFilterApp">
  <div ng-controller="MyController">
    <input ng-model="greeting" type="text"><br>
    No filter: {{greeting}}<br>
    Bold: <span ng-bind-html="greeting | boldHello"></span><br>
  </div>
</body>
Hide result
+2

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


All Articles