gpt4 book ai didi

javascript - 用于替换文本的 Angularjs 指令

转载 作者:行者123 更新时间:2023-11-28 15:35:47 25 4
gpt4 key购买 nike

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

范围包括来自数据库的记录。我想更改它们匹配 humanReadable 数组。

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 is here

最佳答案

正如 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 数组来概括它,假设您可能会发现它有用,而不是使用单独的数组。

关于javascript - 用于替换文本的 Angularjs 指令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25667560/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com