用于替换文本的 Angularjs 指令

Angularjs directive for replacing text

本文关键字:Angularjs 指令 文本 替换 用于      更新时间:2023-09-26

我是angularjs的新手,我想创建一个指令来更改文本以使人类可读。

范围包括来自数据库的记录。我想更改它们与人类可读数组匹配。

angular.module('app', [])
    .directive("humanReadable", function () {
        return {
            restrict: "A",
            replace: true
        }
    });
   var humanReadable= [{
        text: "first_name",
        replace: "First Name"
    }, 
    {
        text: "last_name",
        replace: "Last Name"
    }];
function MyCtrl($scope) {   
    $scope.comesFromDatabase = ["first_name", "last_name"];
}

我的 HTML 是这样的。

<div ng-app="app">
    <div ng-controller="MyCtrl">
        <ul>
            <li ng-repeat="item in comesFromDatabase">{{item}} - 
                <span human-readable="item"></span>
            </li>
        </ul>
    </div>
</div>

JSFIDDLE 在这里

正如Martinspire所提到的,最好使用如下所示的过滤器 -

angular.module('myapp')
    .filter('humanReadable', [function () {
        return function (str) {
            return str.split("_").join(" ").replace(/([^ ])([^ ]*)/gi,function(v,v1,v2){ return v1.toUpperCase()+v2; });
        };
    }]);

如果你只想要指令,对上面的代码做了一些修改,它看起来像这样 -

 angular.module('myapp')
        .directive('humanReadable', function () {
            return {
                restrict: 'A',
                link: function (scope, element, attrs) {
                    element.html(attrs.humanReadable.split("_").join(" ").replace(/([^ ])([^ ]*)/gi,function(v,v1,v2){ return v1.toUpperCase()+v2; }));
                }
            };
        });

编辑:我已经完成了它,没有使用您的humamReadable数组来概括它,假设您可能会发现它很有用,而不是使用单独的数组。

angular.module('app', [])
    .directive("humanReadable", function () {
    return {
        restrict: "A",
        scope: {
            items: '=',
            humanReadable: '='
        },
        link: function (scope, element, attrs) {
            scope.items.forEach(function (item, i) {
                if (item.text === scope.humanReadable) {
                    element.text(item.replace);
                }
            });
        }
    }
});

演示:http://jsfiddle.net/vhbg6104/4/

更好的方法是使用自定义过滤器。您可以在文档 https://docs.angularjs.org/guide/filter 或 api https://docs.angularjs.org/api/ng/filter/filter 中阅读有关它的所有内容你也可以从翻译过滤器中得到一些灵感:https://github.com/angular-translate/angular-translate总之,你可能会这样写:{{item | human-readable}}或像这样写ng-bind<span ng-bind="item | human-readable">

使用这些工具,我相信你可以弄清楚一些事情